@@ -156,33 +156,40 @@ export default {
156156 }
157157
158158 try {
159- // 先检查请求体大小(避免解析超大 JSON )
160- const contentLength = request . headers . get ( 'Content-Length' )
161- if ( contentLength && parseInt ( contentLength , 10 ) > 10000 ) {
162- return jsonResponse ( { error : '消息太长' } , 400 )
159+ // 读取原始请求体,检查实际大小(Content-Length 可能被省略 )
160+ const buf = await request . arrayBuffer ( )
161+ if ( buf . byteLength > 10000 ) {
162+ return jsonResponse ( { error : '消息太长' } , 413 )
163163 }
164-
165- const body = ( await request . json ( ) ) as ChatRequest
164+ const body = JSON . parse ( new TextDecoder ( ) . decode ( buf ) ) as ChatRequest
166165
167166 // 基本校验
168167 if ( ! body . messages || ! Array . isArray ( body . messages ) ) {
169168 return jsonResponse ( { error : '无效的请求格式' } , 400 )
170169 }
171170
172- // 转发到 DeepSeek API
173- const response = await fetch ( 'https://api.deepseek.com/v1/chat/completions' , {
174- method : 'POST' ,
175- headers : {
176- 'Content-Type' : 'application/json' ,
177- Authorization : `Bearer ${ env . DEEPSEEK_API_KEY } ` ,
178- } ,
179- body : JSON . stringify ( {
180- model : 'deepseek-chat' ,
181- messages : body . messages ,
182- temperature : 0.7 ,
183- max_tokens : 800 , // 限制回复长度控制成本
184- } ) ,
185- } )
171+ // 转发到 DeepSeek API(25s 超时)
172+ const controller = new AbortController ( )
173+ const timeout = setTimeout ( ( ) => controller . abort ( ) , 25000 )
174+ let response : Response
175+ try {
176+ response = await fetch ( 'https://api.deepseek.com/v1/chat/completions' , {
177+ method : 'POST' ,
178+ headers : {
179+ 'Content-Type' : 'application/json' ,
180+ Authorization : `Bearer ${ env . DEEPSEEK_API_KEY } ` ,
181+ } ,
182+ body : JSON . stringify ( {
183+ model : 'deepseek-chat' ,
184+ messages : body . messages ,
185+ temperature : 0.7 ,
186+ max_tokens : 800 , // 限制回复长度控制成本
187+ } ) ,
188+ signal : controller . signal ,
189+ } )
190+ } finally {
191+ clearTimeout ( timeout )
192+ }
186193
187194 let data : unknown
188195 try {
0 commit comments