openai_agents_prompt_chaining.ipynb•5.71 kB
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "SUknhuHKyc-E"
},
"source": [
"# <center>OpenAI agent pattern: prompt chaining agent</center>\n",
"\n",
"A starter guide for building an agent which chains two prompts together to generate an output using the `openai-agents` library.\n",
"\n",
"In the following example, we'll build a stock portfolio creation system using this pattern:\n",
"1. **Search Agent (Generation):** Searches the web for information on particular stock tickers.\n",
"2. **Report Agent (Generation):** Creates a portfolio of stocks and ETFs that supports the user's investment strategy."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n69HR7eJswNt"
},
"source": [
"### Install Libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install base libraries for OpenAI\n",
"!pip install -q openai openai-agents pydantic\n",
"\n",
"# Install optional libraries for OpenInference/OpenTelemetry tracing\n",
"!pip install -q arize-phoenix-otel openinference-instrumentation-openai-agents openinference-instrumentation-openai"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jQnyEnJisyn3"
},
"source": [
"### Setup Keys\n",
"\n",
"Add your OpenAI API key to the environment variable `OPENAI_API_KEY`.\n",
"\n",
"Copy your Phoenix `API_KEY` from your settings page at [app.phoenix.arize.com](https://app.phoenix.arize.com)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from getpass import getpass\n",
"\n",
"if \"OPENAI_API_KEY\" not in os.environ:\n",
" os.environ[\"OPENAI_API_KEY\"] = getpass(\"🔑 Enter your OpenAI API key: \")\n",
"\n",
"if \"PHOENIX_API_KEY\" not in os.environ:\n",
" os.environ[\"PHOENIX_API_KEY\"] = getpass(\"🔑 Enter your Phoenix API key: \")\n",
"\n",
"if \"PHOENIX_COLLECTOR_ENDPOINT\" not in os.environ:\n",
" os.environ[\"PHOENIX_COLLECTOR_ENDPOINT\"] = getpass(\"🔑 Enter your Phoenix Collector Endpoint\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kfid5cE99yN5"
},
"source": [
"### Setup Tracing"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from phoenix.otel import register\n",
"\n",
"tracer_provider = register(\n",
" project_name=\"openai-agents\",\n",
" auto_instrument=True,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating the agent\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pprint import pprint\n",
"from textwrap import dedent\n",
"\n",
"from agents import Agent, Runner, TResponseInputItem, WebSearchTool\n",
"from agents.model_settings import ModelSettings\n",
"from pydantic import BaseModel, Field\n",
"\n",
"\n",
"class PortfolioItem(BaseModel):\n",
" ticker: str = Field(description=\"The ticker of the stock or ETF.\")\n",
" allocation: float = Field(\n",
" description=\"The percentage allocation of the ticker in the portfolio. The sum of all allocations should be 100.\"\n",
" )\n",
" reason: str = Field(description=\"The reason why this ticker is included in the portfolio.\")\n",
"\n",
"\n",
"class Portfolio(BaseModel):\n",
" tickers: list[PortfolioItem] = Field(\n",
" description=\"A list of tickers that could support the user's stated investment strategy.\"\n",
" )\n",
"\n",
"\n",
"portfolio_agent = Agent(\n",
" name=\"Portfolio Agent\",\n",
" instructions=dedent(\n",
" \"\"\"You are a senior financial analyst. You will be provided with a stock research report. Your task is to create a portfolio of stocks and ETFs that could support the user's stated investment strategy. Include facts and data from the research report in the stated reasons for the portfolio allocation.\"\"\"\n",
" ),\n",
" model=\"o4-mini\",\n",
" output_type=Portfolio,\n",
")\n",
"\n",
"research_agent = Agent(\n",
" name=\"FinancialSearchAgent\",\n",
" instructions=dedent(\n",
" \"\"\"You are a research assistant specializing in financial topics. Given an investment strategy, use web search to retrieve up‑to‑date context and produce a short summary of stocks that support the investment strategy at most 50 words. Focus on key numbers, events, or quotes that will be useful to a financial analyst.\"\"\"\n",
" ),\n",
" model=\"gpt-4.1\",\n",
" tools=[WebSearchTool()],\n",
" model_settings=ModelSettings(tool_choice=\"required\", parallel_tool_calls=True),\n",
")\n",
"\n",
"user_input = input(\"Enter your investment strategy: \")\n",
"input_items: list[TResponseInputItem] = [\n",
" {\"content\": f\"My investment strategy: {user_input}\", \"role\": \"user\"}\n",
"]\n",
"\n",
"\n",
"research_output = await Runner.run(research_agent, input_items)\n",
"pprint(research_output.final_output)\n",
"\n",
"input_items = research_output.to_input_list()\n",
"portfolio_output = await Runner.run(portfolio_agent, input_items)\n",
"pprint(portfolio_output.final_output)"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}