MCPcopy Index your code
hub / github.com/continuedev/continue / countToolsTokens

Function countToolsTokens

core/llm/countTokens.ts:135–177  ·  view source on GitHub ↗
(tools: Tool[], modelName: string)

Source from the content-addressed store, hash-verified

133
134// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
135function countToolsTokens(tools: Tool[], modelName: string): number {
136 const count = (value: string) =>
137 encodingForModel(modelName).encode(value).length;
138
139 let numTokens = 12;
140
141 for (const tool of tools) {
142 let functionTokens = count(tool.function.name);
143 if (tool.function.description) {
144 functionTokens += count(tool.function.description);
145 }
146 const props = tool.function.parameters?.properties;
147 if (props) {
148 for (const key in props) {
149 functionTokens += count(key);
150 const fields = props[key];
151 if (fields) {
152 const fieldType = fields["type"];
153 const fieldDesc = fields["description"];
154 const fieldEnum = fields["enum"];
155 if (fieldType && typeof fieldType === "string") {
156 functionTokens += 2;
157 functionTokens += count(fieldType);
158 }
159 if (fieldDesc && typeof fieldDesc === "string") {
160 functionTokens += 2;
161 functionTokens += count(fieldDesc);
162 }
163 if (fieldEnum && Array.isArray(fieldEnum)) {
164 functionTokens -= 3;
165 for (const e of fieldEnum) {
166 functionTokens += 3;
167 functionTokens += typeof e === "string" ? count(e) : 5;
168 }
169 }
170 }
171 }
172 }
173 numTokens += functionTokens;
174 }
175
176 return numTokens + 12;
177}
178
179function countChatMessageTokens(
180 modelName: string,

Callers 1

compileChatMessagesFunction · 0.85

Calls 1

countFunction · 0.85

Tested by

no test coverage detected