{"name":"@dqbd/tiktoken","version":"1.0.0","license":"MIT","_id":"@dqbd/tiktoken@1.0.0","maintainers":[{"name":"davidduong","email":"david@duong.cz"}],"homepage":"https://github.com/dqbd/tiktoken#readme","bugs":{"url":"https://github.com/dqbd/tiktoken/issues"},"dist":{"shasum":"77f3355351ecda5099a8091224bf30a25f3c1310","tarball":"http://registry-npm.ywwl.com/@dqbd/tiktoken/download/@dqbd/tiktoken-1.0.0.tgz","fileCount":38,"integrity":"sha512-2Bl9JaIXZECFb8AAOPqOV108WEZL+cK7Vn/w8Dhx/XLLJyb02u2LjfsoVL/41eO25xtJvM6sY0sybiKu3PEdMg==","signatures":[{"sig":"MEUCIQC9sOFL46bZ0RQjkZA0RZU4yMYUQVTcUuhKJ1oIYaNFcgIgGvAKmcK5y3VbE+r/Vj0VKt2JjZP5shwCm464RGh++j8=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":7159363,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkEgssACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoLdA//Wrm3MD5G9KmLKuJfAi9b+QWEZTu4hXWJqy6Wn09WjTydcqTD\r\nAI+k7h2/16bsYX0sBKipFmXxws5EDHr4XosoMHXH0Ry8O0dGrBWzRZBF2IzI\r\nLnIQvTa9k9ZZ+61Qf2M0jblTRgjerqZPmRMyNibNPtRaXZE1rm4t2Ylhb2u6\r\nMqBREyl0nhdCtlkrLA+DaUYtFle01zpV1Gg2YJugXvAM2lrCngpTMownjQ9i\r\nDFKtm8H09VIsy1olDf4oGbJa26Ym830T6Io/J2uz2hwSpk4soiwUYVAw5SwG\r\n+D0mcuSFXvAbYJeQE5FnKltPcmmG8Y0MKRVlfm2S3+o/J/QDT23ETCbQKQ9C\r\nbl6RDabULNq5VSBMf37M7LWI7mGGSajVomwli01uHq88ZVuCIJt1+qEQDvhM\r\nsrsbeaUXswaDyMIreqR0GZCwbOyNSaZPo7olhH9HobOlff/Ir9R8RoKJEST3\r\n6GqVd08whXFpP+AfeM75KG4u0PNJ5YrbKK9JTgmas378d77u23f7HXKyGuyt\r\nKtqIajS3VA6YefghwRTHS53IHml8wngARyu6SDhyVEIQfHVK3cBFt6fTdBu8\r\n7hahGAVwIhOSQIZUbPUdhMYnuAyOFfv1bI2WntB8S+yOdqJyiz2BtWlXNsvi\r\nitcbW9SRhU+C+vl4aiH4b4QXC3vZGSjEHRY=\r\n=KdeL\r\n-----END PGP SIGNATURE-----\r\n","size":2960399,"noattachment":false,"key":"/@dqbd/tiktoken/-/@dqbd/tiktoken-1.0.0.tgz"},"main":"tiktoken.cjs","types":"tiktoken.d.ts","exports":{".":{"node":"./tiktoken.cjs","types":"./tiktoken.d.ts","default":"./tiktoken.js"},"./init":{"node":"./init.cjs","types":"./init.d.ts","default":"./init.js"},"./lite":{"node":"./lite/tiktoken.cjs","types":"./lite/tiktoken.d.ts","default":"./lite/tiktoken.js"},"./load":{"node":"./load.cjs","types":"./load.d.ts","default":"./load.js"},"./lite/init":{"node":"./lite/init.cjs","types":"./lite/init.d.ts","default":"./lite/init.js"},"./lite/load":{"node":"./lite/load.cjs","types":"./lite/load.d.ts","default":"./lite/load.js"},"./registry.json":"./registry.json","./tiktoken_bg.wasm":{"types":"./tiktoken_bg.wasm.d.ts","default":"./tiktoken_bg.wasm"},"./encoders/gpt2.json":"./encoders/gpt2.json","./lite/tiktoken_bg.wasm":{"types":"./lite/tiktoken_bg.wasm.d.ts","default":"./lite/tiktoken_bg.wasm"},"./model_to_encoding.json":"./model_to_encoding.json","./encoders/p50k_base.json":"./encoders/p50k_base.json","./encoders/p50k_edit.json":"./encoders/p50k_edit.json","./encoders/r50k_base.json":"./encoders/r50k_base.json","./encoders/cl100k_base.json":"./encoders/cl100k_base.json"},"gitHead":"efe372862d19d2da8b466d0b1432a7344558d978","_npmUser":{"name":"davidduong","email":"david@duong.cz"},"repository":{"url":"git+https://github.com/dqbd/tiktoken.git","type":"git"},"_npmVersion":"9.2.0","description":"Javascript bindings for tiktoken","directories":{},"_nodeVersion":"19.4.0","dependencies":{},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/tiktoken_1.0.0_1678904108350_0.12571044162904843","host":"s3://npm-registry-packages"},"readme":"# ⏳ tiktoken\n\ntiktoken is a [BPE](https://en.wikipedia.org/wiki/Byte_pair_encoding) tokeniser for use with\nOpenAI's models, forked from the original tiktoken library to provide JS/WASM bindings for NodeJS and other JS runtimes.\n\nThis repository contains the following packages:\n\n- `tiktoken` (formally hosted at `@dqbd/tiktoken`): WASM bindings for the original Python library, providing full 1-to-1 feature parity.\n- `js-tiktoken`: Pure JavaScript port of the original library with the core functionality, suitable for environments where WASM is not well supported or not desired (such as edge runtimes). \n\nDocumentation for `js-tiktoken` can be found in [here](https://github.com/dqbd/tiktoken/blob/main/js/README.md). Documentation for the `tiktoken` can be found here below.\n\nThe WASM version of `tiktoken` can be installed from NPM:\n\n```\nnpm install tiktoken\n```\n\n## Usage\n\nBasic usage follows, which includes all the OpenAI encoders and ranks:\n\n```typescript\nimport assert from \"node:assert\";\nimport { get_encoding, encoding_for_model } from \"tiktoken\";\n\nconst enc = get_encoding(\"gpt2\");\nassert(\n  new TextDecoder().decode(enc.decode(enc.encode(\"hello world\"))) ===\n    \"hello world\"\n);\n\n// To get the tokeniser corresponding to a specific model in the OpenAI API:\nconst enc = encoding_for_model(\"text-davinci-003\");\n\n// Extend existing encoding with custom special tokens\nconst enc = encoding_for_model(\"gpt2\", {\n  \"<|im_start|>\": 100264,\n  \"<|im_end|>\": 100265,\n});\n\n// don't forget to free the encoder after it is not used\nenc.free();\n```\n\nIn constrained environments (eg. Edge Runtime, Cloudflare Workers), where you don't want to load all the encoders at once, you can use the lightweight WASM binary via `tiktoken/lite`.\n\n```typescript\nconst { Tiktoken } = require(\"tiktoken/lite\");\nconst cl100k_base = require(\"tiktoken/encoders/cl100k_base.json\");\n\nconst encoding = new Tiktoken(\n  cl100k_base.bpe_ranks,\n  cl100k_base.special_tokens,\n  cl100k_base.pat_str\n);\nconst tokens = encoding.encode(\"hello world\");\nencoding.free();\n```\n\nIf you want to fetch the latest ranks, use the `load` function:\n\n```typescript\nconst { Tiktoken } = require(\"tiktoken/lite\");\nconst { load } = require(\"tiktoken/load\");\nconst registry = require(\"tiktoken/registry.json\");\nconst models = require(\"tiktoken/model_to_encoding.json\");\n\nasync function main() {\n  const model = await load(registry[models[\"gpt-3.5-turbo\"]]);\n  const encoder = new Tiktoken(\n    model.bpe_ranks,\n    model.special_tokens,\n    model.pat_str\n  );\n  const tokens = encoder.encode(\"hello world\");\n  encoder.free();\n}\n\nmain();\n```\n\nIf desired, you can create a Tiktoken instance directly with custom ranks, special tokens and regex pattern:\n\n```typescript\nimport { Tiktoken } from \"../pkg\";\nimport { readFileSync } from \"fs\";\n\nconst encoder = new Tiktoken(\n  readFileSync(\"./ranks/gpt2.tiktoken\").toString(\"utf-8\"),\n  { \"<|endoftext|>\": 50256, \"<|im_start|>\": 100264, \"<|im_end|>\": 100265 },\n  \"'s|'t|'re|'ve|'m|'ll|'d| ?\\\\p{L}+| ?\\\\p{N}+| ?[^\\\\s\\\\p{L}\\\\p{N}]+|\\\\s+(?!\\\\S)|\\\\s+\"\n);\n```\n\nFinally, you can a custom `init` function to override the WASM initialization logic for non-Node environments. This is useful if you are using a bundler that does not support WASM ESM integration.\n\n```typescript\nimport { get_encoding, init } from \"tiktoken/init\";\n\nasync function main() {\n  const wasm = \"...\"; // fetch the WASM binary somehow\n  await init((imports) => WebAssembly.instantiate(wasm, imports));\n\n  const encoding = get_encoding(\"cl100k_base\");\n  const tokens = encoding.encode(\"hello world\");\n  encoding.free();\n}\n\nmain();\n```\n\n## Compatibility\n\nAs this is a WASM library, there might be some issues with specific runtimes. If you encounter any issues, please open an issue.\n\n| Runtime                      | Status | Notes                                                                                      |\n| ---------------------------- | ------ | ------------------------------------------------------------------------------------------ |\n| Node.js                      | ✅     |                                                                                            |\n| Bun                          | ✅     |                                                                                            |\n| Vite                         | ✅     | See [here](#vite) for notes                                                                |\n| Next.js                      | ✅     | See [here](#nextjs) for notes                                                              |\n| Create React App (via Craco) | ✅     | See [here](#create-react-app) for notes                                                    |\n| Vercel Edge Runtime          | ✅     | See [here](#vercel-edge-runtime) for notes                                                 |\n| Cloudflare Workers           | ✅     | See [here](#cloudflare-workers) for notes                                                  |\n| Electron                     | ✅     | See [here](#electron) for notes                                                            |\n| Deno                         | ❌     | Currently unsupported (see [dqbd/tiktoken#22](https://github.com/dqbd/tiktoken/issues/22)) |\n| Svelte + Cloudflare Workers  | ❌     | Currently unsupported (see [dqbd/tiktoken#37](https://github.com/dqbd/tiktoken/issues/37)) |\n\nFor unsupported runtimes, consider using [`js-tiktoken`](https://www.npmjs.com/package/js-tiktoken), which is a pure JS implementation of the tokeniser.\n\n### [Vite](#vite)\n\nIf you are using Vite, you will need to add both the `vite-plugin-wasm` and `vite-plugin-top-level-await`. Add the following to your `vite.config.js`:\n\n```js\nimport wasm from \"vite-plugin-wasm\";\nimport topLevelAwait from \"vite-plugin-top-level-await\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  plugins: [wasm(), topLevelAwait()],\n});\n```\n\n### [Next.js](#nextjs)\n\nBoth API routes and `/pages` are supported with the following `next.config.js` configuration.\n\n```typescript\n// next.config.json\nconst config = {\n  webpack(config, { isServer, dev }) {\n    config.experiments = {\n      asyncWebAssembly: true,\n      layers: true,\n    };\n\n    return config;\n  },\n};\n```\n\nUsage in pages:\n\n```tsx\nimport { get_encoding } from \"tiktoken\";\nimport { useState } from \"react\";\n\nconst encoding = get_encoding(\"cl100k_base\");\n\nexport default function Home() {\n  const [input, setInput] = useState(\"hello world\");\n  const tokens = encoding.encode(input);\n\n  return (\n    <div>\n      <input\n        type=\"text\"\n        value={input}\n        onChange={(e) => setInput(e.target.value)}\n      />\n      <div>{tokens.toString()}</div>\n    </div>\n  );\n}\n```\n\nUsage in API routes:\n\n```typescript\nimport { get_encoding } from \"tiktoken\";\nimport { NextApiRequest, NextApiResponse } from \"next\";\n\nexport default function handler(req: NextApiRequest, res: NextApiResponse) {\n  const encoding = get_encoding(\"cl100k_base\");\n  const tokens = encoding.encode(\"hello world\");\n  encoding.free();\n  return res.status(200).json({ tokens });\n}\n```\n\n### [Create React App](#create-react-app)\n\nBy default, the Webpack configugration found in Create React App does not support WASM ESM modules. To add support, please do the following:\n\n1. Swap `react-scripts` with `craco`, using the guide found here: https://craco.js.org/docs/getting-started/.\n2. Add the following to `craco.config.js`:\n\n```js\nmodule.exports = {\n  webpack: {\n    configure: (config) => {\n      config.experiments = {\n        asyncWebAssembly: true,\n        layers: true,\n      };\n\n      // turn off static file serving of WASM files\n      // we need to let Webpack handle WASM import\n      config.module.rules\n        .find((i) => \"oneOf\" in i)\n        .oneOf.find((i) => i.type === \"asset/resource\")\n        .exclude.push(/\\.wasm$/);\n\n      return config;\n    },\n  },\n};\n```\n\n### [Vercel Edge Runtime](#vercel-edge-runtime)\n\nVercel Edge Runtime does support WASM modules by adding a `?module` suffix. Initialize the encoder with the following snippet:\n\n```typescript\n// @ts-expect-error\nimport wasm from \"tiktoken/lite/tiktoken_bg.wasm?module\";\nimport model from \"tiktoken/encoders/cl100k_base.json\";\nimport { init, Tiktoken } from \"tiktoken/lite/init\";\n\nexport const config = { runtime: \"edge\" };\n\nexport default async function (req: Request) {\n  await init((imports) => WebAssembly.instantiate(wasm, imports));\n\n  const encoding = new Tiktoken(\n    model.bpe_ranks,\n    model.special_tokens,\n    model.pat_str\n  );\n\n  const tokens = encoding.encode(\"hello world\");\n  encoding.free();\n\n  return new Response(`${tokens}`);\n}\n```\n\n### [Cloudflare Workers](#cloudflare-workers)\n\nSimilar to Vercel Edge Runtime, Cloudflare Workers must import the WASM binary file manually and use the `tiktoken/lite` version to fit the 1 MB limit. However, users need to point directly at the WASM binary via a relative path (including `./node_modules/`).\n\nAdd the following rule to the `wrangler.toml` to upload WASM during build:\n\n```toml\n[[rules]]\nglobs = [\"**/*.wasm\"]\ntype = \"CompiledWasm\"\n```\n\nInitialize the encoder with the following snippet:\n\n```javascript\nimport { init, Tiktoken } from \"tiktoken/lite/init\";\nimport wasm from \"./node_modules/tiktoken/lite/tiktoken_bg.wasm\";\nimport model from \"tiktoken/encoders/cl100k_base.json\";\n\nexport default {\n  async fetch() {\n    await init((imports) => WebAssembly.instantiate(wasm, imports));\n    const encoder = new Tiktoken(\n      model.bpe_ranks,\n      model.special_tokens,\n      model.pat_str\n    );\n    const tokens = encoder.encode(\"test\");\n    encoder.free();\n    return new Response(`${tokens}`);\n  },\n};\n```\n\n### [Electron](#electron)\n\nTo use tiktoken in your Electron main process, you need to make sure the WASM binary gets copied into your application package.\n\nAssuming a setup with [Electron Forge](https://www.electronforge.io) and [`@electron-forge/plugin-webpack`](https://www.npmjs.com/package/@electron-forge/plugin-webpack), add the following to your `webpack.main.config.js`:\n\n```javascript\nconst CopyPlugin = require(\"copy-webpack-plugin\");\n\nmodule.exports = {\n  // ...\n  plugins: [\n    new CopyPlugin({\n      patterns: [\n        { from: \"./node_modules/tiktoken/tiktoken_bg.wasm\" },\n      ],\n    }),\n  ],\n};\n```\n\n## Development\n\nTo build the `tiktoken` library, make sure to have:\n- Rust and [`wasm-pack`](https://github.com/rustwasm/wasm-pack) installed.\n- Node.js 18+ is required to build the JS bindings and fetch the latest encoder ranks via `fetch`.\n\nInstall all the dev-dependencies with `yarn install` and build both WASM binary and JS bindings with `yarn build`.\n\n## Acknowledgements\n\n- https://github.com/zurawiki/tiktoken-rs\n","publish_time":1678904108614,"_cnpm_publish_time":1678904108614,"dist-tags":{"alpha":"1.0.7-alpha.0","latest":"1.0.22"}}