gateway.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import { Hono, Context, Next } from "hono"
  2. import { Resource } from "sst"
  3. import { generateText, streamText } from "ai"
  4. import { createAnthropic } from "@ai-sdk/anthropic"
  5. import { createOpenAI } from "@ai-sdk/openai"
  6. import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
  7. import { type LanguageModelV2Prompt } from "@ai-sdk/provider"
  8. import { type ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"
  9. type Env = {}
  10. const auth = async (c: Context, next: Next) => {
  11. const authHeader = c.req.header("authorization")
  12. if (!authHeader || !authHeader.startsWith("Bearer ")) {
  13. return c.json(
  14. {
  15. error: {
  16. message: "Missing API key.",
  17. type: "invalid_request_error",
  18. param: null,
  19. code: "unauthorized",
  20. },
  21. },
  22. 401,
  23. )
  24. }
  25. const apiKey = authHeader.split(" ")[1]
  26. // Replace with your validation logic
  27. if (apiKey !== Resource.OPENCODE_API_KEY.value) {
  28. return c.json(
  29. {
  30. error: {
  31. message: "Invalid API key.",
  32. type: "invalid_request_error",
  33. param: null,
  34. code: "unauthorized",
  35. },
  36. },
  37. 401,
  38. )
  39. }
  40. await next()
  41. }
  42. export default new Hono<{ Bindings: Env }>()
  43. .get("/", (c) => c.text("Hello, world!"))
  44. .post("/v1/chat/completions", auth, async (c) => {
  45. try {
  46. const body = await c.req.json<ChatCompletionCreateParamsBase>()
  47. console.log(body)
  48. const model = (() => {
  49. const [provider, ...parts] = body.model.split("/")
  50. const model = parts.join("/")
  51. if (provider === "anthropic" && model === "claude-sonnet-4") {
  52. return createAnthropic({
  53. apiKey: Resource.ANTHROPIC_API_KEY.value,
  54. })("claude-sonnet-4-20250514")
  55. }
  56. if (provider === "openai" && model === "gpt-4.1") {
  57. return createOpenAI({
  58. apiKey: Resource.OPENAI_API_KEY.value,
  59. })("gpt-4.1")
  60. }
  61. if (provider === "zhipuai" && model === "glm-4.5-flash") {
  62. return createOpenAICompatible({
  63. name: "Zhipu AI",
  64. baseURL: "https://api.z.ai/api/paas/v4",
  65. apiKey: Resource.ZHIPU_API_KEY.value,
  66. })("glm-4.5-flash")
  67. }
  68. throw new Error(`Unsupported provider: ${provider}`)
  69. })()
  70. const requestBody = transformOpenAIRequestToAiSDK()
  71. return body.stream ? await handleStream() : await handleGenerate()
  72. async function handleStream() {
  73. const result = await streamText({
  74. model,
  75. ...requestBody,
  76. })
  77. const encoder = new TextEncoder()
  78. const stream = new ReadableStream({
  79. async start(controller) {
  80. const id = `chatcmpl-${Date.now()}`
  81. const created = Math.floor(Date.now() / 1000)
  82. try {
  83. for await (const chunk of result.fullStream) {
  84. // TODO
  85. //console.log("!!! CHUCK !!!", chunk);
  86. switch (chunk.type) {
  87. case "text-delta": {
  88. const data = {
  89. id,
  90. object: "chat.completion.chunk",
  91. created,
  92. model: body.model,
  93. choices: [
  94. {
  95. index: 0,
  96. delta: {
  97. content: chunk.text,
  98. },
  99. finish_reason: null,
  100. },
  101. ],
  102. }
  103. controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
  104. break
  105. }
  106. case "reasoning-delta": {
  107. const data = {
  108. id,
  109. object: "chat.completion.chunk",
  110. created,
  111. model: body.model,
  112. choices: [
  113. {
  114. index: 0,
  115. delta: {
  116. reasoning_content: chunk.text,
  117. },
  118. finish_reason: null,
  119. },
  120. ],
  121. }
  122. controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
  123. break
  124. }
  125. case "tool-call": {
  126. const data = {
  127. id,
  128. object: "chat.completion.chunk",
  129. created,
  130. model: body.model,
  131. choices: [
  132. {
  133. index: 0,
  134. delta: {
  135. tool_calls: [
  136. {
  137. id: chunk.toolCallId,
  138. type: "function",
  139. function: {
  140. name: chunk.toolName,
  141. arguments: JSON.stringify(chunk.input),
  142. },
  143. },
  144. ],
  145. },
  146. finish_reason: null,
  147. },
  148. ],
  149. }
  150. controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
  151. break
  152. }
  153. case "error": {
  154. const data = {
  155. id,
  156. object: "chat.completion.chunk",
  157. created,
  158. model: body.model,
  159. error: {
  160. message: chunk.error,
  161. type: "server_error",
  162. },
  163. }
  164. controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
  165. controller.enqueue(encoder.encode("data: [DONE]\n\n"))
  166. controller.close()
  167. break
  168. }
  169. case "finish": {
  170. const finishReason =
  171. {
  172. stop: "stop",
  173. length: "length",
  174. "content-filter": "content_filter",
  175. "tool-calls": "tool_calls",
  176. error: "stop",
  177. other: "stop",
  178. unknown: "stop",
  179. }[chunk.finishReason] || "stop"
  180. const data = {
  181. id,
  182. object: "chat.completion.chunk",
  183. created,
  184. model: body.model,
  185. choices: [
  186. {
  187. index: 0,
  188. delta: {},
  189. finish_reason: finishReason,
  190. },
  191. ],
  192. usage: {
  193. prompt_tokens: chunk.totalUsage.inputTokens,
  194. completion_tokens: chunk.totalUsage.outputTokens,
  195. total_tokens: chunk.totalUsage.totalTokens,
  196. completion_tokens_details: {
  197. reasoning_tokens: chunk.totalUsage.reasoningTokens,
  198. },
  199. prompt_tokens_details: {
  200. cached_tokens: chunk.totalUsage.cachedInputTokens,
  201. },
  202. },
  203. }
  204. controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
  205. controller.enqueue(encoder.encode("data: [DONE]\n\n"))
  206. controller.close()
  207. break
  208. }
  209. //case "stream-start":
  210. //case "response-metadata":
  211. case "start-step":
  212. case "finish-step":
  213. case "text-start":
  214. case "text-end":
  215. case "reasoning-start":
  216. case "reasoning-end":
  217. case "tool-input-start":
  218. case "tool-input-delta":
  219. case "tool-input-end":
  220. case "raw":
  221. default:
  222. // Log unknown chunk types for debugging
  223. console.warn(`Unknown chunk type: ${(chunk as any).type}`)
  224. break
  225. }
  226. }
  227. } catch (error) {
  228. controller.error(error)
  229. }
  230. },
  231. })
  232. return new Response(stream, {
  233. headers: {
  234. "Content-Type": "text/plain; charset=utf-8",
  235. "Cache-Control": "no-cache",
  236. Connection: "keep-alive",
  237. },
  238. })
  239. }
  240. async function handleGenerate() {
  241. const response = await generateText({
  242. model,
  243. ...requestBody,
  244. })
  245. return c.json({
  246. id: `chatcmpl-${Date.now()}`,
  247. object: "chat.completion" as const,
  248. created: Math.floor(Date.now() / 1000),
  249. model: body.model,
  250. choices: [
  251. {
  252. index: 0,
  253. message: {
  254. role: "assistant" as const,
  255. content: response.content?.find((c) => c.type === "text")?.text ?? "",
  256. reasoning_content: response.content?.find((c) => c.type === "reasoning")?.text,
  257. tool_calls: response.content
  258. ?.filter((c) => c.type === "tool-call")
  259. .map((toolCall) => ({
  260. id: toolCall.toolCallId,
  261. type: "function" as const,
  262. function: {
  263. name: toolCall.toolName,
  264. arguments: toolCall.input,
  265. },
  266. })),
  267. },
  268. finish_reason:
  269. (
  270. {
  271. stop: "stop",
  272. length: "length",
  273. "content-filter": "content_filter",
  274. "tool-calls": "tool_calls",
  275. error: "stop",
  276. other: "stop",
  277. unknown: "stop",
  278. } as const
  279. )[response.finishReason] || "stop",
  280. },
  281. ],
  282. usage: {
  283. prompt_tokens: response.usage?.inputTokens,
  284. completion_tokens: response.usage?.outputTokens,
  285. total_tokens: response.usage?.totalTokens,
  286. completion_tokens_details: {
  287. reasoning_tokens: response.usage?.reasoningTokens,
  288. },
  289. prompt_tokens_details: {
  290. cached_tokens: response.usage?.cachedInputTokens,
  291. },
  292. },
  293. })
  294. }
  295. function transformOpenAIRequestToAiSDK() {
  296. const prompt = transformMessages()
  297. return {
  298. prompt,
  299. maxOutputTokens: body.max_tokens ?? body.max_completion_tokens ?? undefined,
  300. temperature: body.temperature ?? undefined,
  301. topP: body.top_p ?? undefined,
  302. frequencyPenalty: body.frequency_penalty ?? undefined,
  303. presencePenalty: body.presence_penalty ?? undefined,
  304. providerOptions: body.reasoning_effort
  305. ? {
  306. anthropic: {
  307. reasoningEffort: body.reasoning_effort,
  308. },
  309. }
  310. : undefined,
  311. stopSequences: (typeof body.stop === "string" ? [body.stop] : body.stop) ?? undefined,
  312. responseFormat: (() => {
  313. if (!body.response_format) return { type: "text" }
  314. if (body.response_format.type === "json_schema")
  315. return {
  316. type: "json",
  317. schema: body.response_format.json_schema.schema,
  318. name: body.response_format.json_schema.name,
  319. description: body.response_format.json_schema.description,
  320. }
  321. if (body.response_format.type === "json_object") return { type: "json" }
  322. throw new Error("Unsupported response format")
  323. })(),
  324. seed: body.seed ?? undefined,
  325. }
  326. function transformTools() {
  327. const { tools, tool_choice } = body
  328. if (!tools || tools.length === 0) {
  329. return { tools: undefined, toolChoice: undefined }
  330. }
  331. const aiSdkTools = tools.reduce(
  332. (acc, tool) => {
  333. acc[tool.function.name] = {
  334. type: "function" as const,
  335. name: tool.function.name,
  336. description: tool.function.description,
  337. inputSchema: tool.function.parameters,
  338. }
  339. return acc
  340. },
  341. {} as Record<string, any>,
  342. )
  343. let aiSdkToolChoice
  344. if (tool_choice == null) {
  345. aiSdkToolChoice = undefined
  346. } else if (tool_choice === "auto") {
  347. aiSdkToolChoice = "auto"
  348. } else if (tool_choice === "none") {
  349. aiSdkToolChoice = "none"
  350. } else if (tool_choice === "required") {
  351. aiSdkToolChoice = "required"
  352. } else if (tool_choice.type === "function") {
  353. aiSdkToolChoice = {
  354. type: "tool",
  355. toolName: tool_choice.function.name,
  356. }
  357. }
  358. return { tools: aiSdkTools, toolChoice: aiSdkToolChoice }
  359. }
  360. function transformMessages() {
  361. const { messages } = body
  362. const prompt: LanguageModelV2Prompt = []
  363. for (const message of messages) {
  364. switch (message.role) {
  365. case "system": {
  366. prompt.push({
  367. role: "system",
  368. content: message.content as string,
  369. })
  370. break
  371. }
  372. case "user": {
  373. if (typeof message.content === "string") {
  374. prompt.push({
  375. role: "user",
  376. content: [{ type: "text", text: message.content }],
  377. })
  378. } else {
  379. const content = message.content.map((part) => {
  380. switch (part.type) {
  381. case "text":
  382. return { type: "text" as const, text: part.text }
  383. case "image_url":
  384. return {
  385. type: "file" as const,
  386. mediaType: "image/jpeg" as const,
  387. data: part.image_url.url,
  388. }
  389. default:
  390. throw new Error(`Unsupported content part type: ${(part as any).type}`)
  391. }
  392. })
  393. prompt.push({
  394. role: "user",
  395. content,
  396. })
  397. }
  398. break
  399. }
  400. case "assistant": {
  401. const content: Array<
  402. | { type: "text"; text: string }
  403. | {
  404. type: "tool-call"
  405. toolCallId: string
  406. toolName: string
  407. input: any
  408. }
  409. > = []
  410. if (message.content) {
  411. content.push({
  412. type: "text",
  413. text: message.content as string,
  414. })
  415. }
  416. if (message.tool_calls) {
  417. for (const toolCall of message.tool_calls) {
  418. content.push({
  419. type: "tool-call",
  420. toolCallId: toolCall.id,
  421. toolName: toolCall.function.name,
  422. input: JSON.parse(toolCall.function.arguments),
  423. })
  424. }
  425. }
  426. prompt.push({
  427. role: "assistant",
  428. content,
  429. })
  430. break
  431. }
  432. case "tool": {
  433. prompt.push({
  434. role: "tool",
  435. content: [
  436. {
  437. type: "tool-result",
  438. toolName: "placeholder",
  439. toolCallId: message.tool_call_id,
  440. output: {
  441. type: "text",
  442. value: message.content as string,
  443. },
  444. },
  445. ],
  446. })
  447. break
  448. }
  449. default: {
  450. throw new Error(`Unsupported message role: ${message.role}`)
  451. }
  452. }
  453. }
  454. return prompt
  455. }
  456. }
  457. } catch (error: any) {
  458. return c.json({ error: { message: error.message } }, 500)
  459. }
  460. })
  461. .all("*", (c) => c.text("Not Found"))