-
Notifications
You must be signed in to change notification settings - Fork 2
Raw API OpenRouter, persistent stdin with Escape cancel, slash commands, agent tools #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yashdev9274
wants to merge
1
commit into
main
Choose a base branch
from
supercode-web
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
220 changes: 173 additions & 47 deletions
220
apps/supercode-cli/server/src/cli/ai/openrouter-service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,89 +1,215 @@ | ||
| import { createOpenRouter } from "@openrouter/ai-sdk-provider" | ||
| import { streamText, type ModelMessage } from "ai" | ||
| import { type ModelMessage } from "ai" | ||
| import { openRouterConfig } from "../../config/openrouter.config.ts" | ||
| import chalk from "chalk" | ||
|
|
||
| const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions" | ||
|
|
||
| function isServerTool(name: string): boolean { | ||
| return name === "web_search" || name === "url_fetch" | ||
| } | ||
|
|
||
| function serverTool(name: string): any { | ||
| if (name === "web_search") return { type: "openrouter:web_search" } | ||
| if (name === "url_fetch") return { type: "openrouter:web_fetch" } | ||
| return null | ||
| } | ||
|
|
||
| function zodToJsonSchema(schema: any): any { | ||
| return typeof schema === "object" && "toJSON" in (schema as any) | ||
| ? (schema as any).toJSON() | ||
| : schema | ||
| } | ||
|
|
||
| export class OpenRouterService { | ||
| readonly modelName: string | ||
| model: any | ||
|
|
||
| constructor(model?: string) { | ||
| if (!openRouterConfig.apiKey) { | ||
| throw new Error("OpenRouter is not configured.\n\n Set OPENROUTER_API_KEY in your environment:\n export OPENROUTER_API_KEY=<your-key>\n\n Get a key at: https://openrouter.ai/keys") | ||
| } | ||
|
|
||
| this.modelName = model || openRouterConfig.model | ||
|
|
||
| const openrouter = createOpenRouter({ | ||
| apiKey: openRouterConfig.apiKey, | ||
| }) | ||
|
|
||
| this.model = openrouter(this.modelName) | ||
| } | ||
|
|
||
| async sendMessage( | ||
| messages: ModelMessage[], | ||
| onChunk?: (chunk: string) => void, | ||
| tools?: any, | ||
| onToolCall?: any, | ||
| signal?: AbortSignal, | ||
| ) { | ||
| try { | ||
| const systemMessages = messages.filter(m => m.role === "system") | ||
| const nonSystemMessages = messages.filter(m => m.role !== "system") | ||
| const system = systemMessages.map(m => m.content).join("\n") | ||
|
|
||
| const streamOptions: any = { | ||
| model: this.model, | ||
| messages: nonSystemMessages, | ||
| const systemMessages = messages.filter(m => m.role === "system") | ||
| const nonSystemMessages = messages.filter(m => m.role !== "system") | ||
| const system = systemMessages.map(m => m.content).join("\n") | ||
|
|
||
| const apiMessages: any[] = [] | ||
| if (system) apiMessages.push({ role: "system", content: system }) | ||
| for (const m of nonSystemMessages) { | ||
| if (m.role === "assistant" && (m as any).tool_calls) { | ||
| const msg: any = { role: "assistant", content: m.content } | ||
| msg.tool_calls = (m as any).tool_calls | ||
| apiMessages.push(msg) | ||
| } else { | ||
| apiMessages.push({ role: m.role, content: m.content as string }) | ||
| } | ||
| } | ||
|
|
||
| const apiTools: any[] = [] | ||
| const functionTools: Record<string, any> = {} | ||
| if (tools) { | ||
| for (const [name, def] of Object.entries(tools as Record<string, any>)) { | ||
| if (isServerTool(name)) { | ||
| apiTools.push(serverTool(name)) | ||
| } else { | ||
| apiTools.push({ | ||
| type: "function", | ||
| function: { | ||
| name, | ||
| description: def.description || "", | ||
| parameters: zodToJsonSchema(def.parameters), | ||
| }, | ||
| }) | ||
| functionTools[name] = def | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const allMessages = [...apiMessages] | ||
| const maxToolIterations = 25 | ||
| let fullResponse = "" | ||
|
|
||
| for (let iter = 0; iter < maxToolIterations; iter++) { | ||
| if (signal?.aborted) throw new DOMException("Aborted", "AbortError") | ||
| if (fullResponse) onChunk?.("\n\n") | ||
|
|
||
| const body: any = { | ||
| model: this.modelName, | ||
| messages: allMessages, | ||
| stream: true, | ||
| } | ||
| if (apiTools.length > 0) body.tools = apiTools | ||
| if (this.modelName.includes("minimax-m3") || this.modelName.includes("glm-5.1")) { | ||
| streamOptions.maxOutputTokens = 8192 | ||
| body.max_tokens = 8192 | ||
| } | ||
|
|
||
| if (system) { | ||
| streamOptions.system = system | ||
| const res = await fetch(OPENROUTER_API_URL, { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${openRouterConfig.apiKey}`, | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify(body), | ||
| signal, | ||
| }) | ||
|
|
||
| if (!res.ok) { | ||
| const errText = await res.text().catch(() => "unknown error") | ||
| throw new Error(`OpenRouter API ${res.status}: ${errText.slice(0, 500)}`) | ||
| } | ||
|
|
||
| if (tools && Object.keys(tools).length > 0) { | ||
| streamOptions.tools = tools | ||
| streamOptions.maxSteps = 5 | ||
| if (onToolCall) { | ||
| streamOptions.experimental_onToolCallStart = (event: any) => { | ||
| const tc = event.toolCall | ||
| onToolCall({ toolName: tc.toolName, args: tc.input as Record<string, unknown> }) | ||
| } | ||
| const reader = res.body?.getReader() | ||
| if (!reader) throw new Error("No response body") | ||
|
|
||
| const decoder = new TextDecoder() | ||
| let buffer = "" | ||
| let toolCalls: Array<{ id: string; type: string; function: { name: string; arguments: string } }> = [] | ||
| let finishReason = "" | ||
|
|
||
| while (true) { | ||
| const { done, value } = await reader.read() | ||
| if (done) break | ||
|
|
||
| buffer += decoder.decode(value, { stream: true }) | ||
| const lines = buffer.split("\n") | ||
| buffer = lines.pop() || "" | ||
|
|
||
| for (const line of lines) { | ||
| const trimmed = line.trim() | ||
| if (!trimmed || !trimmed.startsWith("data: ")) continue | ||
| const jsonStr = trimmed.slice(6) | ||
| if (jsonStr === "[DONE]") continue | ||
|
|
||
| try { | ||
| const data = JSON.parse(jsonStr) | ||
| const delta = data.choices?.[0]?.delta | ||
| const finish = data.choices?.[0]?.finish_reason | ||
|
|
||
| if (finish) finishReason = finish | ||
|
|
||
| if (delta?.content) { | ||
| fullResponse += delta.content | ||
| onChunk?.(delta.content) | ||
| } | ||
|
|
||
| if (delta?.tool_calls) { | ||
| for (const tc of delta.tool_calls) { | ||
| const existing = toolCalls.find(t => t.id === tc.id) | ||
| if (existing) { | ||
| if (tc.function?.arguments) existing.function.arguments += tc.function.arguments | ||
| } else { | ||
| toolCalls.push({ | ||
| id: tc.id, | ||
| type: tc.type || "function", | ||
| function: { | ||
| name: tc.function?.name || "", | ||
| arguments: tc.function?.arguments || "", | ||
| }, | ||
| }) | ||
| } | ||
| } | ||
| } | ||
| } catch { /* skip malformed */ } | ||
| } | ||
| } | ||
|
|
||
| const result = streamText(streamOptions) | ||
| if (finishReason === "tool_calls" && toolCalls.length > 0) { | ||
| const assistantMsg: any = { role: "assistant", content: null } | ||
| assistantMsg.tool_calls = toolCalls.map(tc => ({ | ||
| id: tc.id, | ||
| type: tc.type, | ||
| function: { name: tc.function.name, arguments: tc.function.arguments }, | ||
| })) | ||
| allMessages.push(assistantMsg) | ||
|
|
||
| let fullResponse = "" | ||
| for (const tc of toolCalls) { | ||
| const toolName = tc.function.name | ||
| const toolDef = functionTools[toolName] | ||
| let toolResult: string | ||
|
|
||
| for await (const chunk of result.textStream) { | ||
| fullResponse += chunk | ||
| onChunk?.(chunk) | ||
| } | ||
| if (toolDef?.execute) { | ||
| let args: any = {} | ||
| try { args = JSON.parse(tc.function.arguments || "{}") } catch { /* */ } | ||
| onToolCall?.({ toolName, args }) | ||
| try { toolResult = await toolDef.execute(args) } catch (err: any) { toolResult = `Error: ${err.message || String(err)}` } | ||
| } else { | ||
| toolResult = `Tool "${toolName}" is not available locally` | ||
| } | ||
|
|
||
| return { | ||
| content: fullResponse, | ||
| finishResponse: result.finishReason, | ||
| usage: result.usage, | ||
| } | ||
| } catch (error) { | ||
| console.error(chalk.red("OpenRouter Service Error:"), error instanceof Error ? error.message : String(error)) | ||
| if (error instanceof Error && "cause" in error) { | ||
| console.error(chalk.red(" Cause:"), String((error as any).cause)) | ||
| allMessages.push({ | ||
| role: "tool", | ||
| tool_call_id: tc.id, | ||
| content: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult), | ||
| }) | ||
| } | ||
|
|
||
| toolCalls = [] | ||
| finishReason = "" | ||
| continue | ||
| } | ||
| throw error | ||
|
|
||
| break | ||
| } | ||
|
|
||
| return { | ||
| content: fullResponse, | ||
| finishResponse: Promise.resolve("stop" as any), | ||
| usage: Promise.resolve({ inputTokens: 0, outputTokens: 0, totalTokens: 0 } as any), | ||
| } | ||
| } | ||
|
|
||
| async getMessage(messages: ModelMessage[], tools?: any) { | ||
| let fullResponse = "" | ||
| await this.sendMessage(messages, (chunk) => { | ||
| fullResponse += chunk | ||
| }) | ||
| await this.sendMessage(messages, (chunk) => { fullResponse += chunk }, tools) | ||
| return fullResponse | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tool call argument accumulation uses wrong identifier.
OpenRouter/OpenAI streaming sends tool calls with an
indexfield for delta accumulation, not repeatedidvalues. After the first chunk, subsequent deltas haveindexbut may omitid, causing this logic to create duplicate entries instead of appending arguments.🐛 Proposed fix using index-based accumulation
if (delta?.tool_calls) { for (const tc of delta.tool_calls) { - const existing = toolCalls.find(t => t.id === tc.id) + const idx = tc.index ?? toolCalls.length + const existing = toolCalls[idx] if (existing) { if (tc.function?.arguments) existing.function.arguments += tc.function.arguments + if (tc.function?.name) existing.function.name = tc.function.name + if (tc.id) existing.id = tc.id } else { - toolCalls.push({ - id: tc.id, + toolCalls[idx] = { + id: tc.id || "", type: tc.type || "function", function: { name: tc.function?.name || "", arguments: tc.function?.arguments || "", }, - }) + } } } }📝 Committable suggestion
🤖 Prompt for AI Agents