nomid2 commited on
Commit
f2cbdd0
·
verified ·
1 Parent(s): 62be311

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +289 -53
app.py CHANGED
@@ -7,8 +7,10 @@ from fastapi import FastAPI, Request, HTTPException
7
  from fastapi.responses import StreamingResponse, JSONResponse
8
  from fastapi.middleware.cors import CORSMiddleware
9
  import uvicorn
10
- from typing import Dict, Any, AsyncGenerator
11
  import logging
 
 
12
 
13
  # 配置更详细的日志
14
  logging.basicConfig(
@@ -41,37 +43,63 @@ if not REPLICATE_API_TOKEN:
41
  REPLICATE_BASE_URL = "https://api.replicate.com/v1"
42
  DEFAULT_MODEL = "anthropic/claude-3.5-sonnet"
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # 模型配置信息
45
  MODEL_CONFIGS = {
46
  "anthropic/claude-4-sonnet": {
47
- "min_max_tokens": 1024, # Replicate 要求的最小值
48
- "default_max_tokens": 8192, # 如果客户端未指定时的默认值
49
- "has_max_tokens_limit": True
 
 
50
  },
51
  "anthropic/claude-3.5-sonnet": {
52
  "min_max_tokens": 1,
53
  "default_max_tokens": 8192,
54
- "has_max_tokens_limit": False
 
 
55
  },
56
  "anthropic/claude-3-sonnet": {
57
  "min_max_tokens": 1,
58
  "default_max_tokens": 4096,
59
- "has_max_tokens_limit": False
 
 
60
  },
61
  "anthropic/claude-3.5-haiku": {
62
  "min_max_tokens": 1,
63
  "default_max_tokens": 4096,
64
- "has_max_tokens_limit": False
 
 
65
  },
66
  "anthropic/claude-3-haiku": {
67
  "min_max_tokens": 1,
68
  "default_max_tokens": 4096,
69
- "has_max_tokens_limit": False
 
 
70
  },
71
- "google/gemini-2.5-pro": { # 如果将来支持 Gemini
72
  "min_max_tokens": 1,
73
  "default_max_tokens": 8192,
74
- "has_max_tokens_limit": False
 
 
75
  }
76
  }
77
 
@@ -90,6 +118,155 @@ async def global_exception_handler(request: Request, exc: Exception):
90
  }
91
  )
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def transform_openai_to_replicate(openai_request: Dict[str, Any], model_override: str = None) -> Dict[str, Any]:
94
  """将OpenAI格式的请求转换为Replicate格式"""
95
  try:
