### 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: Lesson plan title Key learning objectives """ reviewer_message = """You are a classroom lesson reviewer. You compare the lesson plan to the fourth grade curriculum and provide a maximum of 3 recommended changes for each review. Always provide feedback for the current lesson plan. """ teacher_message = """You are a classroom teacher. You decide topics for lessons and work with a lesson planner. and reviewer to create and finalise lesson plans. """ # 3. Our agents now have tools to use (functions above) lesson_planner = ConversableAgent( name="planner_agent", system_message=planner_message, functions=[record_plan], llm_config=llm_config, ) lesson_reviewer = ConversableAgent( name="reviewer_agent", system_message=reviewer_message, functions=[record_review], llm_config=llm_config, ) teacher = ConversableAgent( name="teacher_agent", system_message=teacher_message, llm_config=llm_config, ) # 4. Transitions using hand-offs # Lesson planner will create a plan and hand off to the reviewer if we're still # allowing reviews. After that's done, transition to the teacher. register_hand_off(lesson_planner, [ OnCondition( target=lesson_reviewer, condition="After creating/updating and recording the plan, it must be reviewed.", available="reviews_left", ), AfterWork(agent=teacher), ] ) # Lesson reviewer will review the plan and return control to the planner if there's # no plan to review, otherwise it will provide a review and register_hand_off(lesson_reviewer, [ OnCondition(target=lesson_planner, condition="After new feedback has been made and recorded, the plan must be updated.") , AfterWork(agent=teacher), ] ) # Teacher works with the lesson planner to create a plan. When control returns to them and # a plan exists, they'll end the swarm. register_hand_off(teacher, [ OnCondition(target=lesson_planner, condition="Create a lesson plan.", available="reviews_left"), AfterWork(AfterWorkOption.TERMINATE), ] ) # 5. Run the Swarm which returns the chat and updated context variables chat_result, context_variables, last_agent = initiate_swarm_chat( initial_agent=teacher, agents=[lesson_planner, lesson_reviewer, teacher], messages="Today, let's introduce our kids to the solar system.", context_variables=shared_context, ) print(f"Number of reviews: {len(context_variables['lesson_reviews'])}") print(f"Reviews remaining: {context_variables['reviews_left']}") print(f"Final Lesson Plan:\n{context_variables['lesson_plans'][-1]}") ``` -------------------------------- ### Clone and Install LLaVA Locally Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_lmm_llava.ipynb Clone the LLaVA repository and install its inference package locally. This requires a GPU and specific environment setup. ```bash git clone https://github.com/haotian-liu/LLaVA.git cd LLaVA conda create -n llava python=3.10 -y conda activate llava pip install --upgrade pip # enable PEP 660 support pip install -e . ``` -------------------------------- ### Install Dependencies Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/deployments/deploy-an-agent-to-vertexai.mdx Create a virtual environment and install required Python packages from requirements.txt. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Initialize API Keys and Memory Client Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_memory_using_mem0.ipynb Set up environment variables for API keys and initialize the Mem0 MemoryClient. Replace 'your_api_key' with your actual keys. ```python import os from mem0 import MemoryClient from autogen import ConversableAgent os.environ["OPENAI_API_KEY"] = "your_api_key" os.environ["MEM0_API_KEY"] = "your_api_key" ``` -------------------------------- ### Install Dependencies and Run Uvicorn Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-05-07-AG2-Copilot-Integration/index.mdx Installs project dependencies from requirements.txt and starts the FastAPI application using Uvicorn on port 8008 with hot-reloading enabled. ```bash cd agent-py pip install -r requirements.txt uvicorn simple_workflow:app --port 8008 --reload ``` -------------------------------- ### Start the Server Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/advanced-concepts/realtime-agent/websocket.mdx Run the application using Uvicorn on a specified port. ```bash uvicorn realtime_over_websockets.main:app --port 5050 ``` -------------------------------- ### Lockfile Example Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/install.md This JSON structure represents the lockfile, which tracks installed artifacts and their versions. It is used by `ag2 install update` to check for newer versions. ```json { "installed": { "skills/ag2": {"version": "0.3.0", "installed_at": "2026-03-18T00:00:00Z"}, "tools/github-mcp": {"version": "1.0.0", "installed_at": "2026-03-18T00:00:00Z"}, "agents/research-analyst": {"version": "1.0.0", "installed_at": "2026-03-18T00:00:00Z"} } } ``` -------------------------------- ### Install Datasets Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/install.md Adds evaluation and training data to your project. Use `--full` to download remote files in addition to metadata and eval registration. ```bash ag2 install dataset agent-eval-bench # Inline sample only ag2 install dataset agent-eval-bench --full # Download remote files too ``` -------------------------------- ### Development Setup for AG2 CLI Source: https://github.com/ag2ai/ag2/blob/main/cli/README.md Set up the AG2 CLI for development by installing it in editable mode with development dependencies. Verify the installation by checking the version. ```bash cd cli pip install -e ".[dev]" ag2 --version ``` -------------------------------- ### Start the Server Source: https://github.com/ag2ai/ag2/blob/main/website/snippets/advanced-concepts/realtime-agent/webrtc.mdx Run the application server using Uvicorn on the specified port. ```bash uvicorn realtime_over_webrtc.main:app --port 5050 ``` -------------------------------- ### ReasoningAgent Configuration Example Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/reference-agents/reasoningagent.mdx Demonstrates setting up ReasoningAgent with LLM configuration, defining a question, and seeding for reproducibility. Includes a helper function for message summarization and initializes a UserProxyAgent. ```python import random from autogen.agents.experimental import ReasoningAgent, ThinkNode from autogen import AssistantAgent, UserProxyAgent, LLMConfig from dotenv import load_dotenv import os load_dotenv() # Put your key in the OPENAI_API_KEY environment variable llm_config = LLMConfig({"api_type": "openai", "model": "gpt-5-nano","api_key":os.getenv("OPENAI_API_KEY")}) verbose = True question = "What is the expected maximum dice value if you can roll a 6-sided dice three times?" random.seed(1) # setup seed for reproducibility def last_meaningful_msg(sender, recipient, summary_args): import warnings if sender == recipient: return "TERMINATE" summary = "" chat_messages = recipient.chat_messages[sender] for msg in reversed(chat_messages): try: content = msg["content"] if isinstance(content, str): summary = content.replace("TERMINATE", "") elif isinstance(content, list): # Remove the `TERMINATE` word in the content list. summary = "\n".join( x["text"].replace("TERMINATE", "") for x in content if isinstance(x, dict) and "text" in x ) if summary.strip().rstrip(): return summary except (IndexError, AttributeError) as e: warnings.warn(f"Cannot extract summary using last_msg: {e}. Using an empty str as summary.", UserWarning) return summary user_proxy = UserProxyAgent( name="user_proxy", human_input_mode="NEVER", code_execution_config=False, is_termination_msg=lambda x: True, # terminate when reasoning agent responds ) ``` -------------------------------- ### A2A Server Tracing Setup Example Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/tracing/opentelemetry.mdx This example sets up a ConversableAgent, an A2aAgentServer, and then instruments the server for distributed tracing. The built app is then ready to receive traced requests. ```python from autogen import ConversableAgent, LLMConfig from autogen.a2a import A2aAgentServer from autogen.opentelemetry import instrument_a2a_server llm_config = LLMConfig({"model": "gpt-4o-mini"}) agent = ConversableAgent( name="tech_agent", system_message="You solve technical problems.", llm_config=llm_config, ) server = A2aAgentServer(agent, url="http://localhost:18123/") server = instrument_a2a_server(server, tracer_provider=tracer_provider) app = server.build() ``` -------------------------------- ### Install Dependencies for RetrieveChat with Couchbase Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_RetrieveChat_couchbase.ipynb Installs necessary Python packages for RetrieveChat functionality, including support for Couchbase and OpenAI. Ensure you have the correct dependencies for your specific setup. ```bash pip install ag2[openai,retrievechat-couchbase] flaml[automl] ``` -------------------------------- ### Start the Server Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-01-10-WebSockets/index.mdx Run the main Python script to start the WebSocket server. ```bash python agentchat-over-websockets/main.py ``` -------------------------------- ### Open an MCP Session and Create a Toolkit Source: https://github.com/ag2ai/ag2/blob/main/website/docs/_blogs/2025-12-24-AG2-MultiMCPSessionManager/index.mdx Demonstrates how to asynchronously open a session with a specified server configuration and then create a toolkit for interacting with the session. This is a fundamental step for agent communication. ```python async with MCPClientSessionManager().open_session(arxiv_server) as session: toolkit = await create_toolkit(session=session) # Use toolkit with your agents ``` -------------------------------- ### Initialize Gemini API Key and Prompt Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_gemini_thinking_config_example.ipynb Sets up the necessary environment variables for the Gemini API key and defines a sample prompt for agent interaction. Ensure the GOOGLE_GEMINI_API_KEY is set. ```python import os from dotenv import load_dotenv from autogen import ConversableAgent, LLMConfig load_dotenv() api_key = os.getenv("GOOGLE_GEMINI_API_KEY") if not api_key: raise RuntimeError("GOOGLE_GEMINI_API_KEY is not set. Please set it in your environment or .env file.") prompt = """You are playing the 20 question game. You know that what you are looking for is an aquatic mammal that doesn't live in the sea, is venomous and that's smaller than a cat. What could that be and how could you make sure? " ``` -------------------------------- ### Install AG2 with LLM Provider Packages Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/basic-concepts/llm-configuration.mdx Install AG2 with specific LLM provider packages using pip. This is required starting from version 0.8 as provider packages are not included by default. ```bash pip install ag2[openai] pip install ag2[gemini] pip install ag2[anthropic,cohere,mistral] ``` -------------------------------- ### Install AG2 with YouTube Search Dependencies Source: https://github.com/ag2ai/ag2/blob/main/notebook/tools_youtube_search.ipynb Install AG2 with the `google-search` extra and `openai` for YouTube search capabilities. Use this command to set up your environment. ```bash pip install -U ag2[openai,google-search] ``` -------------------------------- ### Example Workflow for Publishing an Artifact Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/publish.md This workflow demonstrates the typical steps for creating, implementing, validating, and publishing a tool artifact. ```bash # 1. Scaffold a new tool artifact ag2 create artifact tool web-scraper # 2. Implement the tool and write skills cd web-scraper # ... edit src/web_scraper.py, skills/, artifact.json ... # 3. Validate before publishing ag2 publish artifact . --dry-run # 4. Publish to the registry ag2 publish artifact . # → Validates, forks ag2ai/resource-hub, creates PR ``` -------------------------------- ### Configure LLM with HTTP Client for Example 1 Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_microsoft_fabric.ipynb Configure LLM settings with an HTTP client for use in Example 1, which involves AssistantAgent and UserProxyAgent for code execution. This setup is for openai>=1. ```python import types from synapse.ml.fabric.credentials import get_openai_httpx_sync_client import autogen http_client = get_openai_httpx_sync_client() # http_client is needed for openai>1 http_client.__deepcopy__ = types.MethodType( lambda self, memo: self, http_client ) # https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/llm-configuration-deep-dive/#adding-http-client-in-llm_config-for-proxy # Set temperature, timeout and other LLM configurations llm_config = autogen.LLMConfig( { "model": "gpt-4o", "http_client": http_client, "api_version": "2024-02-01", "api_type": "azure", }, temperature=0, ) ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/ag2ai/ag2/blob/main/website/README.md Build the documentation locally from the project root directory. Use the --force flag to clear cache and rebuild from scratch. ```bash ./scripts/docs_build_mkdocs.sh ``` ```bash ./scripts/docs_build_mkdocs.sh --force ``` -------------------------------- ### Initiate Chat with Assistant Agent Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/getting-started/Getting-Started.mdx Starts a chat with an assistant agent. This is a basic example of initiating a conversation. ```python user_proxy.initiate_chat( assistant, message="Plot a chart of NVDA and TESLA stock price change YTD.", ) ``` -------------------------------- ### Initialize CaptainAgent with Libraries Source: https://github.com/ag2ai/ag2/blob/main/website/docs/user-guide/reference-agents/captainagent.mdx Demonstrates how to initialize the CaptainAgent, specifying agent and tool libraries, and configuring API keys for necessary tools like Bing search and YouTube transcription. ```python # The function requires BING api key and Rapid API key to work. You can follow the instructions from docs to get one. import os from autogen import UserProxyAgent from autogen.agentchat.contrib.captainagent import CaptainAgent os.environ["BING_API_KEY"] = "" # set your bing api key here, if you do not need the search engine, you can skip this step os.environ["RAPID_API_KEY"] = ( "" # set your rapid api key here, in order for this example to work, you need to subscribe to the youtube transcription api(https://rapidapi.com/solid-api-solid-api-default/api/youtube-transcript3) ) ## build agents captain_agent = CaptainAgent( name="captain_agent", code_execution_config={"use_docker": False, "work_dir": "groupchat"}, agent_lib="captainagent_expert_library.json", tool_lib="default", agent_config_save_path=None, # If you'd like to save the created agents in nested chat for further use, specify the save directory here llm_config=llm_config, ) captain_user_proxy = UserProxyAgent(name="captain_user_proxy", human_input_mode="NEVER") query = """# Task Your task is to solve a question given by a user. # Question Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec. What does Teal\'c say in response to the question \"Isn\'t that hot?\" """.strip() result = captain_user_proxy.initiate_chat(captain_agent, message=query) ``` -------------------------------- ### Import Necessary Libraries for Autogen and Environment Setup Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_bedrock_client_structured_output.ipynb Import required modules from Autogen, Pydantic, and dotenv for agent creation, group chat management, and environment variable loading. This setup is crucial for running the example. ```python import os from dotenv import load_dotenv from pydantic import BaseModel from autogen import ConversableAgent, LLMConfig, UserProxyAgent from autogen.agentchat.group.patterns.auto import AutoPattern load_dotenv() ``` -------------------------------- ### Initiate Chat with Assistant Source: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_teachable_oai_assistants.ipynb Starts a conversation with the OSS Analyst assistant, providing an initial message to guide its task. ```python user_proxy.initiate_chat(oss_analyst, message="Top 10 developers with the most followers") ``` -------------------------------- ### Install from Local Path or GitHub URL Source: https://github.com/ag2ai/ag2/blob/main/cli/docs/install.md Installs artifacts directly from a local directory or a GitHub repository. ```bash ag2 install from ./local-artifact ag2 install from github.com/someuser/my-skills ```