{"name":"@dqbd/tiktoken","version":"0.2.1","license":"Apache-2.0","_id":"@dqbd/tiktoken@0.2.1","maintainers":[{"name":"davidduong","email":"david@duong.cz"}],"dist":{"shasum":"22a673e401a2b6ffc9516d044011f9f54eff0994","tarball":"http://registry-npm.ywwl.com/@dqbd/tiktoken/download/@dqbd/tiktoken-0.2.1.tgz","fileCount":28,"integrity":"sha512-Nw9Swn37xZLAvz64qA3tTxy4yJLMhYDj7dWS6uSoHkUJxTn+BcYA+r06O36Q3Jya52b3SvK/LDXzl1dVeHqrew==","signatures":[{"sig":"MEQCIBMNHyR2H0fNLXrNOV12g6+lUU8vSJ/VAx2SdA+L+SQ9AiBO3gLhrlUu6BoCd5DU6ujCC5YH0dykU0uh19XYBaBSbQ==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":12446943,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJj8jH+ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmq34A/+PGxuOAONInUTqBJWqcHO2rGTC52sfJRNK0L7L6T1futXMKWi\r\nTUAdokrnnENd/FK32Ro7L2TnFzIpPMYgw+TxSKLn+okKcPQOPycbyufBwJYg\r\nrtpdCS5KbUUWLxHf/PgtIAqBrr31CH6QQaKVWdBNVLDfQz0/mLqotB6Izy8l\r\nrxQk04lkll3hYfsSYzmscJTD9M2pHaG2qV2LAAyiT5lX41VTy+0tQJdfZYoQ\r\nAW1YpFl8PfIeJhOnsu/ThwJDf97uUs6Jto87MhZeO8BYDRULT5hIdw8Ge0Pi\r\nLbzW1mAvmhOVIBQH2KZAPUn+KH89wgqUDx1Jql/3PYz3bbI15y04uNtm4eLw\r\nJs3+94K589PwE4+Kd5OlTwuv6S1EDPs+zjz7TOTz5msFaphmr0lrLI4S5yJo\r\ntIoDb5dhv/SsvCs1dSuoIFbjY2DzLiO7/ZCCJ6WrqgEyDVWvn/IEo1pE8ie3\r\nUdmlzVVD3q3Ipxhi5P9NmeRX7PLIqYfjIRPJM6X2IB1l2zz5LKJNPAHGdAma\r\n5zVRyfn2rbKh7vNCpfH+vifPMDvKFz42w1QekjprSym6r1fqkp6Q3tPqsxEM\r\nZk4XDf0oDZeycA9xhUK7vdCSAqKJ1y3ZjVJHeD/Ey56o+98fb5IJYPgEH0r7\r\nmYS6cBLWX+EaW7DQCNtqNy1DfpylAhCVFHE=\r\n=Eh78\r\n-----END PGP SIGNATURE-----\r\n","size":5302582,"noattachment":false,"key":"/@dqbd/tiktoken/-/@dqbd/tiktoken-0.2.1.tgz"},"main":"dist/node/_tiktoken.js","types":"dist/node/_tiktoken.d.ts","browser":"dist/web/_tiktoken.js","scripts":{"build":"rm -rf dist/ && npm run build:node && npm run build:bundler && npm run build:web","build:web":"wasm-pack build --target no-modules --release --out-dir dist/web && rm dist/web/.gitignore","build:node":"wasm-pack build --target nodejs --release --out-dir dist/node && rm dist/node/.gitignore","build:bundler":"wasm-pack build --target bundler --release --out-dir dist/bundler && rm dist/bundler/.gitignore"},"_npmUser":{"name":"davidduong","email":"david@duong.cz"},"repository":{"url":"https://github.com/dqbd/tiktoken","type":"git"},"description":"Javascript bindings for tiktoken","directories":{},"licenseText":"MIT License\n\nCopyright (c) 2022 OpenAI, Shantanu Jain\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","_hasShrinkwrap":false,"devDependencies":{},"_npmOperationalInternal":{"tmp":"tmp/tiktoken_0.2.1_1676816893992_0.32642862992952915","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":1676816894301,"_cnpm_publish_time":1676816894301,"dist-tags":{"alpha":"1.0.7-alpha.0","latest":"1.0.22"}}