Spaces:
Runtime error
Runtime error
Download utils/api_client.py from Macbath/indicator-modeling: direct link, hf CLI and curl.
- Browser
- Download file 5.14 kB
-
https://huggingface.co/spaces/Macbath/indicator-modeling/resolve/main/utils/api_client.py
- Command line
-
hf download hf://spaces/Macbath/indicator-modeling/utils/api_client.py
-
curl -L -o api_client.py https://huggingface.co/spaces/Macbath/indicator-modeling/resolve/main/utils/api_client.py
5.14 kB
| """ | |
| API客户端模块 - DeepSeek API接口封装 (v3.0) | |
| 本模块提供与DeepSeek API交互的客户端封装。 | |
| 始终调用真实API,需要配置有效的API Key。 | |
| 主要功能: | |
| - 根据用户输入生成指标建模方案的API调用 | |
| - 提供统一的错误处理和日志记录 | |
| 作者: 数据指标建模助手开发团队 | |
| 版本: 3.0 | |
| """ | |
| import json | |
| import logging | |
| import requests | |
| from typing import Optional | |
| # 配置日志记录 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class DeepSeekClient: | |
| """ | |
| DeepSeek API客户端类 | |
| 封装了与DeepSeek API的交互逻辑,始终调用真实API。 | |
| 需要有效API Key才能正常工作。 | |
| 属性: | |
| api_key (str): DeepSeek API密钥 | |
| api_url (str): DeepSeek API的端点URL | |
| logger (Logger): 日志记录器,用于记录API调用状态 | |
| """ | |
| def __init__(self, api_key: str = ""): | |
| """ | |
| 初始化DeepSeek API客户端 | |
| 参数: | |
| api_key (str): DeepSeek API密钥 | |
| 返回: | |
| None | |
| 示例: | |
| >>> client = DeepSeekClient(api_key="sk-xxx") | |
| """ | |
| self.api_key = api_key | |
| self.api_url = "https://api.deepseek.com/v1/chat/completions" | |
| logger.info("DeepSeekClient 初始化完成") | |
| def call(self, prompt: str, system_message: str = "") -> str: | |
| """ | |
| 调用DeepSeek API | |
| 参数: | |
| prompt (str): 用户输入的提示词/查询内容 | |
| system_message (str): 可选的系统消息,用于提供上下文信息 | |
| 返回: | |
| str: API响应文本(JSON格式) | |
| 示例: | |
| >>> client.call("我需要统计每日订单金额") | |
| '{"metric_name": "日订单金额", ...}' | |
| """ | |
| return self._api_call(prompt, system_message) | |
| def _api_call(self, prompt: str, system_message: str = "") -> str: | |
| """ | |
| 调用真实的DeepSeek API | |
| 内部方法:构造HTTP请求调用DeepSeek API,处理认证、超时和错误。 | |
| 需要有效API Key,否则抛出ValueError异常。 | |
| 参数: | |
| prompt (str): 用户输入的提示词 | |
| system_message (str): 系统消息,用于设定对话上下文 | |
| 返回: | |
| str: API返回的响应内容(message.content) | |
| 异常: | |
| ValueError: 当API Key未配置时抛出 | |
| Exception: 当API调用失败、超时或响应格式错误时抛出 | |
| 处理逻辑: | |
| 1. 检查API Key是否配置 | |
| 2. 构造请求头和请求体(包含model、messages、temperature等参数) | |
| 3. 发送POST请求到DeepSeek API | |
| 4. 解析响应JSON,提取content字段 | |
| 5. 处理各类异常(超时、请求错误、响应格式错误) | |
| """ | |
| if not self.api_key: | |
| raise ValueError("DeepSeek API Key 未配置。请在设置中输入 API Key。") | |
| # 准备请求头 | |
| headers = { | |
| "Authorization": f"Bearer {self.api_key}", | |
| "Content-Type": "application/json" | |
| } | |
| # 准备请求数据(消息列表) | |
| messages = [] | |
| if system_message: | |
| messages.append({"role": "system", "content": system_message}) | |
| messages.append({"role": "user", "content": prompt}) | |
| # 构造完整的请求体 | |
| data = { | |
| "model": "deepseek-chat", | |
| "messages": messages, | |
| "temperature": 0.7, # 控制生成文本的随机性 | |
| "max_tokens": 2048 # 最大生成token数(通过prompt控制输出长度) | |
| } | |
| try: | |
| # 发送API请求(超时时间60秒) | |
| # 显式禁用代理,避免系统代理设置干扰 | |
| logger.info("正在调用 DeepSeek API...") | |
| response = requests.post( | |
| self.api_url, | |
| headers=headers, | |
| json=data, | |
| timeout=60, | |
| proxies={"http": None, "https": None} # 禁用代理 | |
| ) | |
| # 检查HTTP状态码,如果失败则抛出HTTPError | |
| response.raise_for_status() | |
| # 解析响应JSON | |
| result = response.json() | |
| # 提取AI生成的内容 | |
| content = result["choices"][0]["message"]["content"] | |
| logger.info("API 调用成功") | |
| return content | |
| except requests.exceptions.Timeout: | |
| # 处理超时异常 | |
| raise Exception("API 调用超时,请稍后重试") | |
| except requests.exceptions.RequestException as e: | |
| # 处理其他请求异常(网络错误、HTTP错误等) | |
| raise Exception(f"API 调用失败: {str(e)}") | |
| except KeyError as e: | |
| # 处理响应格式错误(缺少期望的字段) | |
| raise Exception(f"API 响应格式错误: {str(e)}") | |