Commit ·
77eaf1d
1
Parent(s): a1634c8
feat: 图片模型连续对话自动上一次响应作为参考图
Browse files123456789101112137 unmodified lines21222324252665 unmodified lines929394959697"""API routes - OpenAI compatible endpoints"""from fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.responses import StreamingResponse, JSONResponsefrom typing import Listimport base64import reimport jsonfrom ..core.auth import verify_api_key_headerfrom ..core.models import ChatCompletionRequestfrom ..services.generation_handler import GenerationHandler, MODEL_CONFIGrouter = APIRouter()7 unmodified linesgeneration_handler = handler@router.get("/v1/models")async def list_models(api_key: str = Depends(verify_api_key_header)):"""List available models"""65 unmodified linesimage_bytes = base64.b64decode(image_base64)images.append(image_bytes)if not prompt:raise HTTPException(status_code=400, detail="Prompt cannot be empty")12345678910111213141516177 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465 unmodified lines130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""API routes - OpenAI compatible endpoints"""from fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.responses import StreamingResponse, JSONResponsefrom typing import List, Optionalimport base64import reimport jsonimport timefrom urllib.parse import urlparsefrom curl_cffi.requests import AsyncSessionfrom ..core.auth import verify_api_key_headerfrom ..core.models import ChatCompletionRequestfrom ..services.generation_handler import GenerationHandler, MODEL_CONFIGfrom ..core.logger import debug_loggerrouter = APIRouter()7 unmodified linesgeneration_handler = handlerasync def retrieve_image_data(url: str) -> Optional[bytes]:"""智能获取图片数据:1. 优先检查是否为本地 /tmp/ 缓存文件,如果是则直接读取磁盘2. 如果本地不存在或是外部链接,则进行网络下载"""# 优先尝试本地读取try:if "/tmp/" in url and generation_handler and generation_handler.file_cache:path = urlparse(url).pathfilename = path.split("/tmp/")[-1]local_file_path = generation_handler.file_cache.cache_dir / filenameif local_file_path.exists() and local_file_path.is_file():data = local_file_path.read_bytes()if data:return dataexcept Exception as e:debug_logger.log_warning(f"[CONTEXT] 本地缓存读取失败: {str(e)}")# 回退逻辑:网络下载try:async with AsyncSession() as session:response = await session.get(url, timeout=30, impersonate="chrome110", verify=False)if response.status_code == 200:return response.contentelse:debug_logger.log_warning(f"[CONTEXT] 图片下载失败,状态码: {response.status_code}")except Exception as e:debug_logger.log_error(f"[CONTEXT] 图片下载异常: {str(e)}")return None@router.get("/v1/models")async def list_models(api_key: str = Depends(verify_api_key_header)):"""List available models"""65 unmodified linesimage_bytes = base64.b64decode(image_base64)images.append(image_bytes)# 自动参考图:仅对图片模型生效model_config = MODEL_CONFIG.get(request.model)if model_config and model_config["type"] == "image" and not images and len(request.messages) > 1:debug_logger.log_info(f"[CONTEXT] 开始查找历史参考图,消息数量: {len(request.messages)}")# 如果当前请求没有上传图片,则尝试从历史记录中寻找最近的一张生成图for msg in reversed(request.messages[:-1]):if msg.role == "assistant" and isinstance(msg.content, str):# 匹配 Markdown 图片格式: matches = re.findall(r"!\[.*?\]\((.*?)\)", msg.content)if matches:last_image_url = matches[-1]if last_image_url.startswith("http"):try:downloaded_bytes = await retrieve_image_data(last_image_url)if downloaded_bytes and len(downloaded_bytes) > 0:images.append(downloaded_bytes)debug_logger.log_info(f"[CONTEXT] ✅ 自动使用历史参考图: {last_image_url}")breakelse:debug_logger.log_warning(f"[CONTEXT] 图片下载失败或为空,尝试下一个: {last_image_url}")except Exception as e:debug_logger.log_error(f"[CONTEXT] 处理参考图时出错: {str(e)}")# 继续尝试下一个图片if not prompt:raise HTTPException(status_code=400, detail="Prompt cannot be empty")
src/api/routes.py+66-1