Skip to content

Python SDK for AI agent monitoring, LLM cost tracking, benchmarking, and more. Integrates with most LLMs and agent frameworks including CrewAI, Agno, OpenAI Agents SDK, Langchain, Autogen, AG2, and CamelAI

Agents sdk examples (#979)

Alex Reibmanb205b414524b
diff --git a/examples/openai_agents_sdk/customer_service_agent.ipynb b/examples/openai_agents_sdk/customer_service_agent.ipynb
new file mode 100644
index 00000000..53b84b95
--- /dev/null
+++ b/examples/openai_agents_sdk/customer_service_agent.ipynb
@@ -0,0 +1,245 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Install dependencies. \n",
+ "!pip install -U agentops openai-agents"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Set the API keys for your AgentOps and OpenAI accounts.\n",
+ "import os\n",
+ "\n",
+ "os.environ[\"OPENAI_API_KEY\"] = ''\n",
+ "os.environ[\"AGENTOPS_API_KEY\"] = ''\n",
+ "\n",
+ "if os.environ[\"OPENAI_API_KEY\"] == '':\n",
+ " raise ValueError(\"OPENAI_API_KEY is not set. You can get one at https://platform.openai.com/api-keys\")\n",
+ "if os.environ[\"AGENTOPS_API_KEY\"] == '':\n",
+ " raise ValueError(\"AGENTOPS_API_KEY is not set. You can get one at https://app.agentops.ai/\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from __future__ import annotations as _annotations\n",
+ "\n",
+ "import random\n",
+ "import uuid\n",
+ "from pydantic import BaseModel\n",
+ "import agentops\n",
+ "\n",
+ "# API key is automatically read from the environment variable\n",
+ "agentops.init(tags=[\"customer-service-agent\", \"agentops-example\"])\n",
+ "\n",
+ "from agents import (\n",
+ " Agent,\n",
+ " HandoffOutputItem,\n",
+ " ItemHelpers,\n",
+ " MessageOutputItem,\n",
+ " RunContextWrapper,\n",
+ " Runner,\n",
+ " ToolCallItem,\n",
+ " ToolCallOutputItem,\n",
+ " TResponseInputItem,\n",
+ " function_tool,\n",
+ " handoff,\n",
+ " trace,\n",
+ ")\n",
+ "from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX\n",
+ "\n",
+ "### CONTEXT\n",
+ "\n",
+ "\n",
+ "class AirlineAgentContext(BaseModel):\n",
+ " passenger_name: str | None = None\n",
+ " confirmation_number: str | None = None\n",
+ " seat_number: str | None = None\n",
+ " flight_number: str | None = None\n",
+ "\n",
+ "\n",
+ "### TOOLS\n",
+ "\n",
+ "\n",
+ "@function_tool(\n",
+ " name_override=\"faq_lookup_tool\", description_override=\"Lookup frequently asked questions.\"\n",
+ ")\n",
+ "async def faq_lookup_tool(question: str) -> str:\n",
+ " if \"bag\" in question or \"baggage\" in question:\n",
+ " return (\n",
+ " \"You are allowed to bring one bag on the plane. \"\n",
+ " \"It must be under 50 pounds and 22 inches x 14 inches x 9 inches.\"\n",
+ " )\n",
+ " elif \"seats\" in question or \"plane\" in question:\n",
+ " return (\n",
+ " \"There are 120 seats on the plane. \"\n",
+ " \"There are 22 business class seats and 98 economy seats. \"\n",
+ " \"Exit rows are rows 4 and 16. \"\n",
+ " \"Rows 5-8 are Economy Plus, with extra legroom. \"\n",
+ " )\n",
+ " elif \"wifi\" in question:\n",
+ " return \"We have free wifi on the plane, join Airline-Wifi\"\n",
+ " return \"I'm sorry, I don't know the answer to that question.\"\n",
+ "\n",
+ "\n",
+ "@function_tool\n",
+ "async def update_seat(\n",
+ " context: RunContextWrapper[AirlineAgentContext], confirmation_number: str, new_seat: str\n",
+ ") -> str:\n",
+ " \"\"\"\n",
+ " Update the seat for a given confirmation number.\n",
+ "\n",
+ " Args:\n",
+ " confirmation_number: The confirmation number for the flight.\n",
+ " new_seat: The new seat to update to.\n",
+ " \"\"\"\n",
+ " # Update the context based on the customer's input\n",
+ " context.context.confirmation_number = confirmation_number\n",
+ " context.context.seat_number = new_seat\n",
+ " # Ensure that the flight number has been set by the incoming handoff\n",
+ " assert context.context.flight_number is not None, \"Flight number is required\"\n",
+ " return f\"Updated seat to {new_seat} for confirmation number {confirmation_number}\"\n",
+ "\n",
+ "\n",
+ "### HOOKS\n",
+ "\n",
+ "\n",
+ "async def on_seat_booking_handoff(context: RunContextWrapper[AirlineAgentContext]) -> None:\n",
+ " flight_number = f\"FLT-{random.randint(100, 999)}\"\n",
+ " context.context.flight_number = flight_number\n",
+ "\n",
+ "\n",
+ "### AGENTS\n",
+ "\n",
+ "faq_agent = Agent[AirlineAgentContext](\n",
+ " name=\"FAQ Agent\",\n",
+ " handoff_description=\"A helpful agent that can answer questions about the airline.\",\n",
+ " instructions=f\"\"\"{RECOMMENDED_PROMPT_PREFIX}\n",
+ " You are an FAQ agent. If you are speaking to a customer, you probably were transferred to from the triage agent.\n",
+ " Use the following routine to support the customer.\n",
+ " # Routine\n",
+ " 1. Identify the last question asked by the customer.\n",
+ " 2. Use the faq lookup tool to answer the question. Do not rely on your own knowledge.\n",
+ " 3. If you cannot answer the question, transfer back to the triage agent.\"\"\",\n",
+ " tools=[faq_lookup_tool],\n",
+ ")\n",
+ "\n",
+ "seat_booking_agent = Agent[AirlineAgentContext](\n",
+ " name=\"Seat Booking Agent\",\n",
+ " handoff_description=\"A helpful agent that can update a seat on a flight.\",\n",
+ " instructions=f\"\"\"{RECOMMENDED_PROMPT_PREFIX}\n",
+ " You are a seat booking agent. If you are speaking to a customer, you probably were transferred to from the triage agent.\n",
+ " Use the following routine to support the customer.\n",
+ " # Routine\n",
+ " 1. Ask for their confirmation number.\n",
+ " 2. Ask the customer what their desired seat number is.\n",
+ " 3. Use the update seat tool to update the seat on the flight.\n",
+ " If the customer asks a question that is not related to the routine, transfer back to the triage agent. \"\"\",\n",
+ " tools=[update_seat],\n",
+ ")\n",
+ "\n",
+ "triage_agent = Agent[AirlineAgentContext](\n",
+ " name=\"Triage Agent\",\n",
+ " handoff_description=\"A triage agent that can delegate a customer's request to the appropriate agent.\",\n",
+ " instructions=(\n",
+ " f\"{RECOMMENDED_PROMPT_PREFIX} \"\n",
+ " \"You are a helpful triaging agent. You can use your tools to delegate questions to other appropriate agents.\"\n",
+ " ),\n",
+ " handoffs=[\n",
+ " faq_agent,\n",
+ " handoff(agent=seat_booking_agent, on_handoff=on_seat_booking_handoff),\n",
+ " ],\n",
+ ")\n",
+ "\n",
+ "faq_agent.handoffs.append(triage_agent)\n",
+ "seat_booking_agent.handoffs.append(triage_agent)\n",
+ "\n",
+ "\n",
+ "### RUN\n",
+ "\n",
+ "\n",
+ "async def main():\n",
+ " current_agent: Agent[AirlineAgentContext] = triage_agent\n",
+ " input_items: list[TResponseInputItem] = []\n",
+ " context = AirlineAgentContext()\n",
+ "\n",
+ " # Normally, each input from the user would be an API request to your app, and you can wrap the request in a trace()\n",
+ " # Here, we'll just use a random UUID for the conversation ID\n",
+ " conversation_id = uuid.uuid4().hex[:16]\n",
+ "\n",
+ " while True:\n",
+ " user_input = input(\"Enter your message: \")\n",
+ " with trace(\"Customer service\", group_id=conversation_id):\n",
+ " input_items.append({\"content\": user_input, \"role\": \"user\"})\n",
+ " result = await Runner.run(current_agent, input_items, context=context)\n",
+ "\n",
+ " for new_item in result.new_items:\n",
+ " agent_name = new_item.agent.name\n",
+ " if isinstance(new_item, MessageOutputItem):\n",
+ " print(f\"{agent_name}: {ItemHelpers.text_message_output(new_item)}\")\n",
+ " elif isinstance(new_item, HandoffOutputItem):\n",
+ " print(\n",
+ " f\"Handed off from {new_item.source_agent.name} to {new_item.target_agent.name}\"\n",
+ " )\n",
+ " elif isinstance(new_item, ToolCallItem):\n",
+ " print(f\"{agent_name}: Calling a tool\")\n",
+ " elif isinstance(new_item, ToolCallOutputItem):\n",
+ " print(f\"{agent_name}: Tool call output: {new_item.output}\")\n",
+ " else:\n",
+ " print(f\"{agent_name}: Skipping item: {new_item.__class__.__name__}\")\n",
+ " input_items = result.to_input_list()\n",
+ " current_agent = result.last_agent\n",
+ "\n",
+ "\n",
+ "await main()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can check the trace in the AgentOps UI: https://app.agentops.ai/traces"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "base",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/openai_agents_sdk/web_search_agent.ipynb b/examples/openai_agents_sdk/web_search_agent.ipynb
new file mode 100644
index 00000000..54d90e21
--- /dev/null
+++ b/examples/openai_agents_sdk/web_search_agent.ipynb
@@ -0,0 +1,97 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Install dependencies. \n",
+ "!pip install -U agentops openai-agents"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Set the API keys for your AgentOps and OpenAI accounts.\n",
+ "import os\n",
+ "\n",
+ "os.environ[\"OPENAI_API_KEY\"] = ''\n",
+ "os.environ[\"AGENTOPS_API_KEY\"] = ''\n",
+ "\n",
+ "if os.environ[\"OPENAI_API_KEY\"] == '':\n",
+ " raise ValueError(\"OPENAI_API_KEY is not set. You can get one at https://platform.openai.com/api-keys\")\n",
+ "if os.environ[\"AGENTOPS_API_KEY\"] == '':\n",
+ " raise ValueError(\"AGENTOPS_API_KEY is not set. You can get one at https://app.agentops.ai/\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agents import Agent, Runner, WebSearchTool, trace\n",
+ "import agentops\n",
+ "\n",
+ "# AgentOps automatically reads the API key from the environment variable\n",
+ "agentops.init(tags=[\"web-search-agent\", \"agentops-example\"])\n",
+ "\n",
+ "async def main():\n",
+ " agent = Agent(\n",
+ " name=\"Web searcher\",\n",
+ " instructions=\"You are a helpful agent.\",\n",
+ " tools=[WebSearchTool(user_location={\"type\": \"approximate\", \"city\": \"New York\"})],\n",
+ " )\n",
+ "\n",
+ " with trace(\"Web search example\"):\n",
+ " result = await Runner.run(\n",
+ " agent,\n",
+ " \"search the web for 'local sports news' and give me 1 interesting update in a sentence.\",\n",
+ " )\n",
+ " print(result.final_output)\n",
+ " # The New York Giants are reportedly pursuing quarterback Aaron Rodgers after his ...\n",
+ "\n",
+ "await main()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can check the trace in the AgentOps UI: https://app.agentops.ai/traces"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "base",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}