Installing
pip install "ag2[openai]"
Example
from datetime import datetime
from typing import Annotated
from autogen import ConversableAgent, register_function, LLMConfig
# Put your key in the OPENAI_API_KEY environment variable
llm_config = LLMConfig(api_type="openai", model="gpt-4o-mini")
# 1. Our tool, returns the day of the week for a given date
def get_weekday(date_string: Annotated[str, "Format: YYYY-MM-DD"]) -> str:
date = datetime.strptime(date_string, "%Y-%m-%d")
return date.strftime("%A")
# 2. Agent for determining whether to run the tool
with llm_config:
date_agent = ConversableAgent(
name="date_agent",
system_message="You get the day of the week for a given date.",
)
# 3. And an agent for executing the tool
executor_agent = ConversableAgent(
name="executor_agent",
human_input_mode="NEVER",
)
# 4. Registers the tool with the agents, the description will be used by the LLM
register_function(
get_weekday,
caller=date_agent,
executor=executor_agent,
description="Get the day of the week for a given date",
)
# 5. Two-way chat ensures the executor agent follows the suggesting agent
chat_result = executor_agent.initiate_chat(
recipient=date_agent,
message="I was born on the 25th of March 1995, what day was it?",
max_turns=2,
)
print(chat_result.chat_history[-1]["content"])