上传文件至 /
This commit is contained in:
91
智语医助11-28修改-多图片上传中间层.py
Normal file
91
智语医助11-28修改-多图片上传中间层.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
from fastapi import FastAPI, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
import httpx
|
||||||
|
import random
|
||||||
|
import logging
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 直接在代码中定义目标 URL 和 API Key
|
||||||
|
TARGET_URL = "https://ue-ai.excn.vip/api/v1/chat/completions" # 替换为实际目标接口地址
|
||||||
|
API_KEY = "fastgpt-tkMWhPfR4tLmJVMA46KrA1zR89W1hbbV3Kcv4CYPVVUvvR5FsKDJ" # 替换为实际的 API Key
|
||||||
|
|
||||||
|
|
||||||
|
class ImageRequest(BaseModel):
|
||||||
|
images: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
def _id():
|
||||||
|
return ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=7))
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/process-images")
|
||||||
|
async def process_images(request: ImageRequest):
|
||||||
|
image_data = request.images
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# 设置最长等待响应时间为 500 秒
|
||||||
|
timeout = httpx.Timeout(500.0, connect=10.0)
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||||
|
for unique_id, image_url in image_data.items():
|
||||||
|
payload = {
|
||||||
|
"chatId": _id(),
|
||||||
|
"stream": False,
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "image_url", "image_url": {"url": image_url}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = await client.post(
|
||||||
|
url=TARGET_URL,
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {API_KEY}",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
json=payload
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
# Log the entire response content for debugging
|
||||||
|
logger.info(f"Response content: {response.content}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
response_data = response.json()
|
||||||
|
except ValueError:
|
||||||
|
logger.error("Failed to decode JSON from response")
|
||||||
|
logger.error(f"Non-JSON response content: {response.text}")
|
||||||
|
raise HTTPException(status_code=500, detail="Response is not valid JSON")
|
||||||
|
|
||||||
|
# Extract the relevant message content from the response
|
||||||
|
result_message = None
|
||||||
|
if "choices" in response_data and len(response_data["choices"]) > 0:
|
||||||
|
message_content = response_data["choices"][0]["message"]["content"]
|
||||||
|
result_message = message_content
|
||||||
|
|
||||||
|
results.append({"id": unique_id, "result": result_message})
|
||||||
|
logger.info(f"Processed image {unique_id} successfully.")
|
||||||
|
|
||||||
|
except httpx.ReadTimeout:
|
||||||
|
logger.error("Request timed out.")
|
||||||
|
raise HTTPException(status_code=504, detail="Request to target service timed out.")
|
||||||
|
except httpx.HTTPStatusError as e:
|
||||||
|
logger.error(f"HTTP error occurred: {str(e)}")
|
||||||
|
logger.error(f"Response status code: {e.response.status_code}, content: {e.response.text}")
|
||||||
|
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Unexpected error occurred: {str(e)}")
|
||||||
|
logger.error(traceback.format_exc()) # Log the stack trace
|
||||||
|
raise HTTPException(status_code=500, detail="An unexpected error occurred")
|
||||||
|
|
||||||
|
return {"results": results}
|
||||||
Reference in New Issue
Block a user