@@ -98,38 +275,43 @@ def transform_openai_to_replicate(openai_request: Dict[str, Any], model_override
98
  # 完全使用客户端提供的 system prompt,不设置默认值
99
  system_prompt = None
100
  user_messages = []
 
 
 
101
 
102
  for message in messages:
103
  if message.get("role") == "system":
104
  system_prompt = message.get("content", "")
105
  elif message.get("role") in ["user", "assistant"]:
106
- user_messages.append(message)
107
-
108
- # 构建prompt - 包含完整的对话历��,不限制数量
109
- prompt_parts = []
110
- for msg in user_messages:
111
- role = msg.get("role", "")
112
- content = msg.get("content", "")
113
- if role == "user":
114
- prompt_parts.append(f"Human: {content}")
115
- elif role == "assistant":
116
- prompt_parts.append(f"Assistant: {content}")
117
-
118
- prompt = "\n\n".join(prompt_parts)
119
- if prompt_parts and not prompt.endswith("\n\nAssistant:"):
120
- prompt += "\n\nAssistant:"
 
 
121
 
122
  # 确定使用的模型
123
  model = model_override or openai_request.get("model", DEFAULT_MODEL)
124
 
125
- # 正确的模型名称映射
126
  model_mapping = {
127
  "claude-4-sonnet": "anthropic/claude-4-sonnet",
128
  "claude-3.5-sonnet": "anthropic/claude-3.5-sonnet",
129
  "claude-3-sonnet": "anthropic/claude-3-sonnet",
130
  "claude-3.5-haiku": "anthropic/claude-3.5-haiku",
131
  "claude-3-haiku": "anthropic/claude-3-haiku",
132
- "gemini-2.5-pro": "google/gemini-2.5-pro", # 预留
133
  }
134
 
135
  if model in model_mapping:
@@ -140,41 +322,77 @@ def transform_openai_to_replicate(openai_request: Dict[str, Any], model_override
140
  # 获取模型配置
141
  model_config = MODEL_CONFIGS.get(model, MODEL_CONFIGS["anthropic/claude-3.5-sonnet"])
142
 
143
- # 处理 max_tokens - 完全根据客户端和模型配置
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  client_max_tokens = openai_request.get("max_tokens")
145
 
146
  if client_max_tokens is not None:
147
- # 客户端指定了 max_tokens,尊重客户端设置
148
  max_tokens = client_max_tokens
149
- # 只在低于模型最小要求时调整
150
  if max_tokens < model_config["min_max_tokens"]:
151
  logger.info(f"Adjusting max_tokens from {max_tokens} to {model_config['min_max_tokens']} (model minimum)")
152
  max_tokens = model_config["min_max_tokens"]
153
  else:
154
- # 客户端未指定 max_tokens
155
  if model_config["has_max_tokens_limit"]:
156
- # 模型有强制要求,使用默认值
157
  max_tokens = model_config["default_max_tokens"]
158
  logger.info(f"Using default max_tokens {max_tokens} for model {model}")
159
  else:
160
- # 模型没有限制,不设置 max_tokens
161
  max_tokens = None
162
  logger.info(f"No max_tokens limit for model {model}, allowing unlimited")
163
 
164
- # 构建 Replicate 请求的 input 参数
165
- replicate_input = {
166
- "prompt": prompt,
167
- }
168
-
169
- # 只在有 system_prompt 时才添加
170
- if system_prompt:
171
- replicate_input["system_prompt"] = system_prompt
172
-
173
- # 只在有 max_tokens 时才添加
174
  if max_tokens is not None:
175
  replicate_input["max_tokens"] = max_tokens
176
 
177
- # 处理其他参数 - 完全使用客户端设置
178
  if "temperature" in openai_request:
179
  replicate_input["temperature"] = openai_request["temperature"]
180
 
@@ -194,7 +412,10 @@ def transform_openai_to_replicate(openai_request: Dict[str, Any], model_override
194
 
195
  logger.info(f"Transformed request for model: {model}")
196
  logger.info(f"Message count: {len(messages)} (system: {1 if system_prompt else 0}, user/assistant: {len(user_messages)})")
197
- logger.info(f"Parameters: max_tokens={max_tokens}, temperature={replicate_input.get('temperature', 'not set')}, top_p={replicate_input.get('top_p', 'not set')}")
 
 
 
198
 
199
  return replicate_request, model
200
 
@@ -212,7 +433,14 @@ async def create_replicate_prediction(session: aiohttp.ClientSession, model: str
212
  }
213
 
214
  logger.info(f"Creating prediction for model: {model}")
215
- logger.info(f"Request data: {json.dumps(data, indent=2)}")
 
 
 
 
 
 
 
216
 
217
  async with session.post(url, headers=headers, json=data, timeout=30) as response:
218
  response_text = await response.text()
@@ -291,11 +519,15 @@ def create_openai_chunk(content: str, model: str, prediction_id: str, finish_rea
291
  async def root():
292
  """健康检查端点"""
293
  return {
294
- "message": "Replicate API Proxy for LobeChat",
295
  "status": "running",
296
  "replicate_token_configured": bool(REPLICATE_API_TOKEN),
297
- "version": "1.0.0",
298
- "supported_models": list(MODEL_CONFIGS.keys())
 
 
 
 
299
  }
300
 
301
  @app.get("/health")
@@ -305,7 +537,11 @@ async def health():
305
  "status": "healthy",
306
  "replicate_token": "configured" if REPLICATE_API_TOKEN else "missing",
307
  "timestamp": asyncio.get_event_loop().time(),
308
- "model_configs": MODEL_CONFIGS
 
 
 
 
309
  }
310
 
311
  @app.get("/v1/models")
@@ -332,7 +568,7 @@ async def chat_completions(request: Request):
332
  try:
333
  body = await request.json()
334
  logger.info(f"Received chat completion request")
335
- logger.info(f"Client parameters: max_tokens={body.get('max_tokens', 'not set')}, temperature={body.get('temperature', 'not set')}, top_p={body.get('top_p', 'not set')}")
336
  logger.info(f"Message count: {len(body.get('messages', []))}")
337
 
338
  # 转换请求格式
@@ -433,7 +669,7 @@ async def chat_completions(request: Request):
433
  "Cache-Control": "no-cache",
434
  "Connection": "keep-alive",
435
  "Access-Control-Allow-Origin": "*",
436
- "X-Accel-Buffering": "no", # 禁用 Nginx 缓冲
437
  }
438
  )
439
 
@@ -449,7 +685,7 @@ async def chat_completions(request: Request):
449
  prediction_url = f"{REPLICATE_BASE_URL}/predictions/{prediction_id}"
450
  headers = {"Authorization": f"Bearer {REPLICATE_API_TOKEN}"}
451
 
452
- max_attempts = 60 # 最多等待60秒
453
  attempt = 0
454
 
455
  while attempt < max_attempts:
 
7
  from fastapi.responses import StreamingResponse, JSONResponse
8
  from fastapi.middleware.cors import CORSMiddleware
9
  import uvicorn
10
+ from typing import Dict, Any, AsyncGenerator, List, Union
11
  import logging
12
+ import base64
13
+ import mimetypes
14
 
15
  # 配置更详细的日志
16
  logging.basicConfig(
 
43
  REPLICATE_BASE_URL = "https://api.replicate.com/v1"
44
  DEFAULT_MODEL = "anthropic/claude-3.5-sonnet"
45
 
46
+ # 支持的文件类型
47
+ SUPPORTED_TEXT_EXTENSIONS = {
48
+ '.txt', '.md', '.py', '.js', '.ts', '.html', '.htm', '.css', '.json',
49
+ '.xml', '.yaml', '.yml', '.sh', '.bash', '.zsh', '.fish', '.ps1',
50
+ '.java', '.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.cs', '.php',
51
+ '.rb', '.go', '.rs', '.swift', '.kt', '.scala', '.r', '.sql',
52
+ '.dockerfile', '.gitignore', '.gitattributes', '.env', '.ini', '.conf',
53
+ '.log', '.csv', '.tsv', '.properties', '.toml', '.lock'
54
+ }
55
+
56
+ SUPPORTED_IMAGE_EXTENSIONS = {
57
+ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'
58
+ }
59
+
60
  # 模型配置信息
61
  MODEL_CONFIGS = {
62
  "anthropic/claude-4-sonnet": {
63
+ "min_max_tokens": 1024,
64
+ "default_max_tokens": 8192,
65
+ "has_max_tokens_limit": True,
66
+ "supports_vision": True,
67
+ "supports_files": True
68
  },
69
  "anthropic/claude-3.5-sonnet": {
70
  "min_max_tokens": 1,
71
  "default_max_tokens": 8192,
72
+ "has_max_tokens_limit": False,
73
+ "supports_vision": True,
74
+ "supports_files": True
75
  },
76
  "anthropic/claude-3-sonnet": {
77
  "min_max_tokens": 1,
78
  "default_max_tokens": 4096,
79
+ "has_max_tokens_limit": False,
80
+ "supports_vision": True,
81
+ "supports_files": True
82
  },
83
  "anthropic/claude-3.5-haiku": {
84
  "min_max_tokens": 1,
85
  "default_max_tokens": 4096,
86
+ "has_max_tokens_limit": False,
87
+ "supports_vision": True,
88
+ "supports_files": True
89
  },
90
  "anthropic/claude-3-haiku": {
91
  "min_max_tokens": 1,
92
  "default_max_tokens": 4096,
93
+ "has_max_tokens_limit": False,
94
+ "supports_vision": True,
95
+ "supports_files": True
96
  },
97
+ "google/gemini-2.5-pro": {
98
  "min_max_tokens": 1,
99
  "default_max_tokens": 8192,
100
+ "has_max_tokens_limit": False,
101
+ "supports_vision": True,
102
+ "supports_files": True
103
  }
104
  }
105
 
 
118
  }
119
  )
