wanazesi commited on
Commit
40610d7
·
verified ·
1 Parent(s): b2d812c

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +84 -0
main.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import asyncio
4
+ import httpx
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.responses import StreamingResponse
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+
9
+ app = FastAPI()
10
+
11
+ # 允许跨域请求
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ # 从环境变量获取你的配置
20
+ AIROPS_API_KEY = os.environ.get("AIROPS_API_KEY", "")
21
+ AIROPS_APP_ID = os.environ.get("AIROPS_APP_ID", "")
22
+ INPUT_VAR = os.environ.get("INPUT_VAR_NAME", "input")
23
+
24
+ @app.post("/v1/chat/completions")
25
+ async def chat_completions(request: Request):
26
+ try:
27
+ body = await request.json()
28
+ except:
29
+ body = {}
30
+
31
+ messages = body.get("messages", [])
32
+ # 获取用户发送的最后一条消息
33
+ user_msg = messages[-1]["content"] if messages else ""
34
+
35
+ headers = {
36
+ "Authorization": f"Bearer {AIROPS_API_KEY}",
37
+ "Content-Type": "application/json"
38
+ }
39
+
40
+ # 构造 AirOps 需要的数据格式
41
+ payload = {
42
+ "inputs": {
43
+ INPUT_VAR: user_msg
44
+ }
45
+ }
46
+
47
+ async def generate():
48
+ # 设置 120 秒超时,防止长文本生成失败
49
+ async with httpx.AsyncClient(timeout=120.0) as client:
50
+ url = f"https://api.airops.com/public_api/airops_apps/{AIROPS_APP_ID}/execute"
51
+
52
+ try:
53
+ response = await client.post(url, headers=headers, json=payload)
54
+ if response.status_code == 200:
55
+ data = response.json()
56
+ # 提取 AirOps 返回的文本结果
57
+ result_text = data.get("result", "")
58
+
59
+ if isinstance(result_text, dict) or isinstance(result_text, list):
60
+ result_text = json.dumps(result_text, ensure_ascii=False)
61
+
62
+ # 核心:将静态结果转换为完美的 OpenAI 流式打字机输出
63
+ chunk_size = 3
64
+ for i in range(0, len(result_text), chunk_size):
65
+ chunk = result_text[i:i+chunk_size]
66
+ openai_chunk = {
67
+ "id": "chatcmpl-airops",
68
+ "object": "chat.completion.chunk",
69
+ "choices": [{"delta": {"content": chunk}}]
70
+ }
71
+ yield f"data: {json.dumps(openai_chunk)}\n\n"
72
+ await asyncio.sleep(0.01) # 极速打字机效果
73
+
74
+ yield "data: [DONE]\n\n"
75
+ else:
76
+ err = {"error": f"AirOps 接口报错: {response.text}"}
77
+ yield f"data: {json.dumps(err)}\n\n"
78
+ yield "data: [DONE]\n\n"
79
+ except Exception as e:
80
+ err = {"error": f"代理服务器内部错误: {str(e)}"}
81
+ yield f"data: {json.dumps(err)}\n\n"
82
+ yield "data: [DONE]\n\n"
83
+
84
+ return StreamingResponse(generate(), media_type="text/event-stream")