-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Use openrouter stream_options include_usage #1905
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
Merged
Merged
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,11 +24,6 @@ type OpenRouterChatCompletionParams = OpenAI.Chat.ChatCompletionCreateParams & { | |
| thinking?: BetaThinkingConfigParam | ||
| } | ||
|
|
||
| // Add custom interface for OpenRouter usage chunk. | ||
| interface OpenRouterApiStreamUsageChunk extends ApiStreamUsageChunk { | ||
| fullResponseText: string | ||
| } | ||
|
|
||
| export class OpenRouterHandler extends BaseProvider implements SingleCompletionHandler { | ||
| protected options: ApiHandlerOptions | ||
| private client: OpenAI | ||
|
|
@@ -110,7 +105,7 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH | |
| top_p: topP, | ||
| messages: openAiMessages, | ||
| stream: true, | ||
| include_reasoning: true, | ||
| stream_options: { include_usage: true }, | ||
| // Only include provider if openRouterSpecificProvider is not "[default]". | ||
| ...(this.options.openRouterSpecificProvider && | ||
| this.options.openRouterSpecificProvider !== OPENROUTER_DEFAULT_PROVIDER_NAME && { | ||
|
|
@@ -122,7 +117,7 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH | |
|
|
||
| const stream = await this.client.chat.completions.create(completionParams) | ||
|
|
||
| let genId: string | undefined | ||
| let lastUsage | ||
|
|
||
| for await (const chunk of stream as unknown as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) { | ||
| // OpenRouter returns an error object instead of the OpenAI SDK throwing an error. | ||
|
|
@@ -132,10 +127,6 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH | |
| throw new Error(`OpenRouter API Error ${error?.code}: ${error?.message}`) | ||
| } | ||
|
|
||
| if (!genId && chunk.id) { | ||
| genId = chunk.id | ||
| } | ||
|
|
||
| const delta = chunk.choices[0]?.delta | ||
|
|
||
| if ("reasoning" in delta && delta.reasoning) { | ||
|
|
@@ -146,47 +137,23 @@ export class OpenRouterHandler extends BaseProvider implements SingleCompletionH | |
| fullResponseText += delta.content | ||
| yield { type: "text", text: delta.content } as ApiStreamChunk | ||
| } | ||
| } | ||
|
|
||
| const endpoint = `${this.client.baseURL}/generation?id=${genId}` | ||
|
|
||
| const config: AxiosRequestConfig = { | ||
| headers: { Authorization: `Bearer ${this.options.openRouterApiKey}` }, | ||
| timeout: 3_000, | ||
| if (chunk.usage) { | ||
| lastUsage = chunk.usage | ||
| } | ||
| } | ||
|
|
||
| let attempt = 0 | ||
| let lastError: Error | undefined | ||
| const startTime = Date.now() | ||
|
|
||
| while (attempt++ < 10) { | ||
| await delay(attempt * 100) // Give OpenRouter some time to produce the generation metadata. | ||
|
|
||
| try { | ||
| const response = await axios.get(endpoint, config) | ||
| const generation = response.data?.data | ||
|
|
||
| yield { | ||
| type: "usage", | ||
| inputTokens: generation?.native_tokens_prompt || 0, | ||
| outputTokens: generation?.native_tokens_completion || 0, | ||
| totalCost: generation?.total_cost || 0, | ||
| fullResponseText, | ||
| } as OpenRouterApiStreamUsageChunk | ||
|
|
||
| break | ||
| } catch (error: unknown) { | ||
| if (error instanceof Error) { | ||
| lastError = error | ||
| } | ||
| } | ||
| if (lastUsage) { | ||
| yield this.processUsageMetrics(lastUsage) | ||
| } | ||
| } | ||
|
|
||
| if (lastError) { | ||
| console.error( | ||
| `Failed to fetch OpenRouter generation details after attempt #${attempt} (${Date.now() - startTime}ms) [${genId}]`, | ||
| lastError, | ||
| ) | ||
| processUsageMetrics(usage: any): ApiStreamUsageChunk { | ||
mrubens marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return { | ||
| type: "usage", | ||
| inputTokens: usage?.prompt_tokens || 0, | ||
| outputTokens: usage?.completion_tokens || 0, | ||
| totalCost: usage?.cost || 0, | ||
| } | ||
| } | ||
|
|
||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.