-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: oilbeater <[email protected]>
- Loading branch information
Showing
4 changed files
with
40 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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 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 |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { Context, Next } from 'hono'; | ||
import { AppContext } from '.'; | ||
|
||
export const fallbackMiddleware = async (c: Context<AppContext>, next: Next) => { | ||
try { | ||
await next(); | ||
|
||
// Check if the response status is in the 5xx range | ||
if (c.res && c.res.status >= 500 && c.res.status < 600) { | ||
throw new Error(`Upstream returned ${c.res.status} status`); | ||
} | ||
} catch (error) { | ||
try { | ||
// Call CF Workers AI as a fallback | ||
const fallbackResponse = await c.env.AI.run( | ||
"@cf/meta/llama-3.1-8b-instruct", | ||
await c.req.json() | ||
); | ||
|
||
let response: Response; | ||
if (fallbackResponse instanceof ReadableStream) { | ||
response = new Response(fallbackResponse); | ||
} else { | ||
response = new Response(fallbackResponse.response); | ||
} | ||
|
||
// Add a header to indicate fallback was used | ||
response.headers.set('X-Fallback-Used', 'true'); | ||
return response; | ||
} catch (fallbackError) { | ||
return new Response('Both primary and fallback providers failed', { status: 500 }); | ||
} | ||
} | ||
}; |
This file contains 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 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