Compare commits

..
Author SHA1 Message Date
sharevb 11cfe91ebd feat(new tool): GPT Token Counter
Fix #1334
2025-01-26 13:37:36 +01:00
11 changed files with 1489 additions and 1443 deletions

No files matched your search

+5 -3
View File
@@ -82,7 +82,7 @@ declare module '@vue/runtime-core' {
FormatTransformer: typeof import('./src/components/FormatTransformer.vue')['default']
GitMemo: typeof import('./src/tools/git-memo/git-memo.vue')['default']
'GitMemo.content': typeof import('./src/tools/git-memo/git-memo.content.md')['default']
HarSanitizer: typeof import('./src/tools/har-sanitizer/har-sanitizer.vue')['default']
GptTokenEstimator: typeof import('./src/tools/gpt-token-estimator/gpt-token-estimator.vue')['default']
HashText: typeof import('./src/tools/hash-text/hash-text.vue')['default']
HmacGenerator: typeof import('./src/tools/hmac-generator/hmac-generator.vue')['default']
'Home.page': typeof import('./src/pages/Home.page.vue')['default']
@@ -132,17 +132,19 @@ declare module '@vue/runtime-core' {
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NGrid: typeof import('naive-ui')['NGrid']
NFormItem: typeof import('naive-ui')['NFormItem']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NSpace: typeof import('naive-ui')['NSpace']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
+1 -1
View File
@@ -67,6 +67,7 @@
"figlet": "^1.7.0",
"figue": "^1.2.0",
"fuse.js": "^6.6.2",
"gpt-tokens": "^1.3.13",
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
@@ -115,7 +116,6 @@
"@types/bcryptjs": "^2.4.2",
"@types/crypto-js": "^4.1.1",
"@types/dompurify": "^3.0.5",
"@types/har-format": "^1.2.16",
"@types/jsdom": "^21.0.0",
"@types/lodash": "^4.14.192",
"@types/mime-types": "^2.1.1",
+1298 -993
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,170 @@
<script setup lang="ts">
import { GPTTokens } from 'gpt-tokens';
import JSON5 from 'json5';
import type { supportModelType } from 'gpt-tokens';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { useValidation } from '@/composable/validation';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const models = GPTTokens.supportModels;
const model = useQueryParamOrStorage({ name: 'model', storageName: 'gpt-counter:model', defaultValue: 'gpt-3.5-turbo-1106' });
const systemPrompt = ref('');
const userPrompt = ref('');
const isAdvancedMode = ref(false);
const messagesJsonArray = ref('');
const toolsJsonArray = ref('');
const messagesValidation = useValidation({
source: messagesJsonArray,
rules: [
{
message: 'Invalid "messages" array',
validator: value => value && JSON5.parse(value.trim()),
},
],
});
const toolsValidation = useValidation({
source: toolsJsonArray,
rules: [
{
message: 'Invalid "tools" array',
validator: value => value && JSON5.parse(value.trim()),
},
],
});
const outputTokenCosts = computed(() => {
try {
let messagesArray = [];
let toolsArray = [];
if (isAdvancedMode.value) {
messagesArray = messagesJsonArray.value ? JSON5.parse(messagesJsonArray.value.trim()) : [];
toolsArray = toolsJsonArray.value ? JSON5.parse(toolsJsonArray.value.trim()) : [];
}
else {
if (systemPrompt.value) {
messagesArray.push({ role: 'system', content: systemPrompt.value });
}
if (userPrompt.value) {
messagesArray.push({ role: 'user', content: userPrompt.value });
}
}
if (!messagesArray.length) {
return {
error: '',
usedTokens: '0',
usedUSD: '0',
promptUsedTokens: '0',
completionUsedTokens: '0',
};
}
const tokens = new GPTTokens({
model: model.value as supportModelType,
messages: messagesArray,
tools: toolsArray,
});
return {
error: '',
usedTokens: tokens.usedTokens.toString(),
usedUSD: tokens.usedUSD.toString(),
promptUsedTokens: tokens.promptUsedTokens.toString(),
completionUsedTokens: tokens.completionUsedTokens.toString(),
};
}
catch (e: any) {
return {
error: e.toString(),
usedTokens: '',
usedUSD: '',
promptUsedTokens: '',
completionUsedTokens: '',
};
}
});
</script>
<template>
<div>
<c-select
v-model:value="model"
label-position="left"
label="Model:"
:options="models"
placeholder="Select GPT model"
mb-2
/>
<div flex justify-center>
<n-form-item label="Advanded JSON Mode" label-placement="left">
<n-checkbox v-model:checked="isAdvancedMode" mr-2 />
</n-form-item>
</div>
<c-card v-if="isAdvancedMode" title="Prompts">
<c-input-text
v-model:value="messagesJsonArray"
multiline raw-text
placeholder="Your 'messages' JSON array..."
rows="5"
autofocus
label="Your 'messages' JSON array:"
:validation="messagesValidation"
/>
<c-input-text
v-model:value="toolsJsonArray"
multiline raw-text
placeholder="Your 'tools' JSON array..."
rows="5"
autofocus
label="Your 'tools' JSON array:"
:validation="toolsValidation"
/>
</c-card>
<c-card v-else title="Input JSON(s)">
<c-input-text
v-model:value="systemPrompt"
multiline raw-text
placeholder="Your System Prompt content..."
rows="2"
autofocus
label="Your System Prompt content:"
/>
<c-input-text
v-model:value="userPrompt"
multiline raw-text
placeholder="Your User Prompt content..."
rows="6"
autofocus
label="Your User Prompt content:"
/>
</c-card>
<n-divider />
<c-alert v-if="outputTokenCosts.error">
{{ outputTokenCosts.error }}
</c-alert>
<div v-if="!outputTokenCosts.error">
<n-form-item label="Used Tokens:">
<TextareaCopyable :value="outputTokenCosts.usedTokens" />
</n-form-item>
<n-form-item label="Prompt Tokens:">
<TextareaCopyable :value="outputTokenCosts.promptUsedTokens" />
</n-form-item>
<n-form-item label="Completion Tokens:">
<TextareaCopyable :value="outputTokenCosts.completionUsedTokens" />
</n-form-item>
<n-form-item label="Used USD:">
<TextareaCopyable :value="outputTokenCosts.usedUSD" />
</n-form-item>
</div>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
import { CurrencyDollar } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'GPT Token Estimator',
path: '/gpt-token-estimator',
description: 'OpenAI GPT Token Estimator',
keywords: ['gpt', 'token', 'estimator'],
component: () => import('./gpt-token-estimator.vue'),
icon: CurrencyDollar,
createdAt: new Date('2024-08-15'),
});
-150
View File
@@ -1,150 +0,0 @@
<script setup lang="ts">
import { downloadFile } from './lib/downloadFile';
import { defaultScrubItems, getHarInfo, sanitize } from './lib/har_sanitize';
type ScrubState = Record<ScrubType, Record<string, boolean>>;
type ScrubType =
| 'cookies'
| 'headers'
| 'queryArgs'
| 'postParams'
| 'mimeTypes';
const typeMap: Record<ScrubType, string> = {
cookies: 'Cookies',
mimeTypes: 'Mime Types',
headers: 'Headers',
postParams: 'Post Body Params',
queryArgs: 'Query String Parameters',
};
const defaulScrubState: ScrubState = {
cookies: {},
headers: {},
queryArgs: {},
postParams: {},
mimeTypes: {},
};
const scrubItemsToClean = ref<ScrubState>(defaulScrubState);
function getScrubableItems(input: string): ScrubState {
const rawItems = getHarInfo(input);
const output = { ...defaulScrubState };
Object.entries(rawItems).forEach(([key, items]: [string, string[]]) => {
output[key as ScrubType] = items.reduce(
(acc, curr) => {
if (!curr) {
return acc;
}
acc[curr] = defaultScrubItems.includes(curr);
return acc;
},
{} as Record<string, boolean>,
);
return null;
});
return output;
}
function sanitizeHar(input: string, scrubItems: ScrubState) {
const words = new Set<string>();
Object.entries(scrubItems.cookies).forEach(([key, val]) => {
if (val) {
words.add(key);
}
});
Object.entries(scrubItems.headers).forEach(([key, val]) => {
if (val) {
words.add(key);
}
});
Object.entries(scrubItems.queryArgs).forEach(([key, val]) => {
if (val) {
words.add(key);
}
});
Object.entries(scrubItems.postParams).forEach(([key, val]) => {
if (val) {
words.add(key);
}
});
const mimeTypes = new Set<string>();
Object.entries(scrubItems.mimeTypes).forEach(([key, val]) => {
if (val) {
mimeTypes.add(key);
}
});
return sanitize(input, {
scrubWords: [...words],
scrubMimetypes: [...mimeTypes],
});
}
const file = ref<File | null>(null);
const error = ref('');
function readAsTextAsync(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => resolve(reader.result?.toString() ?? '');
reader.onerror = error => reject(error);
});
}
const harContent = ref('');
async function onFileUploaded(uploadedFile: File) {
file.value = uploadedFile;
harContent.value = await readAsTextAsync(uploadedFile);
error.value = '';
try {
scrubItemsToClean.value = getScrubableItems(harContent.value);
}
catch (e: any) {
error.value = e.toString();
}
}
function processHar() {
downloadFile(sanitizeHar(harContent.value, scrubItemsToClean.value), `sanitized-${file.value?.name}`);
}
</script>
<template>
<div>
<div style="flex: 0 0 100%" mb-3>
<div mx-auto max-w-600px>
<c-file-upload
title="Drag and drop a HAR file here, or click to select a file"
accept=".har" @file-upload="onFileUploaded"
/>
</div>
</div>
<c-alert v-if="error" title="Error">
{{ error }}
</c-alert>
<div v-for="(title, key) in typeMap" :key="key" mb-1>
<c-card v-if="Object.keys(scrubItemsToClean[key]).length" :title="title">
<n-checkbox font-size-5 @update:checked="(allChecked: boolean) => Object.keys(scrubItemsToClean[key]).forEach((name) => scrubItemsToClean[key][name] = allChecked)">
All {{ title }}
</n-checkbox>
<n-space size="large">
<n-checkbox v-for="(checked, name) in scrubItemsToClean[key]" :key="name" v-model:checked="scrubItemsToClean[key][name]" style="width: 150px">
{{ name }}
</n-checkbox>
</n-space>
</c-card>
</div>
<div v-if="!error" mt-3 flex justify-center>
<c-button @click="processHar()">
Sanitize and download
</c-button>
</div>
</div>
</template>
-12
View File
@@ -1,12 +0,0 @@
import { ClearFormatting } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'HAR Sanitizer',
path: '/har-sanitizer',
description: 'HAR Files Sanitizer',
keywords: ['har', 'sanitizer'],
component: () => import('./har-sanitizer.vue'),
icon: ClearFormatting,
createdAt: new Date('2024-06-17'),
});
@@ -1,19 +0,0 @@
export function downloadFile(harOutput: string, name: string) {
const blob = new Blob([harOutput], { type: 'application/json' });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
// Set file name
a.download = name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Clean up by removing the anchor and revoking the URL
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
@@ -1,237 +0,0 @@
/* eslint-disable prefer-regex-literals */
import type { Cookie, Har, Header, Param, QueryString } from 'har-format';
export interface PossibleScrubItems {
headers: string[]
cookies: string[]
queryArgs: string[]
postParams: string[]
mimeTypes: string[]
}
const defaultMimeTypesList = ['application/javascript', 'text/javascript'];
const defaultWordList = [
'Authorization',
'SAMLRequest',
'SAMLResponse',
'access_token',
'appID',
'assertion',
'auth',
'authenticity_token',
'challenge',
'client_id',
'client_secret',
'code',
'code_challenge',
'code_verifier',
'email',
'facetID',
'fcParams',
'id_token',
'password',
'refresh_token',
'serverData',
'shdf',
'state',
'token',
'usg',
'vses2',
'x-client-data',
];
export const defaultScrubItems = [...defaultMimeTypesList, ...defaultWordList];
// The default list of regexes that aren't word dependent
// Uses double list so it matches format of word regex
const defaultRegex = [
[
// Redact signature on JWTs
{
regex: new RegExp(
'\\b(ey[A-Za-z0-9-_=]+)\\.(ey[A-Za-z0-9-_=]+)\\.[A-Za-z0-9-_.+/=]+\\b',
'g',
),
replacement: '$1.$2.redacted',
},
],
];
function buildRegex(word: string) {
return [
{
// [full word]=[capture]
regex: new RegExp(
`([\\s";,&?]+${word}=)([\\w+-_/=#|.%&:!*()\`~'"]+?)(&|\\\\",|",|"\\s|"}}|;){1}`,
'g',
),
replacement: `$1[${word} redacted]$3`,
},
// Set up this way in case "value" isn't directly after "name"
// {
// "name": "[word]",
// "something": "not wanted",
// "value": "[capture]"
// }
{
regex: new RegExp(
`("name": "${word}",[\\s\\w+:"-\\%!*()\`~'.,#]*?"value": ")((?:\\\\"|[^"])*?)(")`,
'g',
),
replacement: `$1[${word} redacted]$3`,
},
// "name" comes after "value"
// {
// "value": "[capture]",
// "something": "not wanted",
// "name": "[word]"
// }
{
regex: new RegExp(
`("value": ")([\\w+-_:&+=#$~/()\\\\.\\,*!|%"\\s;]+)("[,\\s}}]+)([\\s\\w+:"-\\\\%!*\`()~'#.]*"name": "${word}")`,
'g',
),
replacement: `$1[${word} redacted]$3$4`,
},
];
}
function removeContentForMimeTypes(input: string, scrubList: string[]) {
const harJSON = JSON.parse(input);
const entries = harJSON.log.entries;
if (!entries) {
throw new Error('failed to find entries in HAR file');
}
for (const entry of entries) {
const response = entry.response;
if (response && scrubList.includes(response.content.mimeType)) {
response.content.text = `[${response.content.mimeType} redacted]`;
}
}
return JSON.stringify(harJSON, null, 2);
}
export function getHarInfo(input: string): PossibleScrubItems {
const output = {
headers: new Set<string>(),
queryArgs: new Set<string>(),
cookies: new Set<string>(),
postParams: new Set<string>(),
mimeTypes: new Set<string>(),
};
const harJSON: Har = JSON.parse(input);
const entries = harJSON.log.entries;
if (!entries) {
throw new Error('failed to find entries in HAR file');
}
for (const entry of entries) {
const response = entry.response;
response.headers.map((header: Header) => output.headers.add(header.name));
response.cookies.map((cookie: Cookie) => output.cookies.add(cookie.name));
output.mimeTypes.add(response.content.mimeType);
const request = entry.request;
request.headers.map((header: Header) => output.headers.add(header.name));
request.queryString.map((arg: QueryString) =>
output.queryArgs.add(arg.name),
);
request.cookies.map((cookie: Cookie) => output.cookies.add(cookie.name));
if (request.postData) {
request.postData.params?.map((param: Param) =>
output.postParams.add(param.name),
);
}
}
return {
headers: [...output.headers].sort((a, b) => a.localeCompare(b)),
queryArgs: [...output.queryArgs].sort((a, b) => a.localeCompare(b)),
cookies: [...output.cookies].sort((a, b) => a.localeCompare(b)),
postParams: [...output.postParams].sort((a, b) => a.localeCompare(b)),
mimeTypes: [...output.mimeTypes].sort((a, b) => a.localeCompare(b)),
};
}
function getScrubMimeTypes(
options?: SanitizeOptions,
possibleScrubItems?: PossibleScrubItems,
) {
if (options?.allMimeTypes && !!possibleScrubItems) {
return possibleScrubItems.mimeTypes;
}
return options?.scrubMimetypes || defaultMimeTypesList;
}
function getScrubWords(
options?: SanitizeOptions,
possibleScrubItems?: PossibleScrubItems,
) {
let scrubWords = options?.scrubWords || [];
if (options?.allCookies && !!possibleScrubItems) {
scrubWords = scrubWords.concat(possibleScrubItems.cookies);
}
if (options?.allHeaders && !!possibleScrubItems) {
scrubWords = scrubWords.concat(possibleScrubItems.headers);
}
if (options?.allQueryArgs && !!possibleScrubItems) {
scrubWords = scrubWords.concat(possibleScrubItems.queryArgs);
}
if (options?.allPostParams && !!possibleScrubItems) {
scrubWords = scrubWords.concat(possibleScrubItems.postParams);
}
return scrubWords || defaultScrubItems;
}
interface SanitizeOptions {
scrubWords?: string[]
scrubMimetypes?: string[]
allCookies?: boolean
allHeaders?: boolean
allQueryArgs?: boolean
allMimeTypes?: boolean
allPostParams?: boolean
}
export function sanitize(input: string, options?: SanitizeOptions) {
let possibleScrubItems: PossibleScrubItems | undefined;
if (
options?.allCookies
|| options?.allHeaders
|| options?.allMimeTypes
|| options?.allQueryArgs
|| options?.allPostParams
) {
// we have to parse the HAR to get the full list of things we could scrub
possibleScrubItems = getHarInfo(input);
}
// Remove specific mime responses first
input = removeContentForMimeTypes(
input,
getScrubMimeTypes(options, possibleScrubItems),
);
// trim the list of words we are looking for down to the ones actually in the HAR file
const wordList = getScrubWords(options, possibleScrubItems).filter(val =>
input.includes(val),
);
// build list of regexes needed to actually scrub the file
const wordSpecificScrubList = wordList.map(word => buildRegex(word));
const allScrubList = defaultRegex.concat(wordSpecificScrubList);
for (const scrubList of allScrubList) {
for (const scrub of scrubList) {
input = input.replace(scrub.regex, scrub.replacement);
}
}
return input;
}
-18
View File
@@ -1,18 +0,0 @@
export type HashMap = Record<string, string[]>;
export function toHashString(obj: HashMap): string {
const params = new URLSearchParams();
Object.entries(obj).forEach(([key, stringArr]) => {
stringArr.forEach((value) => {
params.append(key, value);
});
});
return `#${params.toString()}`;
}
export function getHashMap(hash: string): HashMap {
const existingParams = new URLSearchParams(hash.replace('#', ''));
return Object.fromEntries(
[...existingParams.keys()].map(key => [key, existingParams.getAll(key)]),
);
}
+3 -10
View File
@@ -2,6 +2,7 @@ import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as emailNormalizer } from './email-normalizer';
import { tool as gptTokenEstimator } from './gpt-token-estimator';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -12,7 +13,6 @@ import { tool as jsonToXml } from './json-to-xml';
import { tool as regexTester } from './regex-tester';
import { tool as regexMemo } from './regex-memo';
import { tool as markdownToHtml } from './markdown-to-html';
import { tool as harSanitizer } from './har-sanitizer';
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
import { tool as numeronymGenerator } from './numeronym-generator';
import { tool as macAddressGenerator } from './mac-address-generator';
@@ -161,19 +161,12 @@ export const toolsByCategory: ToolCategory[] = [
emailNormalizer,
regexTester,
regexMemo,
gptTokenEstimator,
],
},
{
name: 'Network',
components: [
ipv4SubnetCalculator,
ipv4AddressConverter,
ipv4RangeExpander,
macAddressLookup,
macAddressGenerator,
ipv6UlaGenerator,
harSanitizer,
],
components: [ipv4SubnetCalculator, ipv4AddressConverter, ipv4RangeExpander, macAddressLookup, macAddressGenerator, ipv6UlaGenerator],
},
{
name: 'Math',