Repository navigation
Expand file tree
/
Copy pathassistant_api.py
More file actions
206 lines (167 loc) · 6.26 KB
/
Copy pathassistant_api.py
File metadata and controls
206 lines (167 loc) · 6.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
"""
AI 悬浮助手功能 - 翻译和总结 API
提供划词翻译和页面总结功能
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import httpx
import asyncio
import os
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).parent.absolute()
# 统一从项目根目录加载,避免 cwd 不同导致读取失败
load_dotenv(BASE_DIR / ".env", override=True)
load_dotenv(BASE_DIR / ".env.ai", override=True)
def get_cors_origins() -> list[str]:
raw = os.getenv("CORS_ALLOW_ORIGINS", "http://localhost:3000,http://localhost:3001")
origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
return origins or ["http://localhost:3000", "http://localhost:3001"]
app = FastAPI(title="AI Assistant API")
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=get_cors_origins(),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# LLM API 配置(从环境变量读取)
LLM_API_KEY = os.getenv('LLM_API_KEY') or os.getenv('OPENAI_API_KEY', 'your-api-key-here')
LLM_API_URL = os.getenv('LLM_API_URL', 'https://api.openai.com/v1/chat/completions')
LLM_MODEL = os.getenv('LLM_MODEL', 'gpt-3.5-turbo')
TRANSLATE_TIMEOUT = int(os.getenv('TRANSLATE_TIMEOUT', '30'))
SUMMARIZE_TIMEOUT = int(os.getenv('SUMMARIZE_TIMEOUT', '60'))
# --- 数据模型 ---
class TranslateRequest(BaseModel):
text: str
target_lang: str = "zh" # zh=中文,en=英文,ja=日文
class TranslateResponse(BaseModel):
translated_text: str
source_lang: Optional[str] = None
confidence: Optional[float] = None
class SummarizeRequest(BaseModel):
title: str
content: str
max_length: int = 500
class SummarizeResponse(BaseModel):
summary: str
key_points: Optional[list] = None
# --- 翻译功能 ---
@app.post("/api/translate", response_model=TranslateResponse)
async def translate_text(request: TranslateRequest):
"""
划词翻译功能
使用 LLM 进行智能翻译
"""
try:
# 构建翻译提示
lang_map = {
"zh": "中文",
"en": "英文",
"ja": "日文",
"ko": "韩文",
"fr": "法文",
"de": "德文",
}
target_lang_name = lang_map.get(request.target_lang, request.target_lang)
prompt = f"""请将以下文本翻译成{target_lang_name}。只返回翻译结果,不要其他内容。
原文:{request.text}
翻译:"""
# 调用 LLM API
async with httpx.AsyncClient(timeout=float(TRANSLATE_TIMEOUT)) as client:
response = await client.post(
LLM_API_URL,
headers={
"Authorization": f"Bearer {LLM_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": LLM_MODEL,
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"max_tokens": 500,
}
)
if response.status_code != 200:
raise HTTPException(status_code=500, detail="翻译服务不可用")
result = response.json()
translated_text = result["choices"][0]["message"]["content"].strip()
return TranslateResponse(
translated_text=translated_text,
source_lang=request.target_lang,
confidence=0.95
)
except httpx.RequestError as e:
raise HTTPException(status_code=503, detail=f"翻译请求失败:{str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"翻译失败:{str(e)}")
# --- 页面总结功能 ---
@app.post("/api/summarize", response_model=SummarizeResponse)
async def summarize_page(request: SummarizeRequest):
"""
页面总结功能
使用 LLM 提取页面核心内容
"""
try:
# 构建总结提示
prompt = f"""请对以下网页内容进行总结,要求:
1. 提取核心主题和关键信息
2. 使用清晰的 Markdown 格式
3. 总结长度控制在{request.max_length}字以内
网页标题:{request.title}
网页内容:
{request.content[:4000]} # 限制内容长度
请用以下格式返回总结:
## 📚 页面主题
[一句话概括]
## 🎯 核心内容
[分点列出关键信息]
## 💡 重要观点
[总结最重要的观点]
"""
# 调用 LLM API
async with httpx.AsyncClient(timeout=float(SUMMARIZE_TIMEOUT)) as client:
response = await client.post(
LLM_API_URL,
headers={
"Authorization": f"Bearer {LLM_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": LLM_MODEL,
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.5,
"max_tokens": 800,
}
)
if response.status_code != 200:
raise HTTPException(status_code=500, detail="总结服务不可用")
result = response.json()
summary = result["choices"][0]["message"]["content"].strip()
# 提取关键点(可选)
key_points = []
for line in summary.split("\n"):
if line.strip().startswith("- ") or line.strip().startswith("* "):
key_points.append(line.strip()[2:])
return SummarizeResponse(
summary=summary,
key_points=key_points[:5] # 最多 5 个关键点
)
except httpx.RequestError as e:
raise HTTPException(status_code=503, detail=f"总结请求失败:{str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"总结失败:{str(e)}")
# --- 健康检查 ---
@app.get("/health")
async def health_check():
return {"status": "ok", "service": "ai-assistant"}
# 如果要独立运行这个服务
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8084)