Spaces:
Sleeping
Sleeping
import os | |
import re | |
import requests | |
import pandas as pd | |
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, HfApiModel | |
# --- BasicAgent 定义(和你现有代码一致) --- | |
class BasicAgent: | |
def __init__(self): | |
api_key = os.getenv("DEEPSEEK_API_KEY") | |
if not api_key: | |
raise ValueError("DEEPSEEK_API_KEY not found.") | |
model = OpenAIServerModel( | |
model_id="deepseek-chat", | |
api_key=api_key, | |
api_base="https://api.deepseek.com/v1" | |
) | |
search_tool = DuckDuckGoSearchTool() | |
self.agent = CodeAgent( | |
model=model, | |
tools=[search_tool], | |
additional_authorized_imports=["pandas"] | |
) | |
SYSTEM_PROMPT = """ | |
You MUST follow these response rules: | |
1. Strictly use FINAL ANSWER: template | |
2. Only use plain text format | |
3. Never use markdown or special formatting | |
4. Numbers must be digits only | |
5. Lists must be comma-separated without quotes | |
6. Always use English characters | |
""" | |
self.agent.prompt_templates["system_prompt"] += SYSTEM_PROMPT | |
def __call__(self, question: str) -> str: | |
if not isinstance(question, str): | |
question = str(question) | |
raw = str(self.agent.run(question)) | |
raw = raw.replace("\n", " ").replace("\r", " ").strip() | |
m = re.search(r"FINAL ANSWER:\s*(.*?)(?=\n|$)", raw, re.IGNORECASE) | |
return m.group(1).strip() if m else raw | |
# --- Monkey-patch _prepare_completion_kwargs 来拦截 messages --- | |
_original_prep = OpenAIServerModel._prepare_completion_kwargs | |
def _inspect_prep(self, messages, **kwargs): | |
bad = [] | |
for idx, msg in enumerate(messages): | |
content = msg.get("content") | |
if not isinstance(content, str): | |
bad.append((idx, type(content).__name__, content)) | |
if bad: | |
print("🔍 在 _prepare_completion_kwargs 中发现非字符串的 message.content:") | |
for i, t, v in bad: | |
print(f" - index {i}: 类型={t}, 值={v!r}") | |
# 中断,让你看到错误 | |
raise ValueError("Found non-str message.content, aborting.") | |
# 全部合法才继续原逻辑 | |
return _original_prep(self, messages, **kwargs) | |
# 应用 patch | |
OpenAIServerModel._prepare_completion_kwargs = _inspect_prep | |
# --- 主流程:直接运行你要问的问题 --- | |
if __name__ == "__main__": | |
question = ( | |
"Who nominated the only Featured Article on English Wikipedia about a " | |
"dinosaur that was promoted in November 2016?" | |
) | |
try: | |
agent = BasicAgent() | |
print("提问:", question) | |
ans = agent(question) | |
print("回答:", ans) | |
except Exception as e: | |
print("出错:", e) | |