Skip to content

Commit 7c6828e

Browse files
committed
count tokens from messages in Anthropic format
1 parent b7189d6 commit 7c6828e

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

src/routes/messages/handler.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { streamSSE } from "hono/streaming"
66
import { awaitApproval } from "~/lib/approval"
77
import { checkRateLimit } from "~/lib/rate-limit"
88
import { state } from "~/lib/state"
9+
import { getTokenCount } from "~/lib/tokenizer"
910
import {
1011
createChatCompletions,
1112
type ChatCompletionChunk,
@@ -89,3 +90,22 @@ export async function handleCompletion(c: Context) {
8990
const 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+
}

src/routes/messages/route.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { Hono } from "hono"
22

33
import { forwardError } from "~/lib/error"
44

5-
import { handleCompletion } from "./handler"
5+
import { handleCompletion, handleCountTokens } from "./handler"
66

77
export 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+
})

src/server.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,3 @@ server.route("/v1/embeddings", embeddingRoutes)
2929

3030
// Anthropic compatible endpoints
3131
server.route("/v1/messages", messageRoutes)
32-
server.post("/v1/messages/count_tokens", (c) => c.json({ input_tokens: 1 }))

0 commit comments

Comments
 (0)