| |
|
|
| import asyncio |
| from email import message |
| import requests |
| import json |
| import sys |
| import os |
| import logging |
| from typing import Dict, Any, Optional, List |
| from dotenv import load_dotenv |
| import httpx |
| from pathlib import Path |
|
|
| |
| |
|
|
|
|
| logger = logging.getLogger(__name__) |
|
|
| class AIAPIClient: |
| def __init__(self, api_key: str, base_url: str, api_type: str = "openai", concurrency_limit: int = 5): |
| self.api_key = api_key |
| self.base_url = base_url |
| self.api_type = api_type |
| self.semaphore = asyncio.Semaphore(concurrency_limit) |
| |
| def get_headers(self) -> Dict[str, str]: |
| return { |
| "Content-Type": "application/json", |
| "Authorization": f"Bearer {self.api_key}" |
| } |
| |
| def build_request_body(self, messages: List[Dict], model: str, **kwargs) -> Dict[str, Any]: |
| """ |
| [修改] 适配 OpenAI 格式的 messages 列表输入 |
| """ |
| return { |
| "model": model, |
| "messages": messages, |
| "temperature": kwargs.get("temperature", 0.7), |
| "max_tokens": kwargs.get("max_tokens", 1000) |
| } |
|
|
| def _print_error_details(self, response): |
| |
| print(f"❌ HTTP 状态码: {response.status_code}") |
| try: |
| error_json = response.json() |
| print(f"❌ API 错误信息 (JSON):") |
| print(json.dumps(error_json, indent=2, ensure_ascii=False)) |
| except json.JSONDecodeError: |
| text = response.text |
| print(f"❌ 错误详情 (Text/HTML): {text[:500]}...") |
|
|
| def call_chat(self, messages: List[Dict[str, str]], model: str, **kwargs) -> str: |
| """ |
| [新增] 专门用于 generator.py 调用的同步接口 |
| 输入: OpenAI 格式的 messages 列表 |
| 输出: 纯文本回复 |
| """ |
| headers = self.get_headers() |
| |
| body = { |
| "model": model, |
| "messages": messages, |
| "temperature": kwargs.get("temperature", 0.7), |
| "max_tokens": kwargs.get("max_tokens", 65536) |
| } |
| |
| |
| |
| |
| endpoint = self.base_url |
| |
| try: |
| response = requests.post( |
| endpoint, |
| headers=headers, |
| json=body, |
| timeout=600 |
| ) |
| response.raise_for_status() |
| resp_json = response.json() |
| return resp_json["choices"][0]["message"]["content"] |
| |
| except requests.exceptions.RequestException as e: |
| print(f"❌ 请求异常: {e}") |
| if hasattr(e, 'response') and e.response is not None: |
| self._print_error_details(e.response) |
| return "" |