zhiyu1998 commited on
Commit
b907d8f
·
1 Parent(s): 7c9f7a7

📄docs: 更新版本号至0.1.1并添加Ruff配置

Browse files
Files changed (3) hide show
  1. README.md +17 -45
  2. main.py +268 -313
  3. pyproject.toml +16 -2
README.md CHANGED
@@ -54,18 +54,6 @@ SECURE_1PSIDTS = "COOKIE VALUE HERE"
54
 
55
  4. 服务将在 http://0.0.0.0:8000 上运行
56
 
57
- ### 常见问题
58
-
59
- 如果遇到 `Failed to initialize client` 错误,这通常是因为 Cookie 已过期。请按以下步骤更新:
60
-
61
- 1. 访问 [Google Gemini](https://gemini.google.com/) 并登录
62
- 2. 打开浏览器开发工具 (F12)
63
- 3. 切换到 "Application" 或 "应用程序" 标签
64
- 4. 在左侧找到 "Cookies" > "gemini.google.com"
65
- 5. 复制 `__Secure-1PSID` 和 `__Secure-1PSIDTS` 的值
66
- 6. 更新 `.env` 文件
67
- 7. 重启容器: `docker-compose restart`
68
-
69
  ### 其他 Docker 命令
70
 
71
  ```bash
@@ -82,41 +70,25 @@ docker-compose down
82
  docker-compose up -d --build
83
  ```
84
 
85
- ## 环境变量配置
86
-
87
- 服务需要以下环境变量来与Gemini API进行通信:
88
-
89
- - `SECURE_1PSID` - Google账号的身份验证Cookie
90
- - `SECURE_1PSIDTS` - Google账号的身份验证Cookie
91
-
92
- ### Docker 环境变量配置
93
-
94
- 使用`.env`文件设置环境变量(推荐方式):
95
-
96
- 1. 创建`.env`文件,参考`.env.example`:
97
- ```bash
98
- # 复制示例文件
99
- cp .env.example .env
100
-
101
- # 编辑.env文件
102
- nano .env # 或使用其他编辑器
103
- ```
104
 
105
- 2. 在`.env`文件中设置变量(**注意:不要使用引号**):
106
- ```
107
- SECURE_1PSID=你的SECURE_1PSID值
108
- SECURE_1PSIDTS=你的SECURE_1PSIDTS值
109
- ```
110
 
111
- 3. 确保值格式正确:
112
- - 不要在值两边加引号
113
- - 确保没有多余的空格
114
- - 复制时确保没有包含不可见字符
115
 
116
- 如果环境变量仍然没有被正确加载,可以尝试直接在`docker-compose.yml`中的`environment`部分设置。
117
 
118
- ## API端点
 
 
119
 
120
- - `GET /`: 服务状态检查
121
- - `GET /v1/models`: 获取可用模型列表
122
- - `POST /v1/chat/completions`: 与模型聊天 (类似OpenAI接口)
 
 
 
 
 
 
54
 
55
  4. 服务将在 http://0.0.0.0:8000 上运行
56
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  ### 其他 Docker 命令
58
 
59
  ```bash
 
70
  docker-compose up -d --build
71
  ```
72
 
73
+ ## API端点
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ - `GET /`: 服务状态检查
76
+ - `GET /v1/models`: 获取可用模型列表
77
+ - `POST /v1/chat/completions`: 与模型聊天 (类似OpenAI接口)
 
 
78
 
79
+ ## 常见问题
 
 
 
80
 
81
+ ### 服务器报 500 问题解决方案
82
 
83
+ 500 的问题一般是 IP 不太行 或者 请求太频繁(后者等待一段时间或者重新新建一个隐身标签登录一下重新给 Secure_1PSID 和 Secure_1PSIDTS 即可),见 issue:
84
+ - [__Secure-1PSIDTS · Issue #6 · HanaokaYuzu/Gemini-API](https://github.com/HanaokaYuzu/Gemini-API/issues/6)
85
+ - [Failed to initialize client. SECURE_1PSIDTS could get expired frequently · Issue #72 · HanaokaYuzu/Gemini-API](https://github.com/HanaokaYuzu/Gemini-API/issues/72)
86
 
87
+ 解决步骤:
88
+ 1. 使用隐身标签访问 [Google Gemini](https://gemini.google.com/) 并登录
89
+ 2. 打开浏览器开发工具 (F12)
90
+ 3. 切换到 "Application" 或 "应用程序" 标签
91
+ 4. 在左侧找到 "Cookies" > "gemini.google.com"
92
+ 5. 复制 `__Secure-1PSID` 和 `__Secure-1PSIDTS` 的值
93
+ 6. 更新 `.env` 文件
94
+ 7. 重新构建并启动: `docker-compose up -d --build`
main.py CHANGED
@@ -27,11 +27,11 @@ app = FastAPI(title="Gemini API FastAPI Server")
27
 
28
  # Add CORS middleware
29
  app.add_middleware(
30
- CORSMiddleware,
31
- allow_origins=["*"],
32
- allow_credentials=True,
33
- allow_methods=["*"],
34
- allow_headers=["*"],
35
  )
36
 
37
  # Global client
@@ -43,369 +43,324 @@ SECURE_1PSIDTS = os.environ.get("SECURE_1PSIDTS", "")
43
 
44
  # Print debug info at startup
45
  if not SECURE_1PSID or not SECURE_1PSIDTS:
46
- logger.warning("⚠️ Gemini API credentials are not set or empty! Please check your environment variables.")
47
- logger.warning("Make sure SECURE_1PSID and SECURE_1PSIDTS are correctly set in your .env file or environment.")
48
- logger.warning("If using Docker, ensure the .env file is correctly mounted and formatted.")
49
- logger.warning("Example format in .env file (no quotes):")
50
- logger.warning("SECURE_1PSID=your_secure_1psid_value_here")
51
- logger.warning("SECURE_1PSIDTS=your_secure_1psidts_value_here")
52
  else:
53
- # Only log the first few characters for security
54
- logger.info(f"Credentials found. SECURE_1PSID starts with: {SECURE_1PSID[:5]}...")
55
- logger.info(f"Credentials found. SECURE_1PSIDTS starts with: {SECURE_1PSIDTS[:5]}...")
 
56
 
57
  # Pydantic models for API requests and responses
58
  class ContentItem(BaseModel):
59
- type: str
60
- text: Optional[str] = None
61
- image_url: Optional[Dict[str, str]] = None
 
62
 
63
  class Message(BaseModel):
64
- role: str
65
- content: Union[str, List[ContentItem]]
66
- name: Optional[str] = None
67
 
68
 
69
  class ChatCompletionRequest(BaseModel):
70
- model: str
71
- messages: List[Message]
72
- temperature: Optional[float] = 0.7
73
- top_p: Optional[float] = 1.0
74
- n: Optional[int] = 1
75
- stream: Optional[bool] = False
76
- max_tokens: Optional[int] = None
77
- presence_penalty: Optional[float] = 0
78
- frequency_penalty: Optional[float] = 0
79
- user: Optional[str] = None
80
 
81
 
82
  class Choice(BaseModel):
83
- index: int
84
- message: Message
85
- finish_reason: str
86
 
87
 
88
  class Usage(BaseModel):
89
- prompt_tokens: int
90
- completion_tokens: int
91
- total_tokens: int
92
 
93
 
94
  class ChatCompletionResponse(BaseModel):
95
- id: str
96
- object: str = "chat.completion"
97
- created: int
98
- model: str
99
- choices: List[Choice]
100
- usage: Usage
101
 
102
 
103
  class ModelData(BaseModel):
104
- id: str
105
- object: str = "model"
106
- created: int
107
- owned_by: str = "google"
108
 
109
 
110
  class ModelList(BaseModel):
111
- object: str = "list"
112
- data: List[ModelData]
113
 
114
 
115
  # Simple error handler middleware
116
  @app.middleware("http")
117
  async def error_handling(request: Request, call_next):
118
- try:
119
- return await call_next(request)
120
- except Exception as e:
121
- logger.error(f"Request failed: {str(e)}")
122
- return JSONResponse(
123
- status_code=500,
124
- content={ "error": { "message": str(e), "type": "internal_server_error" } }
125
- )
126
 
127
 
128
  # Get list of available models
129
  @app.get("/v1/models")
130
  async def list_models():
131
- """返回 gemini_webapi 中声明的模型列表"""
132
- now = int(datetime.now(tz=timezone.utc).timestamp())
133
- data = [
134
- {
135
- "id": m.model_name, # 如 "gemini-2.0-flash"
136
- "object": "model",
137
- "created": now,
138
- "owned_by": "google-gemini-web"
139
- }
140
- for m in Model
141
- ]
142
- print(data)
143
- return {"object": "list", "data": data}
144
 
145
 
146
  # Helper to convert between Gemini and OpenAI model names
147
  def map_model_name(openai_model_name: str) -> Model:
148
- """根据模型名称字符串查找匹配的 Model 枚举值"""
149
- # 打印所有可用模型以便调试
150
- all_models = [m.model_name if hasattr(m, "model_name") else str(m) for m in Model]
151
- logger.info(f"Available models: {all_models}")
152
-
153
- # 首先尝试直接查找匹配的模型名称
154
- for m in Model:
155
- model_name = m.model_name if hasattr(m, "model_name") else str(m)
156
- if openai_model_name.lower() in model_name.lower():
157
- return m
158
-
159
- # 如果找不到匹配项,使用默认映射
160
- model_keywords = {
161
- "gemini-pro": ["pro", "2.0"],
162
- "gemini-pro-vision": ["vision", "pro"],
163
- "gemini-flash": ["flash", "2.0"],
164
- "gemini-1.5-pro": ["1.5", "pro"],
165
- "gemini-1.5-flash": ["1.5", "flash"],
166
- }
167
-
168
- # 根据关键词匹配
169
- keywords = model_keywords.get(openai_model_name, ["pro"]) # 默认使用pro模型
170
-
171
- for m in Model:
172
- model_name = m.model_name if hasattr(m, "model_name") else str(m)
173
- if all(kw.lower() in model_name.lower() for kw in keywords):
174
- return m
175
-
176
- # 如果还是找不到,返回第一个模型
177
- return next(iter(Model))
178
 
179
 
180
  # Prepare conversation history from OpenAI messages format
181
  def prepare_conversation(messages: List[Message]) -> tuple:
182
- conversation = ""
183
- temp_files = []
184
-
185
- for msg in messages:
186
- if isinstance(msg.content, str):
187
- # String content handling
188
- if msg.role == "system":
189
- conversation += f"System: {msg.content}\n\n"
190
- elif msg.role == "user":
191
- conversation += f"Human: {msg.content}\n\n"
192
- elif msg.role == "assistant":
193
- conversation += f"Assistant: {msg.content}\n\n"
194
- else:
195
- # Mixed content handling
196
- if msg.role == "user":
197
- conversation += "Human: "
198
- elif msg.role == "system":
199
- conversation += "System: "
200
- elif msg.role == "assistant":
201
- conversation += "Assistant: "
202
-
203
- for item in msg.content:
204
- if item.type == "text":
205
- conversation += item.text or ""
206
- elif item.type == "image_url" and item.image_url:
207
- # Handle image
208
- image_url = item.image_url.get("url", "")
209
- if image_url.startswith("data:image/"):
210
- # Process base64 encoded image
211
- try:
212
- # Extract the base64 part
213
- base64_data = image_url.split(",")[1]
214
- image_data = base64.b64decode(base64_data)
215
-
216
- # Create temporary file to hold the image
217
- with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
218
- tmp.write(image_data)
219
- temp_files.append(tmp.name)
220
- except Exception as e:
221
- logger.error(f"Error processing base64 image: {str(e)}")
222
-
223
- conversation += "\n\n"
224
-
225
- # Add a final prompt for the assistant to respond to
226
- conversation += "Assistant: "
227
-
228
- return conversation, temp_files
229
 
230
 
231
  # Dependency to get the initialized Gemini client
232
  async def get_gemini_client():
233
- global gemini_client
234
- if gemini_client is None:
235
- try:
236
- gemini_client = GeminiClient(SECURE_1PSID, SECURE_1PSIDTS)
237
- await gemini_client.init(timeout=300)
238
- except Exception as e:
239
- logger.error(f"Failed to initialize Gemini client: {str(e)}")
240
- raise HTTPException(
241
- status_code=500,
242
- detail=f"Failed to initialize Gemini client: {str(e)}"
243
- )
244
- return gemini_client
245
 
246
 
247
  @app.post("/v1/chat/completions")
248
  async def create_chat_completion(request: ChatCompletionRequest):
249
- try:
250
- # 确保客户端已初始化
251
- global gemini_client
252
- if gemini_client is None:
253
- gemini_client = GeminiClient(SECURE_1PSID, SECURE_1PSIDTS)
254
- await gemini_client.init(timeout=300)
255
- logger.info("Gemini client initialized successfully")
256
-
257
- # 转换消息为对话格式
258
- conversation, temp_files = prepare_conversation(request.messages)
259
- logger.info(f"Prepared conversation: {conversation}")
260
- logger.info(f"Temp files: {temp_files}")
261
-
262
- # 获取适当的模型
263
- model = map_model_name(request.model)
264
- logger.info(f"Using model: {model}")
265
-
266
- # 生成响应
267
- logger.info("Sending request to Gemini...")
268
- if temp_files:
269
- # With files
270
- response = await gemini_client.generate_content(
271
- conversation,
272
- files=temp_files,
273
- model=model
274
- )
275
- else:
276
- # Text only
277
- response = await gemini_client.generate_content(conversation, model=model)
278
-
279
- # 清理临时文件
280
- for temp_file in temp_files:
281
- try:
282
- os.unlink(temp_file)
283
- except Exception as e:
284
- logger.warning(f"Failed to delete temp file {temp_file}: {str(e)}")
285
-
286
- # 提取文本响应
287
- reply_text = ""
288
- if hasattr(response, "text"):
289
- reply_text = response.text
290
- else:
291
- reply_text = str(response)
292
-
293
- logger.info(f"Response: {reply_text}")
294
-
295
- if not reply_text or reply_text.strip() == "":
296
- logger.warning("Empty response received from Gemini")
297
- reply_text = "服务器返回了空响应。请检查 Gemini API 凭据是否有效。"
298
-
299
- # 创建响应对象
300
- completion_id = f"chatcmpl-{uuid.uuid4()}"
301
- created_time = int(time.time())
302
-
303
- # 检查客户端是否请求流式响应
304
- if request.stream:
305
- # 实现流式响应
306
- async def generate_stream():
307
- # 创建 SSE 格式的流式响应
308
- # 先发送开始事件
309
- data = {
310
- "id": completion_id,
311
- "object": "chat.completion.chunk",
312
- "created": created_time,
313
- "model": request.model,
314
- "choices": [
315
- {
316
- "index": 0,
317
- "delta": {
318
- "role": "assistant"
319
- },
320
- "finish_reason": None
321
- }
322
- ]
323
- }
324
- yield f"data: {json.dumps(data)}\n\n"
325
-
326
- # 模拟流式输出 - 将文本按字符分割发送
327
- for char in reply_text:
328
- data = {
329
- "id": completion_id,
330
- "object": "chat.completion.chunk",
331
- "created": created_time,
332
- "model": request.model,
333
- "choices": [
334
- {
335
- "index": 0,
336
- "delta": {
337
- "content": char
338
- },
339
- "finish_reason": None
340
- }
341
- ]
342
- }
343
- yield f"data: {json.dumps(data)}\n\n"
344
- # 可选:添加短暂延迟以模拟真实的流式输出
345
- await asyncio.sleep(0.01)
346
-
347
- # 发送结束事件
348
- data = {
349
- "id": completion_id,
350
- "object": "chat.completion.chunk",
351
- "created": created_time,
352
- "model": request.model,
353
- "choices": [
354
- {
355
- "index": 0,
356
- "delta": { },
357
- "finish_reason": "stop"
358
- }
359
- ]
360
- }
361
- yield f"data: {json.dumps(data)}\n\n"
362
- yield "data: [DONE]\n\n"
363
-
364
- return StreamingResponse(
365
- generate_stream(),
366
- media_type="text/event-stream"
367
- )
368
- else:
369
- # 非流式响应(原来的逻辑)
370
- result = {
371
- "id": completion_id,
372
- "object": "chat.completion",
373
- "created": created_time,
374
- "model": request.model,
375
- "choices": [
376
- {
377
- "index": 0,
378
- "message": {
379
- "role": "assistant",
380
- "content": reply_text
381
- },
382
- "finish_reason": "stop"
383
- }
384
- ],
385
- "usage": {
386
- "prompt_tokens": len(conversation.split()),
387
- "completion_tokens": len(reply_text.split()),
388
- "total_tokens": len(conversation.split()) + len(reply_text.split())
389
- }
390
- }
391
-
392
- logger.info(f"Returning response: {result}")
393
- return result
394
-
395
- except Exception as e:
396
- logger.error(f"Error generating completion: {str(e)}", exc_info=True)
397
- raise HTTPException(
398
- status_code=500,
399
- detail=f"Error generating completion: {str(e)}"
400
- )
401
 
402
 
403
  @app.get("/")
404
  async def root():
405
- return { "status": "online", "message": "Gemini API FastAPI Server is running" }
406
 
407
 
408
  if __name__ == "__main__":
409
- import uvicorn
410
 
411
- uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="info")
 
27
 
28
  # Add CORS middleware
29
  app.add_middleware(
30
+ CORSMiddleware,
31
+ allow_origins=["*"],
32
+ allow_credentials=True,
33
+ allow_methods=["*"],
34
+ allow_headers=["*"],
35
  )
36
 
37
  # Global client
 
43
 
44
  # Print debug info at startup
45
  if not SECURE_1PSID or not SECURE_1PSIDTS:
46
+ logger.warning("⚠️ Gemini API credentials are not set or empty! Please check your environment variables.")
47
+ logger.warning("Make sure SECURE_1PSID and SECURE_1PSIDTS are correctly set in your .env file or environment.")
48
+ logger.warning("If using Docker, ensure the .env file is correctly mounted and formatted.")
49
+ logger.warning("Example format in .env file (no quotes):")
50
+ logger.warning("SECURE_1PSID=your_secure_1psid_value_here")
51
+ logger.warning("SECURE_1PSIDTS=your_secure_1psidts_value_here")
52
  else:
53
+ # Only log the first few characters for security
54
+ logger.info(f"Credentials found. SECURE_1PSID starts with: {SECURE_1PSID[:5]}...")
55
+ logger.info(f"Credentials found. SECURE_1PSIDTS starts with: {SECURE_1PSIDTS[:5]}...")
56
+
57
 
58
  # Pydantic models for API requests and responses
59
  class ContentItem(BaseModel):
60
+ type: str
61
+ text: Optional[str] = None
62
+ image_url: Optional[Dict[str, str]] = None
63
+
64
 
65
  class Message(BaseModel):
66
+ role: str
67
+ content: Union[str, List[ContentItem]]
68
+ name: Optional[str] = None
69
 
70
 
71
  class ChatCompletionRequest(BaseModel):
72
+ model: str
73
+ messages: List[Message]
74
+ temperature: Optional[float] = 0.7
75
+ top_p: Optional[float] = 1.0
76
+ n: Optional[int] = 1
77
+ stream: Optional[bool] = False
78
+ max_tokens: Optional[int] = None
79
+ presence_penalty: Optional[float] = 0
80
+ frequency_penalty: Optional[float] = 0
81
+ user: Optional[str] = None
82
 
83
 
84
  class Choice(BaseModel):
85
+ index: int
86
+ message: Message
87
+ finish_reason: str
88
 
89
 
90
  class Usage(BaseModel):
91
+ prompt_tokens: int
92
+ completion_tokens: int
93
+ total_tokens: int
94
 
95
 
96
  class ChatCompletionResponse(BaseModel):
97
+ id: str
98
+ object: str = "chat.completion"
99
+ created: int
100
+ model: str
101
+ choices: List[Choice]
102
+ usage: Usage
103
 
104
 
105
  class ModelData(BaseModel):
106
+ id: str
107
+ object: str = "model"
108
+ created: int
109
+ owned_by: str = "google"
110
 
111
 
112
  class ModelList(BaseModel):
113
+ object: str = "list"
114
+ data: List[ModelData]
115
 
116
 
117
  # Simple error handler middleware
118
  @app.middleware("http")
119
  async def error_handling(request: Request, call_next):
120
+ try:
121
+ return await call_next(request)
122
+ except Exception as e:
123
+ logger.error(f"Request failed: {str(e)}")
124
+ return JSONResponse(status_code=500, content={"error": {"message": str(e), "type": "internal_server_error"}})
 
 
 
125
 
126
 
127
  # Get list of available models
128
  @app.get("/v1/models")
129
  async def list_models():
130
+ """返回 gemini_webapi 中声明的模型列表"""
131
+ now = int(datetime.now(tz=timezone.utc).timestamp())
132
+ data = [
133
+ {
134
+ "id": m.model_name, # 如 "gemini-2.0-flash"
135
+ "object": "model",
136
+ "created": now,
137
+ "owned_by": "google-gemini-web",
138
+ }
139
+ for m in Model
140
+ ]
141
+ print(data)
142
+ return {"object": "list", "data": data}
143
 
144
 
145
  # Helper to convert between Gemini and OpenAI model names
146
  def map_model_name(openai_model_name: str) -> Model:
147
+ """根据模型名称字符串查找匹配的 Model 枚举值"""
148
+ # 打印所有可用模型以便调试
149
+ all_models = [m.model_name if hasattr(m, "model_name") else str(m) for m in Model]
150
+ logger.info(f"Available models: {all_models}")
151
+
152
+ # 首先尝试直接查找匹配的模型名称
153
+ for m in Model:
154
+ model_name = m.model_name if hasattr(m, "model_name") else str(m)
155
+ if openai_model_name.lower() in model_name.lower():
156
+ return m
157
+
158
+ # 如果找不到匹配项,使用默认映射
159
+ model_keywords = {
160
+ "gemini-pro": ["pro", "2.0"],
161
+ "gemini-pro-vision": ["vision", "pro"],
162
+ "gemini-flash": ["flash", "2.0"],
163
+ "gemini-1.5-pro": ["1.5", "pro"],
164
+ "gemini-1.5-flash": ["1.5", "flash"],
165
+ }
166
+
167
+ # 根据关键词匹配
168
+ keywords = model_keywords.get(openai_model_name, ["pro"]) # 默认使用pro模型
169
+
170
+ for m in Model:
171
+ model_name = m.model_name if hasattr(m, "model_name") else str(m)
172
+ if all(kw.lower() in model_name.lower() for kw in keywords):
173
+ return m
174
+
175
+ # 如果还是找不到,返回第一个模型
176
+ return next(iter(Model))
177
 
178
 
179
  # Prepare conversation history from OpenAI messages format
180
  def prepare_conversation(messages: List[Message]) -> tuple:
181
+ conversation = ""
182
+ temp_files = []
183
+
184
+ for msg in messages:
185
+ if isinstance(msg.content, str):
186
+ # String content handling
187
+ if msg.role == "system":
188
+ conversation += f"System: {msg.content}\n\n"
189
+ elif msg.role == "user":
190
+ conversation += f"Human: {msg.content}\n\n"
191
+ elif msg.role == "assistant":
192
+ conversation += f"Assistant: {msg.content}\n\n"
193
+ else:
194
+ # Mixed content handling
195
+ if msg.role == "user":
196
+ conversation += "Human: "
197
+ elif msg.role == "system":
198
+ conversation += "System: "
199
+ elif msg.role == "assistant":
200
+ conversation += "Assistant: "
201
+
202
+ for item in msg.content:
203
+ if item.type == "text":
204
+ conversation += item.text or ""
205
+ elif item.type == "image_url" and item.image_url:
206
+ # Handle image
207
+ image_url = item.image_url.get("url", "")
208
+ if image_url.startswith("data:image/"):
209
+ # Process base64 encoded image
210
+ try:
211
+ # Extract the base64 part
212
+ base64_data = image_url.split(",")[1]
213
+ image_data = base64.b64decode(base64_data)
214
+
215
+ # Create temporary file to hold the image
216
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
217
+ tmp.write(image_data)
218
+ temp_files.append(tmp.name)
219
+ except Exception as e:
220
+ logger.error(f"Error processing base64 image: {str(e)}")
221
+
222
+ conversation += "\n\n"
223
+
224
+ # Add a final prompt for the assistant to respond to
225
+ conversation += "Assistant: "
226
+
227
+ return conversation, temp_files
228
 
229
 
230
  # Dependency to get the initialized Gemini client
231
  async def get_gemini_client():
232
+ global gemini_client
233
+ if gemini_client is None:
234
+ try:
235
+ gemini_client = GeminiClient(SECURE_1PSID, SECURE_1PSIDTS)
236
+ await gemini_client.init(timeout=300)
237
+ except Exception as e:
238
+ logger.error(f"Failed to initialize Gemini client: {str(e)}")
239
+ raise HTTPException(status_code=500, detail=f"Failed to initialize Gemini client: {str(e)}")
240
+ return gemini_client
 
 
 
241
 
242
 
243
  @app.post("/v1/chat/completions")
244
  async def create_chat_completion(request: ChatCompletionRequest):
245
+ try:
246
+ # 确保客户端已初始化
247
+ global gemini_client
248
+ if gemini_client is None:
249
+ gemini_client = GeminiClient(SECURE_1PSID, SECURE_1PSIDTS)
250
+ await gemini_client.init(timeout=300)
251
+ logger.info("Gemini client initialized successfully")
252
+
253
+ # 转换消息为对话格式
254
+ conversation, temp_files = prepare_conversation(request.messages)
255
+ logger.info(f"Prepared conversation: {conversation}")
256
+ logger.info(f"Temp files: {temp_files}")
257
+
258
+ # 获取适当的模型
259
+ model = map_model_name(request.model)
260
+ logger.info(f"Using model: {model}")
261
+
262
+ # 生成响应
263
+ logger.info("Sending request to Gemini...")
264
+ if temp_files:
265
+ # With files
266
+ response = await gemini_client.generate_content(conversation, files=temp_files, model=model)
267
+ else:
268
+ # Text only
269
+ response = await gemini_client.generate_content(conversation, model=model)
270
+
271
+ # 清理临时文件
272
+ for temp_file in temp_files:
273
+ try:
274
+ os.unlink(temp_file)
275
+ except Exception as e:
276
+ logger.warning(f"Failed to delete temp file {temp_file}: {str(e)}")
277
+
278
+ # 提取文本响应
279
+ reply_text = ""
280
+ if hasattr(response, "text"):
281
+ reply_text = response.text
282
+ else:
283
+ reply_text = str(response)
284
+
285
+ logger.info(f"Response: {reply_text}")
286
+
287
+ if not reply_text or reply_text.strip() == "":
288
+ logger.warning("Empty response received from Gemini")
289
+ reply_text = "服务器返回了空响应。请检查 Gemini API 凭据是否有效。"
290
+
291
+ # 创建响应对象
292
+ completion_id = f"chatcmpl-{uuid.uuid4()}"
293
+ created_time = int(time.time())
294
+
295
+ # 检查客户端是否请求流式响应
296
+ if request.stream:
297
+ # 实现流式响应
298
+ async def generate_stream():
299
+ # 创建 SSE 格式的流式响应
300
+ # 先发送开始事件
301
+ data = {
302
+ "id": completion_id,
303
+ "object": "chat.completion.chunk",
304
+ "created": created_time,
305
+ "model": request.model,
306
+ "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
307
+ }
308
+ yield f"data: {json.dumps(data)}\n\n"
309
+
310
+ # 模拟流式输出 - ���文本按字符分割发送
311
+ for char in reply_text:
312
+ data = {
313
+ "id": completion_id,
314
+ "object": "chat.completion.chunk",
315
+ "created": created_time,
316
+ "model": request.model,
317
+ "choices": [{"index": 0, "delta": {"content": char}, "finish_reason": None}],
318
+ }
319
+ yield f"data: {json.dumps(data)}\n\n"
320
+ # 可选:添加短暂延迟以模拟真实的流式输出
321
+ await asyncio.sleep(0.01)
322
+
323
+ # 发送结束事件
324
+ data = {
325
+ "id": completion_id,
326
+ "object": "chat.completion.chunk",
327
+ "created": created_time,
328
+ "model": request.model,
329
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
330
+ }
331
+ yield f"data: {json.dumps(data)}\n\n"
332
+ yield "data: [DONE]\n\n"
333
+
334
+ return StreamingResponse(generate_stream(), media_type="text/event-stream")
335
+ else:
336
+ # 非流式响应(原来的逻辑)
337
+ result = {
338
+ "id": completion_id,
339
+ "object": "chat.completion",
340
+ "created": created_time,
341
+ "model": request.model,
342
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": reply_text}, "finish_reason": "stop"}],
343
+ "usage": {
344
+ "prompt_tokens": len(conversation.split()),
345
+ "completion_tokens": len(reply_text.split()),
346
+ "total_tokens": len(conversation.split()) + len(reply_text.split()),
347
+ },
348
+ }
349
+
350
+ logger.info(f"Returning response: {result}")
351
+ return result
352
+
353
+ except Exception as e:
354
+ logger.error(f"Error generating completion: {str(e)}", exc_info=True)
355
+ raise HTTPException(status_code=500, detail=f"Error generating completion: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
 
358
  @app.get("/")
359
  async def root():
360
+ return {"status": "online", "message": "Gemini API FastAPI Server is running"}
361
 
362
 
363
  if __name__ == "__main__":
364
+ import uvicorn
365
 
366
+ uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="info")
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "gemi2api-server"
3
- version = "0.1.0"
4
  description = "Add your description here"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
@@ -12,4 +12,18 @@ dependencies = [
12
  ]
13
  [[tool.uv.index]]
14
  url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
15
- default = true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  [project]
2
  name = "gemi2api-server"
3
+ version = "0.1.1"
4
  description = "Add your description here"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
 
12
  ]
13
  [[tool.uv.index]]
14
  url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
15
+ default = true
16
+
17
+ [dependency-groups]
18
+ dev = [
19
+ "ruff>=0.11.7",
20
+ ]
21
+
22
+ [tool.ruff]
23
+ line-length = 150 # 设置最大行长度
24
+ select = ["E", "F", "W", "I"] # 启用的规则(E: pycodestyle, F: pyflakes, W: pycodestyle warnings, I: isort)
25
+ ignore = ["E501"] # 忽略特定规则(如行长度警告)
26
+
27
+ [tool.ruff.format]
28
+ quote-style = "double" # 使用双引号
29
+ indent-style = "tab" # 使用空格缩进