""" 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)