120
 
121
+ def get_file_extension(filename: str) -> str:
122
+ """获取文件扩展名"""
123
+ return os.path.splitext(filename.lower())[1]
124
+
125
+ def decode_base64_file(data_url: str) -> tuple[str, str, str]:
126
+ """
127
+ 解码 base64 文件数据
128
+ 返回: (mime_type, filename, content)
129
+ """
130
+ try:
131
+ if not data_url.startswith("data:"):
132
+ return None, None, None
133
+
134
+ # 解析 data URL: data:mime/type;name=filename;base64,content
135
+ header, base64_content = data_url.split(",", 1)
136
+ header_parts = header.split(";")
137
+
138
+ mime_type = header_parts[0].replace("data:", "")
139
+ filename = "unknown_file"
140
+
141
+ # 查找文件名
142
+ for part in header_parts:
143
+ if part.startswith("name="):
144
+ filename = part.replace("name=", "")
145
+ break
146
+
147
+ # 解码 base64 内容
148
+ try:
149
+ decoded_bytes = base64.b64decode(base64_content)
150
+
151
+ # 如果是文本类型,尝试解码为文本
152
+ if mime_type.startswith("text/") or any(filename.lower().endswith(ext) for ext in SUPPORTED_TEXT_EXTENSIONS):
153
+ try:
154
+ content = decoded_bytes.decode('utf-8')
155
+ return mime_type, filename, content
156
+ except UnicodeDecodeError:
157
+ try:
158
+ content = decoded_bytes.decode('latin-1')
159
+ return mime_type, filename, content
160
+ except UnicodeDecodeError:
161
+ logger.warning(f"Failed to decode text file {filename}")
162
+ return mime_type, filename, None
163
+ else:
164
+ # 对于二进制文件(如图片),返回 base64 内容
165
+ return mime_type, filename, base64_content
166
+
167
+ except Exception as e:
168
+ logger.error(f"Failed to decode base64 content: {e}")
169
+ return mime_type, filename, None
170
+
171
+ except Exception as e:
172
+ logger.error(f"Failed to parse data URL: {e}")
173
+ return None, None, None
174
+
175
+ def extract_content_from_message(message: Dict[str, Any]) -> tuple[str, List[str], List[Dict[str, str]]]:
176
+ """
177
+ 从消息中提取文本内容、图片和文件
178
+ 返回: (text_content, image_data_list, file_data_list)
179
+ """
180
+ content = message.get("content", "")
181
+ images = []
182
+ files = []
183
+
184
+ if isinstance(content, str):
185
+ # 简单文本消息
186
+ return content, images, files
187
+ elif isinstance(content, list):
188
+ # 复合消息(文本 + 图片 + 文件)
189
+ text_parts = []
190
+
191
+ for item in content:
192
+ if isinstance(item, dict):
193
+ item_type = item.get("type", "")
194
+
195
+ if item_type == "text":
196
+ text_parts.append(item.get("text", ""))
197
+
198
+ elif item_type == "image_url":
199
+ image_url = item.get("image_url", {})
200
+ url = image_url.get("url", "")
201
+
202
+ if url.startswith("data:image/"):
203
+ # Base64 图片数据
204
+ try:
205
+ if ";base64," in url:
206
+ base64_data = url.split(";base64,")[1]
207
+ images.append(base64_data)
208
+ logger.info(f"Found base64 image, size: {len(base64_data)} chars")
209
+ except Exception as e:
210
+ logger.error(f"Error processing image: {e}")
211
+
212
+ elif item_type == "file" or (item_type == "image_url" and not item.get("image_url", {}).get("url", "").startswith("data:image/")):
213
+ # 处理文件上传
214
+ file_url = item.get("image_url", {}).get("url", "") if item_type == "image_url" else item.get("file_url", {}).get("url", "")
215
+
216
+ if file_url.startswith("data:"):
217
+ mime_type, filename, file_content = decode_base64_file(file_url)
218
+
219
+ if file_content is not None:
220
+ file_ext = get_file_extension(filename)
221
+
222
+ if file_ext in SUPPORTED_IMAGE_EXTENSIONS and mime_type.startswith("image/"):
223
+ # 图片文件
224
+ images.append(file_content)
225
+ logger.info(f"Found image file: {filename}")
226
+ elif file_ext in SUPPORTED_TEXT_EXTENSIONS or mime_type.startswith("text/"):
227
+ # 文本文件
228
+ files.append({
229
+ "filename": filename,
230
+ "content": file_content,
231
+ "mime_type": mime_type
232
+ })
233
+ logger.info(f"Found text file: {filename}, size: {len(file_content)} chars")
234
+ else:
235
+ logger.warning(f"Unsupported file type: {filename} ({mime_type})")
236
+
237
+ elif isinstance(item, str):
238
+ text_parts.append(item)
239
+
240
+ return " ".join(text_parts), images, files
241
+
242
+ return str(content), images, files
243
+
244
+ def format_files_for_prompt(files: List[Dict[str, str]]) -> str:
245
+ """将文件内容格式化为提示文本"""
246
+ if not files:
247
+ return ""
248
+
249
+ file_sections = []
250
+ for file_data in files:
251
+ filename = file_data["filename"]
252
+ content = file_data["content"]
253
+ mime_type = file_data.get("mime_type", "text/plain")
254
+
255
+ # 限制单个文件的最大长度(避免 token 过多)
256
+ max_length = 10000 # 约 10k 字符
257
+ if len(content) > max_length:
258
+ content = content[:max_length] + "\n\n[文件内容已截断,显示前 10000 字符]"
259
+
260
+ file_section = f"""
261
+
262
+ --- 文件: {filename} ({mime_type}) ---
263
+ {content}
264
+ --- 文件结束 ---
265
+ """
266
+ file_sections.append(file_section)
267
+
268
+ return "\n".join(file_sections)
269
+
270
  def transform_openai_to_replicate(openai_request: Dict[str, Any], model_override: str = None) -> Dict[str, Any]:
