-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Basic local AI Token management tools #2062
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
grmartin
wants to merge
9
commits into
gchq:master
Choose a base branch
from
grmartin:grmartin/ai-tools
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6df8c10
Adding AI Token Counter
grmartin 233eb3d
Adding AI Category
grmartin 0df7ac0
Making the tokenizer in to a library.
grmartin 8443330
Removing some unneeded comments
grmartin dd583a4
Adding GPT Token Parser display
grmartin 0b913d0
Encoding HTML entities as well as ensuring no script tags slip by
grmartin e6a50df
Lets hope a direct match and replace will satisfy CodeQL
grmartin 4679989
Last attempt to try and satisfy CodeQL
grmartin 6324a3a
Trying to fix the script tag vulnerability
grmartin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// noinspection SpellCheckingInspection | ||
|
||
/** | ||
* @author grmartin [[email protected]] | ||
* @copyright Crown Copyright 2016 | ||
* @license Apache-2.0 | ||
*/ | ||
|
||
const exportModule = (m) => { | ||
return { | ||
countTokens: m.countTokens, // # of tokens | ||
encode: m.encode, // tokens ids | ||
decodeGenerator: m.decodeGenerator, // tokens | ||
}; | ||
}; | ||
|
||
export const defaultValue = Symbol("*"); | ||
|
||
// Tokenizer module constants | ||
const GPT_35_TURBO_TOKENIZER = () => import("gpt-tokenizer/model/gpt-3.5-turbo").then(m => exportModule(m)); | ||
const TEXT_EMBEDDING_ADA_002_TOKENIZER = () => import("gpt-tokenizer/model/text-embedding-ada-002").then(m => exportModule(m)); | ||
const TEXT_EMBEDDING_3_LARGE_TOKENIZER = () => import("gpt-tokenizer/model/text-embedding-3-large").then(m => exportModule(m)); | ||
const TEXT_EMBEDDING_3_SMALL_TOKENIZER = () => import("gpt-tokenizer/model/text-embedding-3-small").then(m => exportModule(m)); | ||
const CODE_DAVINCI_002_TOKENIZER = () => import("gpt-tokenizer/model/code-davinci-002").then(m => exportModule(m)); | ||
const CODE_CUSHMAN_002_TOKENIZER = () => import("gpt-tokenizer/model/code-cushman-002").then(m => exportModule(m)); | ||
const TEXT_DAVINCI_002_TOKENIZER = () => import("gpt-tokenizer/model/text-davinci-002").then(m => exportModule(m)); | ||
const TEXT_DAVINCI_003_TOKENIZER = () => import("gpt-tokenizer/model/text-davinci-003").then(m => exportModule(m)); | ||
const TEXT_DAVINCI_EDIT_001_TOKENIZER = () => import("gpt-tokenizer/model/text-davinci-edit-001").then(m => exportModule(m)); | ||
const CODE_DAVINCI_EDIT_001_TOKENIZER = () => import("gpt-tokenizer/model/code-davinci-edit-001").then(m => exportModule(m)); | ||
const DAVINCI_TOKENIZER = () => import("gpt-tokenizer/model/davinci").then(m => exportModule(m)); | ||
const CURIE_TOKENIZER = () => import("gpt-tokenizer/model/curie").then(m => exportModule(m)); | ||
const BABBAGE_TOKENIZER = () => import("gpt-tokenizer/model/babbage").then(m => exportModule(m)); | ||
const ADA_TOKENIZER = () => import("gpt-tokenizer/model/ada").then(m => exportModule(m)); | ||
|
||
// This mapping returns a Promise that resolves to the correct countTokens function for the model. | ||
export const MODEL_TO_MODULES = { | ||
// cl100k_base models | ||
[defaultValue]: GPT_35_TURBO_TOKENIZER, | ||
"gpt-4": GPT_35_TURBO_TOKENIZER, | ||
"gpt-4-32k": GPT_35_TURBO_TOKENIZER, | ||
"gpt-4-turbo": GPT_35_TURBO_TOKENIZER, | ||
"gpt-4o": GPT_35_TURBO_TOKENIZER, | ||
"gpt-4-0125-preview": GPT_35_TURBO_TOKENIZER, | ||
"gpt-4-1106-preview": GPT_35_TURBO_TOKENIZER, | ||
"gpt-3.5-turbo": GPT_35_TURBO_TOKENIZER, | ||
"gpt-3.5-turbo-16k": GPT_35_TURBO_TOKENIZER, | ||
"gpt-3.5-turbo-instruct": GPT_35_TURBO_TOKENIZER, | ||
"gpt-3.5-turbo-0125": GPT_35_TURBO_TOKENIZER, | ||
"gpt-3.5-turbo-1106": GPT_35_TURBO_TOKENIZER, | ||
"text-embedding-ada-002": TEXT_EMBEDDING_ADA_002_TOKENIZER, | ||
"text-embedding-3-large": TEXT_EMBEDDING_3_LARGE_TOKENIZER, | ||
"text-embedding-3-small": TEXT_EMBEDDING_3_SMALL_TOKENIZER, | ||
|
||
// p50k_base models | ||
"code-davinci-002": CODE_DAVINCI_002_TOKENIZER, | ||
"code-davinci-001": CODE_DAVINCI_002_TOKENIZER, | ||
"code-cushman-002": CODE_CUSHMAN_002_TOKENIZER, | ||
"code-cushman-001": CODE_CUSHMAN_002_TOKENIZER, | ||
"text-davinci-002": TEXT_DAVINCI_002_TOKENIZER, | ||
"text-davinci-003": TEXT_DAVINCI_003_TOKENIZER, | ||
|
||
// p50k_edit models | ||
"text-davinci-edit-001": TEXT_DAVINCI_EDIT_001_TOKENIZER, | ||
"code-davinci-edit-001": CODE_DAVINCI_EDIT_001_TOKENIZER, | ||
|
||
// r50k_base models | ||
"davinci": DAVINCI_TOKENIZER, | ||
"curie": CURIE_TOKENIZER, | ||
"babbage": BABBAGE_TOKENIZER, | ||
"ada": ADA_TOKENIZER, | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
/** | ||
* @author grmartin [[email protected]] | ||
* @copyright Crown Copyright 2016 | ||
* @license Apache-2.0 | ||
*/ | ||
|
||
import Operation from "../Operation.mjs"; | ||
import {defaultValue, MODEL_TO_MODULES} from "../lib/GPTTokenizer.mjs"; | ||
|
||
/** | ||
* Count AI Tokens operation | ||
*/ | ||
class CountAITokens extends Operation { | ||
|
||
/** | ||
* Count AI Tokens constructor | ||
*/ | ||
constructor() { | ||
super(); | ||
|
||
this.name = "Count AI Tokens"; | ||
this.module = "AI"; | ||
this.infoURL = "https://github.com/niieani/gpt-tokenizer"; | ||
this.description = "Counts the number of GPT tokens in the input text using niieani/gpt-tokenizer. Select the model to use the correct encoding."; | ||
this.inputType = "string"; | ||
this.outputType = "string"; | ||
this.args = [ | ||
{ | ||
name: "Model", | ||
type: "option", | ||
value: Object.keys(MODEL_TO_MODULES), | ||
} | ||
]; | ||
} | ||
|
||
/** | ||
* @param {string} input | ||
* @param {Object[]} args | ||
* @returns {string} | ||
*/ | ||
async run(input, args) { | ||
if (!input) return ""; | ||
|
||
const [model] = args; | ||
let countTokensFn; | ||
if (MODEL_TO_MODULES[model]) { | ||
countTokensFn = (await MODEL_TO_MODULES[model]()).countTokens; | ||
} else { | ||
// fallback to default (gpt-3.5-turbo encoding) | ||
countTokensFn = (await MODEL_TO_MODULES[defaultValue]()).countTokens; | ||
} | ||
const tokenCount = countTokensFn(input); | ||
return tokenCount.toString(); | ||
} | ||
|
||
} | ||
|
||
export default CountAITokens; | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
/** | ||
* @author grmartin [[email protected]] | ||
* @copyright Crown Copyright 2016 | ||
* @license Apache-2.0 | ||
*/ | ||
|
||
import Operation from "../Operation.mjs"; | ||
import {defaultValue, MODEL_TO_MODULES} from "../lib/GPTTokenizer.mjs"; | ||
|
||
const pastelColors = [ | ||
"rgba(102,197,204,.4)", | ||
"rgba(246,207,113,.4)", | ||
"rgba(248,156,116,.4)", | ||
"rgba(239,65,70,.4)", | ||
"rgba(220,176,242,.4)", | ||
"rgba(135,197,95,.4)", | ||
"rgba(158,185,243,.4)", | ||
"rgba(254,136,177,.4)", | ||
"rgba(201,219,116,.4)", | ||
"rgba(139,224,164,.4)", | ||
"rgba(180,151,231,.4)", | ||
]; | ||
|
||
/** | ||
* Count AI Tokens operation | ||
*/ | ||
class ParseAITokens extends Operation { | ||
|
||
/** | ||
* Parse AI Tokens constructor | ||
*/ | ||
constructor() { | ||
super(); | ||
|
||
this.name = "Parse AI Tokens"; | ||
this.module = "AI"; | ||
this.infoURL = "https://github.com/niieani/gpt-tokenizer"; | ||
this.description = "Parses the GPT tokens in the input text using niieani/gpt-tokenizer. Select the model to use the correct encoding."; | ||
this.inputType = "string"; | ||
this.outputType = "html"; | ||
this.args = [ | ||
{ | ||
name: "Model", | ||
type: "option", | ||
value: Object.keys(MODEL_TO_MODULES), | ||
}, | ||
{ | ||
name: "Show Token IDs", | ||
type: "boolean", | ||
value: false | ||
} | ||
]; | ||
} | ||
|
||
/** | ||
* @param {string} input | ||
* @param {Object[]} args | ||
* @returns {string} | ||
*/ | ||
async run(input, args) { | ||
if (!input) return ""; | ||
|
||
const [model, showIds] = args; | ||
let fns; | ||
if (MODEL_TO_MODULES[model]) { | ||
fns = (await MODEL_TO_MODULES[model]()); | ||
} else { | ||
// fallback to default (gpt-3.5-turbo encoding) | ||
fns = (await MODEL_TO_MODULES[defaultValue]()); | ||
} | ||
|
||
const encodedTokens = fns.encode(input); // IDs | ||
|
||
let displayTokens; | ||
if (showIds) { | ||
displayTokens = encodedTokens.map((x)=> x.toString()); | ||
} else { | ||
const tokens = []; | ||
for (const token of fns.decodeGenerator(encodedTokens)) { | ||
tokens.push(token); | ||
} | ||
displayTokens = tokens; | ||
} | ||
|
||
return this.format(input, displayTokens); | ||
|
||
}; | ||
|
||
/** | ||
* Format HTML | ||
* @param {string} input | ||
* @param {string[]} tokens | ||
*/ | ||
format(input, tokens) { | ||
|
||
const tokenHtml = tokens.map((t, i) => { | ||
const tok = | ||
t.replace(/[\u00A0-\u9999<>&]/g, i => "&#"+i.charCodeAt(0)+";") | ||
.replaceAll(" ", "\u00A0") | ||
.replaceAll("\n", "<newline>"); | ||
|
||
const css = [ | ||
`background-color:${pastelColors[i % pastelColors.length]}`, | ||
"padding: 0 0", | ||
"border-radius: 3px", | ||
"margin-right: 0", | ||
"margin-bottom: 4px", | ||
"display: 'inline-block'", | ||
"height: 1.5em" | ||
]; | ||
|
||
return `<span style="${css.join(";")}">${tok}</span>`; | ||
}); | ||
|
||
return this.replaceSpacesOutsideTags(` | ||
<div style="padding: 0; margin: 0"> | ||
<h1>Tokens</h1> | ||
<p style="font-family: monospace"> | ||
${tokenHtml.join("")} | ||
</p> | ||
<hr /> | ||
<ul style="list-style: none; padding-left: 0"> | ||
<li><strong>Characters:</strong> ${input.length}</li> | ||
<li><strong>Tokens:</strong> ${tokens.length}</li> | ||
</ul> | ||
</div>` | ||
); | ||
}; | ||
|
||
/** | ||
* Replace spaces outside HTML tags and sanitize <script> tags. | ||
* @param {string} htmlString - The input HTML string. | ||
* @returns {string} - The sanitized and formatted HTML string. | ||
*/ | ||
replaceSpacesOutsideTags(htmlString) { | ||
return htmlString | ||
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/ig, "") | ||
Check failureCode scanning / CodeQL Bad HTML filtering regexp High
This regular expression does not match script end tags like </script >.
|
||
.replace(/(<[^>]*?>)|(\s+)/g, function(match, tag, spaces) { | ||
if (tag) { | ||
return tag; | ||
} else if (spaces) { | ||
return ""; | ||
} | ||
}) | ||
Comment on lines
+136
to
+144
Check failureCode scanning / CodeQL Incomplete multi-character sanitization High
This string may still contain
<script Error loading related location Loading |
||
.replace(/[\r\n]/g, ""); | ||
} | ||
|
||
} | ||
|
||
export default ParseAITokens; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Incomplete multi-character sanitization High