(tools: Tool[], modelName: string)
| 133 | |
| 134 | // https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 |
| 135 | function 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 | |
| 179 | function countChatMessageTokens( |
| 180 | modelName: string, |
no test coverage detected