{"id":23552462,"url":"https://github.com/xlisp/learn-autogen","last_synced_at":"2025-12-12T01:23:25.856Z","repository":{"id":62435169,"uuid":"238596500","full_name":"xlisp/learn-autogen","owner":"xlisp","description":"Learn autogen step by step, multi agent design guide","archived":false,"fork":false,"pushed_at":"2024-11-18T08:05:42.000Z","size":2000,"stargazers_count":27,"open_issues_count":0,"forks_count":6,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-30T10:11:27.334Z","etag":null,"topics":["autogen","deep-learning","gpt","multi-agent","python","reinforcement-learning"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xlisp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-02-06T03:05:34.000Z","updated_at":"2024-12-09T19:05:32.000Z","dependencies_parsed_at":"2024-09-06T17:11:18.533Z","dependency_job_id":"cb66c004-80d2-4341-8e4b-b9b0caa861ce","html_url":"https://github.com/xlisp/learn-autogen","commit_stats":null,"previous_names":["xlisp/learn-autogen","chanshunli/wechat-clj"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xlisp%2Flearn-autogen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xlisp%2Flearn-autogen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xlisp%2Flearn-autogen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xlisp%2Flearn-autogen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xlisp","download_url":"https://codeload.github.com/xlisp/learn-autogen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251321909,"owners_count":21570820,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autogen","deep-learning","gpt","multi-agent","python","reinforcement-learning"],"created_at":"2024-12-26T11:11:14.633Z","updated_at":"2025-12-12T01:23:25.804Z","avatar_url":"https://github.com/xlisp.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Learn AutoGen\n\n* Learn autogen step by step, multi agent design guide\n\n\n[![Watch the video](./jiaxiao_pyautogui_app/jiaxiao.JPG)](https://youtu.be/RkgwIOEIoNw)\n\n\n- [Learn AutoGen](#learn-autogen)\n  - [Class Relationship](#class-relationship)\n  - [Basic Definition](#basic-definition)\n  - [Tools Definition](#tools-definition)\n  - [ReAct Definition](#react-definition)\n  - [Chats Group: initiate_chats](#chats-group-initiate_chats)\n  - [More examples](#more-examples)\n  - [Summarize single task](#summarize-single-task)\n  - [Manual call tool and check chat history](#manual-call-tool-and-check-chat-history)\n  - [Use class define a agent](#use-class-define-a-agent)\n  - [Async run agent](#async-run-agent)\n  - [Use other llm](#use-other-llm)\n  - [More examples](#more-examples)\n\n## Class Relationship\n\nlook full graph: [autogen_class_refs.pdf](./autogen_class_refs.pdf)\n\n![](./autogen_class_show.png)\n\n## Basic Definition\n```python\nfrom typing_extensions import Annotated\nimport autogen\nimport os\nimport sys\nimport subprocess\n\nlocal_llm_config = {\n    \"config_list\": [\n        {\n            \"model\": \"gpt-4o\",\n            \"api_key\": os.environ.get(\"OPENAI_API_KEY\"),\n            \"api_type\": \"open_ai\",\n        }\n    ],\n    \"cache_seed\": None,\n}\n\n## system_message is your task description:\nchatbot = autogen.AssistantAgent(\n    name=\"chatbot\",\n    system_message=\"\"\"For (your task description) tasks,\n        only use the functions you have been provided with.\n        If the function has been called previously,\n        return only the word 'TERMINATE'.\"\"\",\n    llm_config=local_llm_config,\n)\n\nuser_proxy = autogen.UserProxyAgent(\n    name=\"user_proxy\",\n    is_termination_msg=lambda x: x.get(\"content\", \"\")\n    and \"TERMINATE\" in x.get(\"content\", \"\"),\n    human_input_mode=\"NEVER\",\n    max_consecutive_auto_reply=1,\n    code_execution_config={\"work_dir\": \"code\", \"use_docker\": False},\n)\n\n## If you need define new tools, you can like this define:\n@user_proxy.register_for_execution()\n@chatbot.register_for_llm(description=\"Calculate distance between two addresses.\")\ndef calculate_distance(\n    start_address: Annotated[str, \"Starting address\"],\n    end_address: Annotated[str, \"Destination address\"],\n) -\u003e str:\n    .... (your function detail) ....\n\ndef main(question):\n    res = user_proxy.initiate_chat(\n        chatbot,\n        message=question,\n        summary_method=\"reflection_with_llm\",\n    )\n    return res\n\nquestion = sys.argv[1]\nmain(question)\n```\n## Tools Definition\n```python\n@user_proxy.register_for_execution()\n@chatbot.register_for_llm(description=\"Calculate distance between two addresses.\")\ndef calculate_distance(\n    start_address: Annotated[str, \"Starting address\"],\n    end_address: Annotated[str, \"Destination address\"],\n) -\u003e str:\n      .... function detail ....\n\n```\n## ReAct Definition\n```python\nfrom autogen import AssistantAgent, UserProxyAgent, ConversableAgent\nimport os\n\nassistant = AssistantAgent(\n    name=\"assistant\",\n    llm_config={\n        \"config_list\": [{\"model\": \"gpt-4o\", \"api_key\": os.environ.get(\"OPENAI_API_KEY\")}]\n    }\n)\n\nuser_proxy = UserProxyAgent(\n    name=\"user_proxy\",\n    human_input_mode=\"NEVER\",\n    max_consecutive_auto_reply=10,\n    code_execution_config={\"work_dir\": \"coding\"}\n)\n\ntask = \"Analyze the following data and create a visualization: [Your data is  current path all log file]\"\n\nuser_proxy.initiate_chat(\n    assistant,\n    message=task\n)\n```\n\n## Chats Group: initiate_chats\n```python\n# Import the autogen package\nimport autogen\n\n# Configure the large language model\nllm_config = {\n    \"config_list\": [{\"model\": \"gpt-4-turbo\", \"api_key\": os.environ['OPENAI_API_KEY']}],\n}\n\n# Define the tasks for running a flower e-commerce business\ninventory_tasks = [\n    \"\"\"Check the current inventory of various flowers and report which ones are low in stock.\"\"\",\n    \"\"\"Based on the past month's sales data, predict which flowers will be in higher demand in the coming month.\"\"\",\n]\n\nmarket_research_tasks = [\"\"\"Analyze market trends to identify the most popular types of flowers and possible reasons for their popularity.\"\"\"]\n\ncontent_creation_tasks = [\"\"\"Using the provided information, write an engaging blog post about the most popular flowers and tips for selecting them.\"\"\"]\n\n# Create Agent roles\ninventory_assistant = autogen.AssistantAgent(\n    name=\"Inventory Management Assistant\",\n    llm_config=llm_config,\n)\nmarket_research_assistant = autogen.AssistantAgent(\n    name=\"Market Research Assistant\",\n    llm_config=llm_config,\n)\ncontent_creator = autogen.AssistantAgent(\n    name=\"Content Creation Assistant\",\n    llm_config=llm_config,\n    system_message=\"\"\"\n        You are a professional writer known for insightful and engaging articles.\n        You can transform complex concepts into compelling narratives.\n        When everything is complete, please reply with 'TERMINATE'.\n        \"\"\",\n)\n\n# Create User Proxy Agents\nuser_proxy_auto = autogen.UserProxyAgent(\n    name=\"User Proxy_Auto\",\n    human_input_mode=\"NEVER\",\n    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n    code_execution_config={\n        \"last_n_messages\": 1,\n        \"work_dir\": \"tasks\",\n        \"use_docker\": False,\n    },\n)\n\nuser_proxy = autogen.UserProxyAgent(\n    name=\"User Proxy\",\n    human_input_mode=\"ALWAYS\",\n    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n    code_execution_config={\n        \"last_n_messages\": 1,\n        \"work_dir\": \"tasks\",\n        \"use_docker\": False,\n    },\n)\n\n# Initiate conversations\nchat_results = autogen.initiate_chats(\n    [\n        {\n            \"sender\": user_proxy_auto,\n            \"recipient\": inventory_assistant,\n            \"message\": inventory_tasks[0],\n            \"clear_history\": True,\n            \"silent\": False,\n            \"summary_method\": \"last_msg\",\n        },\n        {\n            \"sender\": user_proxy_auto,\n            \"recipient\": market_research_assistant,\n            \"message\": market_research_tasks[0],\n            \"max_turns\": 2,\n            \"summary_method\": \"reflection_with_llm\",\n        },\n        {\n            \"sender\": user_proxy,\n            \"recipient\": content_creator,\n            \"message\": content_creation_tasks[0],\n            \"carryover\": \"I would like to include a data table or chart in the blog post.\",\n        },\n    ]\n)\n```\n\n## Summarize single task\n\n```python\nimport os\nimport autogen\n\nconfig_list = [\n    {\n        \"model\": \"gpt-4o\",\n        \"api_key\": os.environ.get(\"OPENAI_API_KEY\"),\n        \"api_type\": \"open_ai\",\n    }\n]\n\n\nllm_config = {\n    \"seed\": 42,\n    \"config_list\": config_list,\n    \"temperature\": 0\n}\n\nassistant = autogen.AssistantAgent(\n    name=\"assistant\",\n    llm_config=llm_config\n)\n\nuser_proxy = autogen.UserProxyAgent(\n    name=\"user_proxy\",\n    human_input_mode=\"TERMINATE\",\n    max_consecutive_auto_reply=10,\n    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n    code_execution_config={\"work_dir\": \"web\"},\n    llm_config=llm_config,\n    system_message=\"\"\"Reply TERMINATE if the task has been solved at full satisfaction\n    Otherwise, reply CONTINUE, or the reason why the task is not solved yet.\"\"\"\n)\n\ntask = \"\"\"\nI Give me a summary of this article: https://apnews.com/article/school-shootings-talk-with-kids-cd21c1445cb6cfd89ed9184f030530ff\n\"\"\"\n\nuser_proxy.initiate_chat(\n    assistant,\n    message=task\n)\n```\n\n## Use class define a agent\n\n```python\nclass CodeSummarizerAgent(AssistantAgent):\n    def __init__(self, name):\n        super().__init__(name=name)\n        self.system_prompt = \"You are a code summarizer. Summarize the given code and test results.\"\n\n    def summarize(self, code, test_results):\n        prompt = f\"Summarize the following code and test results:\\n\\nCode:\\n{code}\\n\\nTest Results:\\n{test_results}\"\n        response = self.chat(prompt)\n        summary = response.content\n        return summary\n\ncode_summarizer = CodeSummarizerAgent(name=\"CodeSummarizer\")\nsummary = code_summarizer.summarize(code, test_results)\n\n```\n\n## Manual call tool and check chat history\n\n```python\ndef main(question):\n    chat_history = []\n    while True:\n        print(f\"Sending message to chatbot: {question}\")\n        response = user_proxy.initiate_chat(\n            chatbot,\n            message=question,\n            clear_history=False\n        )\n\n        print(f\"Received response: {response}\")\n\n        if response.chat_history:\n            last_message = response.chat_history[-1]\n            chat_history.append(last_message)\n            print(f\"Last message: {last_message}\")\n\n            if last_message.get('tool_calls'):\n                print(\"Function call detected, executing...\")\n                tool_call = last_message['tool_calls'][0]\n                function_name = tool_call['function']['name']\n                function_args = tool_call['function']['arguments']\n                print(f\"Function to call: {function_name}\")\n                print(f\"Function arguments: {function_args}\")\n\n                # Execute the function\n                if function_name == 'get_screen_question':\n                    result = get_screen_question()\n                elif function_name == 'select_answer':\n                    import json\n                    args = json.loads(function_args)\n                    result = select_answer(args['answer'])\n                else:\n                    result = \"Unknown function\"\n\n                # Prepare the tool response message\n                tool_response = {\n                    \"tool_call_id\": tool_call['id'],\n                    \"role\": \"tool\",\n                    \"name\": function_name,\n                    \"content\": result\n                }\n\n                # Send the tool response back to the chatbot\n                question = f\"Tool response: {json.dumps(tool_response)}\"\n            else:\n                print(\"No function call detected, terminating...\")\n                break\n        else:\n            print(\"No messages in the response, terminating...\")\n            break\n\n    return chat_history\n```\n\n## Async run agent\n\n```python\nimport asyncio\nfrom autogen_agentchat.agents import AssistantAgent\nfrom autogen_agentchat.task import Console, TextMentionTermination\nfrom autogen_agentchat.teams import RoundRobinGroupChat\nfrom autogen_ext.models import OpenAIChatCompletionClient\n\n# Define a tool\nasync def get_weather(city: str) -\u003e str:\n    return f\"The weather in {city} is 73 degrees and Sunny.\"\n\nasync def main() -\u003e None:\n    # Define an agent\n    weather_agent = AssistantAgent(\n        name=\"weather_agent\",\n        model_client=OpenAIChatCompletionClient(\n            model=\"gpt-4o-2024-08-06\",\n            # api_key=\"YOUR_API_KEY\",\n        ),\n        tools=[get_weather],\n    )\n\n    # Define termination condition\n    termination = TextMentionTermination(\"TERMINATE\")\n\n    # Define a team\n    agent_team = RoundRobinGroupChat([weather_agent], termination_condition=termination)\n\n    # Run the team and stream messages to the console\n    stream = agent_team.run_stream(task=\"What is the weather in New York?\")\n    await Console(stream)\n\nasyncio.run(main())\n```\n  \n## Use other llm\n\n```python\n# OpenRouter API configuration\nOPENROUTER_API_KEY = os.environ['OPENROUTER_API_KEY']\n\nclass OpenRouterLLM:\n    def __init__(self, model=\"openai/gpt-4o-2024-08-06\"):\n        self.model = model\n\n    def create_completion(self, messages):\n        response = requests.post(\n            url=\"https://openrouter.ai/api/v1/chat/completions\",\n            headers={\n                \"Authorization\": f\"Bearer {OPENROUTER_API_KEY}\"\n            },\n            data=json.dumps({\n                \"model\": self.model,\n                \"messages\": messages,\n                \"max_tokens\": 4000,\n                \"temperature\": 0.7,\n            })\n        )\n        return response.json()\n\nllm = OpenRouterLLM()\n\n# ---- \nclass CustomAssistantAgent(autogen.AssistantAgent):\n    def generate_reply(self, sender=None, messages=None):\n        if messages is None:\n            messages = self._oai_messages\n\n        if not messages:\n            return None\n\n        system_message = self.system_message\n\n        last_message = messages[-1]\n        if isinstance(last_message, dict):\n            last_message_content = last_message.get('content', '')\n        else:\n            last_message_content = str(last_message)\n\n        api_messages = create_messages(system_message, last_message_content)\n        response = llm.create_completion(api_messages)\n\n        try:\n            reply = response['choices'][0]['message']['content']\n            if self.name == \"narrative_writer\":\n                novel_progress.add_content(reply)\n            return reply\n        except KeyError:\n            return \"I apologize, but I encountered an error processing your request.\"\n\nstory_planner = CustomAssistantAgent(\n    name=\"story_planner\",\n    system_message=story_planner_config[\"system_message\"]\n)\n\n```\n\n## More examples\n\n* https://github.com/xlisp/novelist-agent\n* https://github.com/xlisp/learn-autogen/tree/master/autogen_examples\n* https://github.com/xlisp/learn-autogen/tree/master/jiaxiao_pyautogui_app\n* https://github.com/xlisp/aippt-agent\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxlisp%2Flearn-autogen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxlisp%2Flearn-autogen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxlisp%2Flearn-autogen/lists"}