# 第二步：Agent 循环。调模型 → 有工具调用就执行、把结果放回对话 → 再调模型……直到模型不再调工具。
import json, os
from openai import OpenAI

client = OpenAI(base_url=os.environ.get("AGENT_BASE_URL", "http://localhost:11434/v1"),
                api_key=os.environ.get("AGENT_API_KEY", "ollama"))
MODEL = os.environ.get("AGENT_MODEL", "qwen3:8b")

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

FUNCTIONS = {"add": add, "multiply": multiply}
tools = [
    {"type": "function", "function": {"name": name, "description": desc, "parameters": {
        "type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}, "required": ["a", "b"]}}}
    for name, desc in [("add", "计算两个数的和"), ("multiply", "计算两个数的积")]
]

def run(question, max_steps=8):
    messages = [{"role": "user", "content": question}]
    for step in range(1, max_steps + 1):
        resp = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
        msg = resp.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))      # 模型这一轮说的话（包括它要调的工具）也要放回对话
        if not msg.tool_calls:                                   # 不再调工具：这就是最终回答
            return msg.content
        for call in msg.tool_calls:
            try:
                args = json.loads(call.function.arguments)
                result = FUNCTIONS[call.function.name](**args)
            except Exception as e:                               # 出错也要告诉模型，让它自己改
                result = f"出错了：{e}"
            print(f"[第 {step} 步] {call.function.name}({args}) = {result}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
    return "超过最大步数，停下。"

if __name__ == "__main__":
    print(run("一箱苹果 24 个，我买了 17 箱，又多拿了 9 个。一共多少个？请用工具计算。"))