271
  """将OpenAI格式的请求转换为Replicate格式"""
272
  try:
 
275
  # 完全使用客户端提供的 system prompt,不设置默认值
276
  system_prompt = None
277
  user_messages = []
278
+ has_images = False
279
+ has_files = False
280
+ all_files = []
281
 
282
  for message in messages:
283
  if message.get("role") == "system":
284
  system_prompt = message.get("content", "")
285
  elif message.get("role") in ["user", "assistant"]:
286
+ # 提取文本、图片和文件
287
+ text_content, image_list, file_list = extract_content_from_message(message)
288
+
289
+ # 为消息添加附件信息
290
+ msg_data = {
291
+ "role": message.get("role"),
292
+ "content": text_content,
293
+ "images": image_list,
294
+ "files": file_list
295
+ }
296
+ user_messages.append(msg_data)
297
+
298
+ if image_list:
299
+ has_images = True
300
+ if file_list:
301
+ has_files = True
302
+ all_files.extend(file_list)
303
 
304
  # 确定使用的模型
305
  model = model_override or openai_request.get("model", DEFAULT_MODEL)
306
 
307
+ # 模型名称映射
308
  model_mapping = {
309
  "claude-4-sonnet": "anthropic/claude-4-sonnet",
310
  "claude-3.5-sonnet": "anthropic/claude-3.5-sonnet",
311
  "claude-3-sonnet": "anthropic/claude-3-sonnet",
312
  "claude-3.5-haiku": "anthropic/claude-3.5-haiku",
313
  "claude-3-haiku": "anthropic/claude-3-haiku",
314
+ "gemini-2.5-pro": "google/gemini-2.5-pro",
315
  }
