Created
May 20, 2026 19:58
-
-
Save pamelafox/ce3416537b0b548560dcc893831cbe71 to your computer and use it in GitHub Desktop.
MAF with monty tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| import logging | |
| import os | |
| import random | |
| import sys | |
| from datetime import datetime | |
| from typing import Annotated | |
| import pydantic_monty | |
| from agent_framework import Agent, tool | |
| from agent_framework.openai import OpenAIChatClient | |
| from azure.identity.aio import AzureDeveloperCliCredential, get_bearer_token_provider | |
| from dotenv import load_dotenv | |
| from pydantic import Field | |
| from rich import print | |
| from rich.logging import RichHandler | |
| # Setup logging | |
| handler = RichHandler(show_path=False, rich_tracebacks=True, show_level=False) | |
| logging.basicConfig(level=logging.WARNING, handlers=[handler], force=True, format="%(message)s") | |
| logger = logging.getLogger(__name__) | |
| logger.setLevel(logging.INFO) | |
| # Configure OpenAI client based on environment | |
| load_dotenv(override=True) | |
| API_HOST = os.getenv("API_HOST", "azure") | |
| async_credential = None | |
| if API_HOST == "azure": | |
| async_credential = AzureDeveloperCliCredential(tenant_id=os.environ.get("AZURE_TENANT_ID")) | |
| token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default") | |
| client = OpenAIChatClient( | |
| base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/", | |
| api_key=token_provider, | |
| model=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"], | |
| ) | |
| elif API_HOST == "ollama": | |
| client = OpenAIChatClient( | |
| base_url="http://localhost:11434/v1/", | |
| model="gemma4:e4b" | |
| ) | |
| else: | |
| client = OpenAIChatClient( | |
| api_key=os.environ["OPENAI_API_KEY"], model=os.environ.get("OPENAI_MODEL", "gpt-5.4") | |
| ) | |
| @tool | |
| def get_weather( | |
| city: Annotated[str, Field(description="The city to get the weather for.")], | |
| ) -> dict: | |
| """Returns weather data for a given city, a dictionary with temperature and description.""" | |
| logger.info(f"Getting weather for {city}") | |
| if random.random() < 0.05: | |
| return { | |
| "temperature": 72, | |
| "description": "Sunny", | |
| } | |
| else: | |
| return { | |
| "temperature": 60, | |
| "description": "Rainy", | |
| } | |
| @tool | |
| def get_activities( | |
| city: Annotated[str, Field(description="The city to get activities for.")], | |
| date: Annotated[str, Field(description="The date to get activities for in format YYYY-MM-DD.")], | |
| ) -> list[dict]: | |
| """Returns a list of activities for a given city and date.""" | |
| logger.info(f"Getting activities for {city} on {date}") | |
| return [ | |
| {"name": "Hiking", "location": city}, | |
| {"name": "Beach", "location": city}, | |
| {"name": "Museum", "location": city}, | |
| ] | |
| @tool | |
| def fast_code_execution( | |
| code: Annotated[str, Field(description="The Python code snippet to execute.")], | |
| ) -> object: | |
| """Executes Python code safely using Monty.""" | |
| logger.info(f"Executing Python code: {code}") | |
| try: | |
| monty = pydantic_monty.Monty(code) | |
| result = monty.run() | |
| logger.info(f"Code execution result: {result}") | |
| return result | |
| except Exception as exc: | |
| raise RuntimeError(f"Code execution failed: {exc}") from exc | |
| agent = Agent( | |
| client=client, | |
| name="weekend-planner", | |
| instructions=( | |
| "You help users plan their weekends and choose the best activities for the given weather. " | |
| "Use the fast_code_execution tool if you need to do some date or math manipulation." | |
| "If an activity would be unpleasant in weather, don't suggest it. Include date of the weekend in response." | |
| ), | |
| tools=[get_weather, get_activities, fast_code_execution], | |
| ) | |
| async def main(): | |
| response = await agent.run("what can I do three weekends from now in SF?") | |
| print(response.text) | |
| if async_credential: | |
| await async_credential.close() | |
| if __name__ == "__main__": | |
| if "--devui" in sys.argv: | |
| from agent_framework.devui import serve | |
| serve(entities=[agent], auto_open=True) | |
| else: | |
| asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment