Spaces:
Build error
Build error
Download backend/llm_interface.py from Lawrencelv/AIAnalystAgent: direct link, hf CLI and curl.
- Browser
- Download file 1.76 kB
-
https://huggingface.co/spaces/Lawrencelv/AIAnalystAgent/resolve/main/backend/llm_interface.py
- Command line
-
hf download hf://spaces/Lawrencelv/AIAnalystAgent/backend/llm_interface.py
-
curl -L -o llm_interface.py https://huggingface.co/spaces/Lawrencelv/AIAnalystAgent/resolve/main/backend/llm_interface.py
1.76 kB
| import os | |
| import openai | |
| from openai import OpenAI | |
| # 调用通用接口函数 | |
| def call_llm(model_type, messages, api_key): | |
| """ | |
| 调用指定大模型(GPT-4o 或 DeepSeek-R1) | |
| Args: | |
| model_type (str): "GPT-4o" or "DeepSeek-R1" | |
| messages (list): [{"role": "user", "content": "..."}] | |
| api_key (str): 用户输入的 API Key(从 Gradio session 获取) | |
| Returns: | |
| dict: { | |
| "content": 最终回答内容, | |
| "reasoning": 推理过程(如适用) | |
| } | |
| """ | |
| try: | |
| if model_type == "GPT-4o": | |
| client = OpenAI(api_key=api_key) | |
| response = client.chat.completions.create( | |
| model="gpt-4o", | |
| messages=messages | |
| ) | |
| return { | |
| "content": response.choices[0].message.content, | |
| "reasoning": None | |
| } | |
| elif model_type == "DeepSeek-R1": | |
| client = OpenAI( | |
| api_key=api_key, | |
| base_url="https://dashscope.aliyuncs.com/compatible-mode/v1" | |
| ) | |
| response = client.chat.completions.create( | |
| model="deepseek-chat", # 或 deepseek-r1 | |
| messages=messages | |
| ) | |
| return { | |
| "content": response.choices[0].message.content, | |
| "reasoning": response.choices[0].message.reasoning_content | |
| } | |
| else: | |
| return { | |
| "content": f"❌ 模型类型不支持: {model_type}", | |
| "reasoning": None | |
| } | |
| except Exception as e: | |
| return { | |
| "content": f"❌ 模型调用失败:{str(e)}", | |
| "reasoning": None | |
| } | |
| # GPT-4o / DeepSeek-R1 接口封装 | |