316
 
317
  if model in model_mapping:
 
322
  # 获取模型配置
323
  model_config = MODEL_CONFIGS.get(model, MODEL_CONFIGS["anthropic/claude-3.5-sonnet"])
324
 
325
+ # 检查模型支持
326
+ if has_images and not model_config.get("supports_vision", False):
327
+ logger.warning(f"Model {model} may not support vision")
328
+ if has_files and not model_config.get("supports_files", False):
329
+ logger.warning(f"Model {model} may not support file processing")
330
+
331
+ # 构建 Replicate 格式的输入
332
+ replicate_input = {}
333
+
334
+ # 构建完整的提示文本
335
+ prompt_parts = []
336
+
337
+ # 添加文件内容到提示中
338
+ if has_files:
339
+ files_section = format_files_for_prompt(all_files)
340
+ if files_section:
341
+ prompt_parts.append("以下是用户上传的文件内容:")
342
+ prompt_parts.append(files_section)
343
+ prompt_parts.append("请根据上述文件内容回答用户的问题。")
344
+
345
+ # 处理对话历史
346
+ for i, msg in enumerate(user_messages):
347
+ role = msg["role"]
348
+ content = msg["content"]
349
+
350
+ if role == "user":
351
+ prompt_parts.append(f"Human: {content}")
352
+ elif role == "assistant":
353
+ prompt_parts.append(f"Assistant: {content}")
354
+
355
+ # 构建最终 prompt
356
+ prompt = "\n\n".join(prompt_parts)
357
+ if not prompt.endswith("\n\nAssistant:"):
358
+ prompt += "\n\nAssistant:"
359
+
360
+ replicate_input["prompt"] = prompt
361
+
362
+ # 处理图片(只使用第一张图片)
363
+ if has_images:
364
+ # 找到最后一个包含图片的用户消息
365
+ for msg in reversed(user_messages):
366
+ if msg["role"] == "user" and msg["images"]:
367
+ primary_image = msg["images"][0]
368
+ replicate_input["image"] = f"data:image/jpeg;base64,{primary_image}"
369
+ logger.info(f"Added primary image to request")
370
+ break
371
+
372
+ # 只在有 system_prompt 时才添加
373
+ if system_prompt:
374
+ replicate_input["system_prompt"] = system_prompt
375
+
376
+ # 处理 max_tokens
377
  client_max_tokens = openai_request.get("max_tokens")
