### Clone the Example Repository Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/advanced-concepts/realtime-agent/webrtc.mdx Clone the project repository to get started with the real-time agent over WebRTC example. ```bash git clone https://github.com/ag2ai/realtime-agent-over-webrtc.git cd realtime-agent-over-webrtc ``` -------------------------------- ### Clone the Repository Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-01-10-WebSockets/index.mdx Clone the example repository to your local machine to get started. ```bash git clone https://github.com/ag2ai/agentchat-over-websockets.git cd agentchat-over-websockets ``` -------------------------------- ### Install and Run Frontend Dependencies Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-05-07-AG2-Copilot-Integration/index.mdx Commands to install frontend dependencies and start the development server. Ensure you are in the 'ui' directory. ```bash cd ui pnpm i pnpm run dev ``` -------------------------------- ### Install Dependencies and Run React UI Source: https://github.com/ag2ai/ag2/blob/main/website/docs/beta/ag-ui/copilotkit-quickstart.mdx Navigate to the UI directory, install Node.js dependencies, and start the development server for the React frontend. ```bash cd ui-react npm install npm run dev ``` -------------------------------- ### Server Startup Logs Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/advanced-concepts/realtime-agent/websocket.mdx Example log output indicating the server has started successfully. ```bash INFO: Started server process [64425] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:5050 (Press CTRL+C to quit) ``` -------------------------------- ### Basic GPTAssistantAgent Setup Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2023-11-13-OAI-assistants/index.mdx Set up configuration and initialize a GPTAssistantAgent and a UserProxyAgent for basic interaction. This example creates a new assistant. ```python from autogen import config_list_from_json from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent from autogen import UserProxyAgent config_list = config_list_from_json("OAI_CONFIG_LIST") ``` ```python # creates new assistant using Assistant API gpt_assistant = GPTAssistantAgent( name="assistant", llm_config={ "config_list": config_list, "assistant_id": None }) user_proxy = UserProxyAgent(name="user_proxy", code_execution_config={ "work_dir": "coding" }, human_input_mode="NEVER") user_proxy.initiate_chat(gpt_assistant, message="Print hello world") ``` -------------------------------- ### Search and Install Artifacts Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/install.md Search for artifacts like skills, tools, or agents using a keyword and then install the desired one. This example searches for 'web scraping' related artifacts. ```bash ag2 install search "web scraping" ``` -------------------------------- ### Install AutoGen Studio via Pip Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2023-12-01-AutoGenStudio/index.mdx Install AutoGen Studio using pip for quick setup. Recommended for most users. ```bash pip install autogenstudio ``` -------------------------------- ### Initialize Agents for Example 1 Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_microsoft_fabric.ipynb Initialize agents for Example 1, which demonstrates using AssistantAgent and UserProxyAgent to write and execute code. This setup is for openai>=1. ```python import autogen ``` -------------------------------- ### Use SkillSearchToolkit for Skill Discovery and Installation Source: https://github.com/ag2ai/ag2/blob/main/website/docs/beta/tools/common_toolkits.mdx Integrate SkillSearchToolkit into an agent to enable searching, installing, and managing skills from the skills.sh registry. This example demonstrates finding and installing a React best practices skill. ```python import asyncio from autogen.beta import Agent from autogen.beta.config import AnthropicConfig from autogen.beta.tools import SkillSearchToolkit agent = Agent( "coder", "You are a helpful coding assistant. Use skills to extend your capabilities.", config=AnthropicConfig(model="claude-sonnet-4-6"), tools=[SkillSearchToolkit()], ) async def main() -> None: reply = await agent.ask( "Find and install a skill for React best practices, then tell me the top 3 rules." ) print(await reply.content()) asyncio.run(main()) ``` -------------------------------- ### Initialize Agents for Logging Example Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_databricks_dbrx.ipynb Sets up a basic AssistantAgent and UserProxyAgent for demonstrating the logging functionality. Note that code execution is disabled for the UserProxyAgent in this specific setup. ```python assistant = autogen.AssistantAgent(name="assistant", llm_config=llm_config) user_proxy = autogen.UserProxyAgent(name="user", code_execution_config=False) ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/ag2ai/ag2/blob/main/website/README.md Install the necessary Python packages for documentation building from the project root. This command is used both for local setup and within a dev container. ```bash pip install -e ".[docs]" ``` -------------------------------- ### Setup Environment for Anthropic Structured Outputs Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_anthropic_structured_outputs.ipynb Installs dependencies and configures the environment by setting the Anthropic API key. Ensures the API key is present before proceeding. ```python import os from pydantic import BaseModel import autogen # Ensure you have your Anthropic API key set # os.environ["ANTHROPIC_API_KEY"] = "your-api-key-here" # Verify the API key is set assert os.getenv("ANTHROPIC_API_KEY"), "Please set ANTHROPIC_API_KEY environment variable" print("✅ Environment configured") ``` -------------------------------- ### Setup QuickResearchTool Instance Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/reference-tools/quick-research.mdx Instantiate the QuickResearchTool, providing the LLM configuration and Tavily API key. Configure the number of results to crawl per query. ```python research_tool = QuickResearchTool( llm_config=llm_config, tavily_api_key=os.getenv("TAVILY_API_KEY"), num_results_per_query=2, ) ``` -------------------------------- ### Clone Repository Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/advanced-concepts/realtime-agent/websocket.mdx Clone the example repository to get started with the real-time agent over websockets. ```bash git clone https://github.com/ag2ai/realtime-agent-over-websockets.git cd realtime-agent-over-websockets ``` -------------------------------- ### Install Dependencies for Autogen and Whisper Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_video_transcript_translate_with_whisper.ipynb Install Autogen with OpenAI support and the openai-whisper library. Refer to the installation guide for more details. ```bash pip install autogen[openai] openai-whisper ``` -------------------------------- ### Install Ollama and Serve Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_small_llm_rag_planning.ipynb Installs the Ollama Python package and starts the Ollama server. Ensure Ollama is installed and running before proceeding. ```python ! pip install ollama ! ollama serve ``` -------------------------------- ### Install RetrieveChat with MongoDB Support Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_RetrieveChat_mongodb.ipynb Installs the necessary dependencies for RetrieveChat with MongoDB integration and FLAML for AutoML. Refer to the installation guide for more details. ```bash pip install autogen[retrievechat-mongodb] flaml[automl] ``` -------------------------------- ### Install AG2 with OpenAI Support Source: https://github.com/ag2ai/ag2/blob/main/autogen/tools/experimental/apply_patch/README.md Install the AG2 library with OpenAI support to enable the apply_patch tool. Refer to the installation guide for more details. ```bash pip install ag2[openai] ``` -------------------------------- ### Install FastAPI, Uvicorn, and Jinja2 Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_realtime_gemini_websocket.ipynb Installs necessary Python packages for running the FastAPI server and templating. Ensure these are installed before proceeding with server setup. ```bash !pip install "fastapi>=0.115.0,<1" "uvicorn>=0.30.6,<1" "jinja2" ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-01-10-WebSockets/index.mdx Copy the sample environment configuration file and update it with your OpenAI API key. ```bash cp OAI_CONFIG_LIST_sample OAI_CONFIG_LIST ``` -------------------------------- ### Swarm Initialization and Agent Setup Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2024-11-17-Swarm/index.mdx Set up swarm agents, including LLM configuration, context variables, and agent functions. This example defines functions for verifying customer identity, approving refunds, and processing payments, returning `SwarmResult` objects to manage context and agent transitions. ```python from autogen import initiate_swarm_chat, ConversableAgent, SwarmResult, OnCondition, AFTER_WORK, AfterWorkOption from autogen import UserProxyAgent import os # All our swarm agents will use gpt-5-nano from OpenAI llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST") # We configure our starting context dictionary context_variables = { "passport_number": "", "customer_verified": False, "refund_approved": False, "payment_processed": False } # Functions that our swarm agents will be assigned # They can return a SwarmResult, a ConversableAgent, or a string # SwarmResult allows you to update context_variables and/or hand off to another agent def verify_customer_identity(passport_number: str, context_variables: dict) -> str: context_variables["passport_number"] = passport_number context_variables["customer_verified"] = True return SwarmResult(values="Customer identity verified", context_variables=context_variables) def approve_refund_and_transfer(context_variables: dict) -> str: context_variables["refund_approved"] = True return SwarmResult(values="Refund approved", context_variables=context_variables, agent=payment_processor) def process_refund_payment(context_variables: dict) -> str: context_variables["payment_processed"] = True return SwarmResult(values="Payment processed successfully", context_variables=context_variables) ``` -------------------------------- ### Install Required Packages Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/advanced-concepts/code-execution.mdx Install the `matplotlib` and `numpy` libraries before running the Python code execution example. ```bash pip install -qqq matplotlib numpy ``` -------------------------------- ### Install Dependencies for AG-UI Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2026-03-03-GPT-Researcher-AG2/index.mdx Clone the build-with-ag2 repository and install the necessary Python dependencies for the AG-UI example. ```bash git clone https://github.com/ag2ai/build-with-ag2.git cd build-with-ag2/ag-ui/gpt-researcher pip install -r requirements.txt ``` -------------------------------- ### Initialize Agents and Setup Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_video_transcript_translate_with_whisper.ipynb Sets up Autogen AssistantAgent and UserProxyAgent, defines translation parameters, and loads necessary libraries. Ensure OPENAI_API_KEY is set in your environment. ```python from typing import Annotated, Any import whisper from openai import OpenAI import autogen source_language = "English" target_language = "Chinese" key = os.getenv("OPENAI_API_KEY") target_video = "your_file_path" assistant = autogen.AssistantAgent( name="assistant", system_message="For coding tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.", llm_config={"config_list": config_list, "timeout": 120}, ) user_proxy = autogen.UserProxyAgent( name="user_proxy", is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"), human_input_mode="NEVER", max_consecutive_auto_reply=10, code_execution_config={}, ) ``` -------------------------------- ### Install Project Templates Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/install.md Scaffolds a new project with full AI context. Variables can be passed to customize the template, and `--preview` shows changes without applying them. ```bash ag2 install template fullstack-agentic-app ag2 install template mcp-server-python --var project_name=my-server ag2 install template research-pipeline --preview ``` -------------------------------- ### Install AG2 with Quick Research Extra Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/reference-tools/quick-research.mdx Install AG2 with the `quick-research` extra. Use `autogen` as an alias for `ag2` if preferred. Ensure `openai` is installed for the example. ```bash pip install -U "ag2[openai,quick-research]" # Or using the autogen alias: pip install -U "autogen[openai,quick-research]" ``` -------------------------------- ### Install pydantic email validator Source: https://github.com/ag2ai/ag2/blob/main/notebook/mcp/mcp_proxy_asana.ipynb Installs the pydantic library with email validation support, required for certain examples. ```bash pip install "pydantic[email]" ``` -------------------------------- ### Create and Run a New Project Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/cli/index.mdx Scaffold a new project with a blank template, navigate into the project directory, and run the main agent with a message. ```bash ag2 create project my-app --template blank cd my-app ag2 run main.py --message "Hello, agent!" ``` -------------------------------- ### Install Dependencies for RetrieveChat Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_RetrieveChat.ipynb Install necessary dependencies for RetrieveChat, including autogen and flaml. This is a prerequisite for running the examples. ```bash pip install autogen[openai,retrievechat] flaml[automl] ``` -------------------------------- ### Prepare `start-chat` Endpoint Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_realtime_webrtc.ipynb Sets up the web server to serve the chat interface. Mounts static files and configures template rendering for the chat page. ```python notebook_path = os.getcwd() app.mount("/static", StaticFiles(directory=Path(notebook_path) / "agentchat_realtime_webrtc" / "static"), name="static") # Templates for HTML responses templates = Jinja2Templates(directory=Path(notebook_path) / "agentchat_realtime_webrtc" / "templates") @app.get("/start-chat/", response_class=HTMLResponse) async def start_chat(request: Request): """Endpoint to return the HTML page for audio chat.""" port = PORT # Extract the client's port return templates.TemplateResponse("chat.html", {"request": request, "port": port}) ``` -------------------------------- ### Install Dependencies and Run AG-UI Backend Source: https://github.com/ag2ai/ag2/blob/main/website/docs/beta/ag-ui/copilotkit-quickstart.mdx Navigate to the agent directory, install Python dependencies, set your LLM API key, and run the backend. ```bash cd agent-py pip install -r requirements.txt export OPENAI_API_KEY="your_openai_api_key" python backend.py ``` -------------------------------- ### Install Chess Package Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/models/togetherai.mdx Install the necessary 'chess' package using pip. This package is required for the chess game example. ```bash pip install chess ``` -------------------------------- ### Initiating a Swarm Chat with Agents and Tools Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/python-examples/swarm.mdx This example demonstrates setting up agents with specific system messages and functions, defining hand-off logic between them, and initiating a swarm chat with initial messages and shared context. It shows how to manage a lesson planning process involving a teacher, planner, and reviewer. ```python from autogen import ( AfterWork, OnCondition, AfterWorkOption, ConversableAgent, SwarmResult, initiate_swarm_chat, register_hand_off, LLMConfig, ) llm_config = LLMConfig(config_list={"api_type": "openai", "model": "gpt-5", "cache_seed": None}) # 1. Context shared_context = { "lesson_plans": [], "lesson_reviews": [], # Will be decremented, resulting in 0 (aka False) when no reviews are left "reviews_left": 2, } # 2. Functions def record_plan(lesson_plan: str, context_variables: dict) -> SwarmResult: """Record the lesson plan""" context_variables["lesson_plans"].append(lesson_plan) # Returning the updated context so the shared context can be updated return SwarmResult(context_variables=context_variables) def record_review(lesson_review: str, context_variables: dict) -> SwarmResult: """After a review has been made, increment the count of reviews""" context_variables["lesson_reviews"].append(lesson_review) context_variables["reviews_left"] -= 1 # Controlling the flow to the next agent from a tool call return SwarmResult( agent=teacher if context_variables["reviews_left"] < 0 else lesson_planner, context_variables=context_variables ) planner_message = """You are a classroom lesson planner. Given a topic, write a lesson plan for a fourth grade class. If you are given revision feedback, update your lesson plan and record it. Use the following format: