Skip to content

Commit 9c480aa

Browse files
committed
add retries to openrouter generation endpoint to prevent failures on slow usage stat updates server side
Signed-off-by: James Barker <[email protected]>
1 parent 9bace96 commit 9c480aa

File tree

1 file changed

+27
-24
lines changed

1 file changed

+27
-24
lines changed

src/api/providers/openrouter.ts

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -183,31 +183,34 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
183183
// }
184184
}
185185

186-
await delay(500) // FIXME: necessary delay to ensure generation endpoint is ready
187-
188-
try {
189-
const response = await axios.get(`https://openrouter.ai/api/v1/generation?id=${genId}`, {
190-
headers: {
191-
Authorization: `Bearer ${this.options.openRouterApiKey}`,
192-
},
193-
timeout: 5_000, // this request hangs sometimes
194-
})
186+
// retry fetching generation details
187+
let retries = 0
188+
while (retries < 3) {
189+
await delay(500) // FIXME: necessary delay to ensure generation endpoint is ready
190+
try {
191+
const response = await axios.get(`https://openrouter.ai/api/v1/generation?id=${genId}`, {
192+
headers: {
193+
Authorization: `Bearer ${this.options.openRouterApiKey}`,
194+
},
195+
timeout: 5_000, // this request hangs sometimes
196+
})
195197

196-
const generation = response.data?.data
197-
console.log("OpenRouter generation details:", response.data)
198-
yield {
199-
type: "usage",
200-
// cacheWriteTokens: 0,
201-
// cacheReadTokens: 0,
202-
// openrouter generation endpoint fails often
203-
inputTokens: generation?.native_tokens_prompt || 0,
204-
outputTokens: generation?.native_tokens_completion || 0,
205-
totalCost: generation?.total_cost || 0,
206-
fullResponseText,
207-
} as OpenRouterApiStreamUsageChunk
208-
} catch (error) {
209-
// ignore if fails
210-
console.error("Error fetching OpenRouter generation details:", error)
198+
const generation = response.data?.data
199+
console.log("OpenRouter generation details:", response.data)
200+
yield {
201+
type: "usage",
202+
// cacheWriteTokens: 0,
203+
// cacheReadTokens: 0,
204+
// openrouter generation endpoint fails often
205+
inputTokens: generation?.native_tokens_prompt || 0,
206+
outputTokens: generation?.native_tokens_completion || 0,
207+
totalCost: generation?.total_cost || 0,
208+
fullResponseText,
209+
} as OpenRouterApiStreamUsageChunk
210+
} catch (error) {
211+
// ignore if fails
212+
console.error("Error fetching OpenRouter generation details:", error)
213+
}
211214
}
212215
}
213216
getModel(): { id: string; info: ModelInfo } {

0 commit comments

Comments
 (0)