Spaces:
Sleeping

File size: 4,596 Bytes
2131907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
agent.py — a bounded, tool-using agent built on Gemini function calling.
The model proposes tool calls; THIS code executes them and feeds results back,
looping until a final answer or a hard step cap. Includes simple guardrails.
"""
import os
from google import genai
from google.genai import types
from dotenv import find_dotenv, load_dotenv
from tools import TOOLS

load_dotenv(find_dotenv())

MODEL_NAME = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash-lite")
MAX_STEPS = 6  # guardrail: never loop forever

SYSTEM = (
    "You are a helpful agent that can use tools. "
    "Use tools when they help; otherwise answer directly. "
    "For get_weather you must supply numeric latitude and longitude. "
    "Never claim to have done something a tool did not return."
)

# Tool schemas the model sees (name, doc, typed params).
TOOL_DECLARATIONS = [
    {"name": "calculator",
     "description": "Evaluate a maths expression, e.g. '2*(3+4)' or 'sqrt(144)'.",
     "parameters": {"type": "object",
                    "properties": {"expression": {"type": "string"}},
                    "required": ["expression"]}},
    {"name": "get_weather",
     "description": "Current weather for a latitude/longitude.",
     "parameters": {"type": "object",
                    "properties": {"latitude": {"type": "number"},
                                   "longitude": {"type": "number"}},
                    "required": ["latitude", "longitude"]}},
    {"name": "save_note",
     "description": "Save a short note to persistent storage.",
     "parameters": {"type": "object",
                    "properties": {"text": {"type": "string"}},
                    "required": ["text"]}},
    {"name": "list_notes",
     "description": "List all saved notes.",
     "parameters": {"type": "object", "properties": {}}},
]


def _client():
    api_key = os.environ.get("GEMINI_API_KEY")
    if not api_key or api_key == "your_gemini_api_key_here":
        raise RuntimeError("Set GEMINI_API_KEY in the repository .env file first.")
    return genai.Client(api_key=api_key)


def _tools():
    declarations = [
        types.FunctionDeclaration(
            name=decl["name"],
            description=decl["description"],
            parameters_json_schema=decl["parameters"],
        )
        for decl in TOOL_DECLARATIONS
    ]
    return [types.Tool(function_declarations=declarations)]


def run(goal, trace=None):
    """
    Execute the agent loop for a user goal.
    Returns (final_answer, trace) where trace is a list of step strings.
    """
    trace = trace if trace is not None else []
    client = _client()
    convo = client.chats.create(
        model=MODEL_NAME,
        config=types.GenerateContentConfig(
            system_instruction=SYSTEM,
            tools=_tools(),
            temperature=0.2,
        ),
    )
    message = goal

    for step in range(MAX_STEPS):
        resp = convo.send_message(message)
        candidate = resp.candidates[0] if resp.candidates else None
        content = candidate.content if candidate else None
        parts = content.parts if content and content.parts else []
        calls = [p.function_call for p in parts if getattr(p, "function_call", None)]

        if not calls:  # model produced a final textual answer
            if resp.text:
                return resp.text, trace
            if trace:
                return "Completed the tool call(s). See the trace for results.", trace
            return "No answer returned by the model. Try a simpler goal.", trace

        # Execute every requested tool call, then feed results back.
        responses = []
        for fc in calls:
            name = fc.name
            args = dict(fc.args) if fc.args else {}
            fn = TOOLS.get(name)
            if fn is None:  # guardrail: unknown tool
                result = f"Error: unknown tool '{name}'."
            else:
                try:
                    result = fn(**args)
                except TypeError as e:
                    result = f"Error: bad arguments for {name}: {e}"
            trace.append(f"step {step+1}: {name}({args}) -> {result}")
            responses.append(types.Part.from_function_response(
                name=name,
                response={"result": result},
            ))
        message = responses  # send all tool results back in one turn

    return "Stopped: reached the maximum number of steps.", trace


if __name__ == "__main__":
    ans, tr = run("What is sqrt(2025), and save the result as a note.")
    print("TRACE:")
    print("\n".join(tr))
    print("\nANSWER:", ans)