File size: 2,799 Bytes
bba5e7c
bbf22d8
bba5e7c
 
b848a2e
e60c643
b848a2e
bba5e7c
 
 
 
b848a2e
 
 
 
 
 
bba5e7c
 
 
 
 
 
 
 
 
 
 
b848a2e
bba5e7c
 
e60c643
bba5e7c
e60c643
bba5e7c
 
 
b848a2e
 
 
 
e60c643
b848a2e
 
bba5e7c
b848a2e
bba5e7c
 
 
 
 
 
b848a2e
bba5e7c
 
b848a2e
 
 
 
bbf22d8
b848a2e
 
bbf22d8
b848a2e
e60c643
bba5e7c
 
 
 
 
 
b848a2e
 
 
bba5e7c
b848a2e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)