378
 
379
  if client_max_tokens is not None:
 
380
  max_tokens = client_max_tokens
 
381
  if max_tokens < model_config["min_max_tokens"]:
382
  logger.info(f"Adjusting max_tokens from {max_tokens} to {model_config['min_max_tokens']} (model minimum)")
383
  max_tokens = model_config["min_max_tokens"]
384
  else:
 
385
  if model_config["has_max_tokens_limit"]:
 
386
  max_tokens = model_config["default_max_tokens"]
387
  logger.info(f"Using default max_tokens {max_tokens} for model {model}")
388
  else:
 
389
  max_tokens = None
390
  logger.info(f"No max_tokens limit for model {model}, allowing unlimited")
391
 
 
 
 
 
 
 
 
 
 
 
392
  if max_tokens is not None:
393
  replicate_input["max_tokens"] = max_tokens
394
 
395
+ # 处理其他参数
396
  if "temperature" in openai_request:
397
  replicate_input["temperature"] = openai_request["temperature"]
398
 
 
412
 
413
  logger.info(f"Transformed request for model: {model}")
414
  logger.info(f"Message count: {len(messages)} (system: {1 if system_prompt else 0}, user/assistant: {len(user_messages)})")
415
+ logger.info(f"Has images: {has_images}, Has files: {has_files}")
416
+ if has_files:
417
+ logger.info(f"Files: {[f['filename'] for f in all_files]}")
418
+ logger.info(f"Parameters: max_tokens={max_tokens}, temperature={replicate_input.get('temperature', 'not set')}")
419
 
