Skip to content

Commit

Permalink
feat: 添加异常处理和跨域处理
Browse files Browse the repository at this point in the history
  • Loading branch information
rxliuli committed Aug 25, 2024
1 parent 283ab8f commit 4344479
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 9 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Supported models
Environment variables

- `API_KEY`: Proxy API Key, required when calling the proxy API
- `CORS_ORIGIN`: Allowed CORS domain, e.g. `https://example.com`

- OpenAI: Supports OpenAI models, e.g. `gpt-4o-mini`
- `OPENAI_API_KEY`: OpenAI API Key
Expand Down
1 change: 1 addition & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
环境变量

- `API_KEY`: 代理 API Key,要求调用代理 API 时必须设置
- `CORS_ORIGIN`: 允许的 CORS 域名,例如 `https://example.com`

- OpenAI: 支持 OpenAI 模型,例如 `gpt-4o-mini`
- `OPENAI_API_KEY`: OpenAI API Key
Expand Down
29 changes: 20 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context, Hono } from 'hono'
import { Hono } from 'hono'
import { streamSSE } from 'hono/streaming'
import { openai } from './llm/openai'
import { anthropic, anthropicVertex } from './llm/anthropic'
Expand All @@ -8,6 +8,7 @@ import { google } from './llm/google'
import { deepseek } from './llm/deepseek'
import { serializeError } from 'serialize-error'
import { HTTPException } from 'hono/http-exception'
import { cors } from 'hono/cors'

interface Bindings {
API_KEY: string
Expand Down Expand Up @@ -38,6 +39,24 @@ curl https://api.openai.com/v1/chat/completions \
"temperature": 0.7
}'
*/
.use(
cors({
origin: (_origin, c) => {
return c.env.CORS_ORIGIN
},
}),
)
.use(async (c, next) => {
await next()
if (c.error) {
throw new HTTPException((c.error as any)?.status ?? 500, {
message: serializeError(c.error).message,
})
}
})
.options('/v1/chat/completions', async (c) => {
return c.json({ body: 'ok' })
})
.use(async (c, next) => {
if (!c.env.API_KEY) {
return c.json({ error: 'Unauthorized' }, 401)
Expand All @@ -47,14 +66,6 @@ curl https://api.openai.com/v1/chat/completions \
}
return next()
})
.use(async (c, next) => {
await next()
if (c.error) {
throw new HTTPException((c.error as any)?.status ?? 500, {
message: serializeError(c.error).message,
})
}
})
.post('/v1/chat/completions', async (c) => {
const req = (await c.req.json()) as
| OpenAI.ChatCompletionCreateParamsNonStreaming
Expand Down

0 comments on commit 4344479

Please sign in to comment.