File tree Expand file tree Collapse file tree 3 files changed +29
-2
lines changed
Expand file tree Collapse file tree 3 files changed +29
-2
lines changed Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ import { streamSSE } from "hono/streaming"
66import { awaitApproval } from "~/lib/approval"
77import { checkRateLimit } from "~/lib/rate-limit"
88import { state } from "~/lib/state"
9+ import { getTokenCount } from "~/lib/tokenizer"
910import {
1011 createChatCompletions ,
1112 type ChatCompletionChunk ,
@@ -89,3 +90,22 @@ export async function handleCompletion(c: Context) {
8990const isNonStreaming = (
9091 response : Awaited < ReturnType < typeof createChatCompletions > > ,
9192) : response is ChatCompletionResponse => Object . hasOwn ( response , "choices" )
93+
94+ export async function handleCountTokens ( c : Context ) {
95+ const anthropicPayload = await c . req . json < AnthropicMessagesPayload > ( )
96+ consola . debug ( "Count tokens request:" , JSON . stringify ( anthropicPayload ) )
97+
98+ // Convert Anthropic format to OpenAI format for token counting
99+ const openAIPayload = translateToOpenAI ( anthropicPayload )
100+
101+ // Calculate tokens using our existing tokenizer
102+ const tokenCounts = getTokenCount ( openAIPayload . messages )
103+
104+ // Return in Anthropic format
105+ const response = {
106+ input_tokens : tokenCounts . input ,
107+ }
108+
109+ consola . debug ( "Token count response:" , JSON . stringify ( response ) )
110+ return c . json ( response )
111+ }
Original file line number Diff line number Diff line change @@ -2,7 +2,7 @@ import { Hono } from "hono"
22
33import { forwardError } from "~/lib/error"
44
5- import { handleCompletion } from "./handler"
5+ import { handleCompletion , handleCountTokens } from "./handler"
66
77export const messageRoutes = new Hono ( )
88
@@ -13,3 +13,11 @@ messageRoutes.post("/", async (c) => {
1313 return await forwardError ( c , error )
1414 }
1515} )
16+
17+ messageRoutes . post ( "/count_tokens" , async ( c ) => {
18+ try {
19+ return await handleCountTokens ( c )
20+ } catch ( error ) {
21+ return await forwardError ( c , error )
22+ }
23+ } )
Original file line number Diff line number Diff line change @@ -29,4 +29,3 @@ server.route("/v1/embeddings", embeddingRoutes)
2929
3030// Anthropic compatible endpoints
3131server . route ( "/v1/messages" , messageRoutes )
32- server . post ( "/v1/messages/count_tokens" , ( c ) => c . json ( { input_tokens : 1 } ) )
You can’t perform that action at this time.
0 commit comments