420
  return replicate_request, model
421
 
 
433
  }
434
 
435
  logger.info(f"Creating prediction for model: {model}")
436
+ # 避免在日志中打印完整的图片数据和文件内容
437
+ log_data = data.copy()
438
+ if "input" in log_data:
439
+ if "image" in log_data["input"]:
440
+ log_data["input"]["image"] = f"[IMAGE_DATA_{len(log_data['input']['image'])}]"
441
+ if "prompt" in log_data["input"] and len(log_data["input"]["prompt"]) > 1000:
442
+ log_data["input"]["prompt"] = log_data["input"]["prompt"][:1000] + "...[TRUNCATED]"
443
+ logger.info(f"Request data: {json.dumps(log_data, indent=2)}")
444
 
445
  async with session.post(url, headers=headers, json=data, timeout=30) as response:
446
  response_text = await response.text()
 
519
  async def root():
520
  """健康检查端点"""
521
  return {
522
+ "message": "Replicate API Proxy for LobeChat with Vision and File Support",
523
  "status": "running",
524
  "replicate_token_configured": bool(REPLICATE_API_TOKEN),
525
+ "version": "1.1.0",
526
+ "supported_models": list(MODEL_CONFIGS.keys()),
527
+ "vision_support": True,
528
+ "file_support": True,
529
+ "supported_text_files": list(SUPPORTED_TEXT_EXTENSIONS),
530
+ "supported_image_files": list(SUPPORTED_IMAGE_EXTENSIONS)
531
  }
532
 
533
  @app.get("/health")
 
537
  "status": "healthy",
538
  "replicate_token": "configured" if REPLICATE_API_TOKEN else "missing",
539
  "timestamp": asyncio.get_event_loop().time(),
540
+ "model_configs": MODEL_CONFIGS,
541
+ "supported_file_types": {
542
+ "text": list(SUPPORTED_TEXT_EXTENSIONS),
543
+ "image": list(SUPPORTED_IMAGE_EXTENSIONS)
544
+ }
545
  }
546
 
547
  @app.get("/v1/models")
 
568
  try:
569
  body = await request.json()
570
  logger.info(f"Received chat completion request")
571
+ logger.info(f"Client parameters: max_tokens={body.get('max_tokens', 'not set')}, temperature={body.get('temperature', 'not set')}")
572
  logger.info(f"Message count: {len(body.get('messages', []))}")
573
 
574
  # 转换请求格式
 
669
  "Cache-Control": "no-cache",
670
  "Connection": "keep-alive",
671
  "Access-Control-Allow-Origin": "*",
672
+ "X-Accel-Buffering": "no",
673
  }
674
  )
675
 
 
685
  prediction_url = f"{REPLICATE_BASE_URL}/predictions/{prediction_id}"
686
  headers = {"Authorization": f"Bearer {REPLICATE_API_TOKEN}"}
687
 
688
+ max_attempts = 60
689
  attempt = 0
690
 
691
  while attempt < max_attempts: