Part 1: AutoGen Unleashed: Crafting Intelligent Group Chats from Scratch

autogen gpt openai python Feb 17, 2024
 


Introduction

AutoGen simplifies the creation and management of autonomous agents for various tasks. This article demonstrates setting up a multi-agent system to fetch real-time stock prices, showcasing AutoGen's flexibility and power.

The image shows AutoGen's features: individual conversable agents and their ability to engage in multi-agent chats, either jointly or hierarchically, allowing for complex conversations and agent customization. 

 

Setting Up the Environment

A virtual environment isolates project dependencies, ensuring a clean workspace. We'll use Python's venv to create one and then install AutoGen along with other necessary packages.

python -m venv venv
source venv/bin/activate
pip install pyautogen

 

Initial Configuration and File Setup

Now, onto the code. Create a file named app.py. This file will serve as the heart of our AutoGen setup. We begin by importing the necessary libraries from AutoGen, which will facilitate the creation of our chat agents and manage our configurations.

from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, config_list_from_json

 

Adding Search Functionality

A crucial feature of our setup is the ability to perform web searches. This is achieved through a custom search function, declared and implemented to fetch data as needed. Our setup includes web searches via a custom function using serper.dev, offering quick data retrieval and streamlined integration. Let's create a new file search.py:

# search.py

from datetime import datetime, timedelta
import json
import requests
import os

search_declaration = {
"name": "Search",
"description": "Search at Google and returns Title, Link, and Snippet",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
},
}

def search(query):
# Calculate the date 6 months ago from today
six_months_ago = datetime.now() - timedelta(days=36*30) # approximating 3 years
date_str = six_months_ago.strftime('%Y-%m-%d')

# Append the date filter to the query
query = f"{query} after:{date_str}"

url = "https://google.serper.dev/search"

# Get the API key from an environment variable
api_key = os.environ.get('GOOGLE_SERPER_API_KEY')

if not api_key:
raise ValueError(
"Environment variable 'GOOGLE_SERPER_API_KEY' not set!"
)

payload = json.dumps({
"q": query
})

headers = {
'X-API-KEY': api_key,
'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

return response.json()


Integrating this function into our Assistant Agent allows it to utilize external data sources, enhancing its utility. For this we first have to import the new function into our app.py:

from search import search, search_declaration

 

Implementing the Assistant Agent

Our first agent, the Assistant Agent, acts as the primary responder within our chat setup.
Here's how to initialize it:

assistant = AssistantAgent('assistant', llm_config={"functions": [search_declaration], "config_list": config_list_from_json("OAI_CONFIG_LIST")})


This snippet assigns a name to our agent and configures it with a language model, ready to handle tasks and queries.

The file OAI_CONFIG_LIST will define the models and API keys used by our AutoGen setup:

[{
"model": "gpt-4",
"api_key": "YOUR OPENAI API KEY"
}]

 

Setting Up the User Proxy Agent

The User Proxy Agent stands between the user and the Assistant, mediating interactions. It's configured to execute code and facilitate user-agent dialogues. 

user_proxy = UserProxyAgent('user_proxy', function_map={"Search": search}) 


This configuration allows the User Proxy Agent to access custom functions, such as our search functionality.


Implementing the Cynical Agent

For an added twist, we introduce a Cynical Agent—a character that injects humor and skepticism into our chat. This agent is set up similarly to the Assistant, with a distinct role defined by its system message.

llm_config = {"config_list": config_list_from_json("OAI_CONFIG_LIST")}
cynic = AssistantAgent(
'cynic', system_message="You are a cynic and you comment everything", llm_config=llm_config) 


Initiating Group Chat

To enable our agents to interact, we initiate a group chat, specifying our Assistant and User Proxy Agents as participants. This setup paves the way for dynamic conversations and task handling.

groupchat = GroupChat(agents=[assistant, cynic, user_proxy], messages=[])


Finalizing Group Chat and Testing

With all agents configured, we finalize our group chat setup. This involves linking our agents through a Group Chat Manager and initiating conversations to test the functionality.

groupchat_manager = GroupChatManager(groupchat, llm_config=llm_config) 

user_proxy.initiate_chat(groupchat_manager, message="Find the latest stock price of Apple")


We can then run the script.This final step demonstrates the collaborative capabilities of our AutoGen setup, showcasing real-time interactions and problem-solving.

export AUTOGEN_USE_DOCKER=false
python app.py

 


Conclusion

Through this guide, we've explored the steps to create a sophisticated AutoGen environment, capable of handling complex interactions and tasks. The combination of multiple agents, including a custom search function and the unique Cynical Agent, demonstrates the flexibility and power of AutoGen for AI-driven chat applications.

For further exploration and to access the complete code, visit our GitHub repository. Whether you're a seasoned developer or new to the AI space, Happy coding, and remember—the possibilities are as limitless as your imagination.

 

 

Stay Ahead in AI with Free Weekly Video Updates!

AI is evolving faster than ever ā€“ donā€™t get left behind. By joining our newsletter, youā€™ll get:

  • Weekly video tutorials previews on new AI tools and frameworks
  • Updates on major AI breakthroughs and their impact
  • Real-world examples of AI in action, delivered every week, completely free.


Don't worry, your information will not be shared.

We hate SPAM. We will never sell your information, for any reason.