#!/usr/bin/env python3

# Minimal weather agent: an LLM that can call a tool.

import json
import requests
from agent_tools import ALL_TOOLS, weather_tool   # ALL_TOOLS: {"name": function}

API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = '-- to be added --'
MODEL   = "openai/gpt-oss-120b"

def ask_llm(messages, tools=None):
    """Send the chat history (and optionally tool definitions) 
       to the LLM, return the LLM's reply message."""
    payload = {"model": MODEL, "messages": messages}
    if tools:
        payload["tools"] = tools
    headers = {"Authorization": f"Bearer {API_KEY}"}
    resp = requests.post(API_URL, headers=headers, json=payload)
    resp.raise_for_status()             # stop with an error if the request failed
    return resp.json()["choices"][0]["message"]


# ------------------------
# 1. Starting conversation: system prompt and user question
# ------------------------
messages = [
    {"role": "system", "content": "Use the provided tools to answer weather queries. "},
    {"role": "user",   "content": "Is it raining in Berlin?"},
]

# ------------------------
# 2. First call: the LLM sees question and tool description
# ------------------------
reply = ask_llm(messages, tools=[weather_tool])
messages.append(reply)

# 3. If the LLM asked for tool calls, run them and add the results to the history
for call in reply.get("tool_calls") or []:
    name = call["function"]["name"]
    args = json.loads(call["function"]["arguments"])   # arguments arrive as a JSON string

    result = ALL_TOOLS[name](**args)                   # the actual tool execution

    messages.append({"role": "tool",
                     "tool_call_id": call["id"],
                     "content": result})

# ------------------------
# 4. Second call: the LLM sees the tool results and writes the final answer
#    :: if no tool was called, the LLM answers directly in step 2
# ------------------------
if reply.get("tool_calls"):
    reply = ask_llm(messages)

print("User:\n", messages[1]["content"])
print("LLM :\n", reply["content"])

# ------------------------
# 5. Dump chat history
# ------------------------
with open("chat_history.json", "w", encoding="utf-8") as f:
    json.dump(messages, f, indent=2, ensure_ascii=False)
