How to define functions for AutoGen
Quick answer
To define functions for
AutoGen in CreAI, create Python functions with clear signatures and register them with the AutoGen agent. These functions can then be dynamically invoked by the AI during conversations to perform tasks or retrieve data.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install crewai
Setup
Install the crewai package and set your OpenAI API key as an environment variable.
- Install with
pip install crewai - Set environment variable in your shell:
export OPENAI_API_KEY='your_api_key'
pip install crewai Step by step
Define Python functions with explicit parameters and register them with the AutoGen agent. The agent can then call these functions dynamically based on user input.
import os
from crewai import AutoGen
# Define a function that the AI can call
def get_weather(city: str) -> str:
# Simulate fetching weather data
return f"The weather in {city} is sunny with 75°F."
# Initialize AutoGen agent with your API key
agent = AutoGen(api_key=os.environ["OPENAI_API_KEY"])
# Register the function with the agent
agent.register_function(get_weather)
# Example usage: AI calls the function based on user input
response = agent.chat("What's the weather in New York?")
print(response) output
The weather in New York is sunny with 75°F.
Common variations
You can define multiple functions with different signatures and register them all. AutoGen supports async functions and can use different models by specifying them during agent initialization.
import asyncio
async def get_news(topic: str) -> str:
# Simulate async news fetching
await asyncio.sleep(1)
return f"Latest news on {topic}: AI adoption is growing rapidly."
# Register async function
agent.register_function(get_news)
# Use a different model
agent_with_model = AutoGen(api_key=os.environ["OPENAI_API_KEY"], model="gpt-4o") Troubleshooting
- If the agent does not call your function, ensure it is registered properly with
agent.register_function(). - Check that function parameters have type annotations for better AI understanding.
- For async functions, ensure you run the event loop properly.
Key Takeaways
- Define Python functions with clear type annotations for AutoGen to understand parameters.
- Register all callable functions with the AutoGen agent using
register_function(). - AutoGen can dynamically invoke registered functions during chat interactions.
- Support for async functions and model selection enhances flexibility.
- Proper registration and typing prevent common integration issues.