diff --git a/openai_agents/handoffs/README.md b/openai_agents/handoffs/README.md new file mode 100644 index 000000000..c38b09198 --- /dev/null +++ b/openai_agents/handoffs/README.md @@ -0,0 +1,44 @@ +# Handoffs Examples + +Agent handoff patterns with message filtering in Temporal workflows. + +*Adapted from [OpenAI Agents SDK handoffs examples](https://github.com/openai/openai-agents-python/tree/main/examples/handoffs)* + +Before running these examples, be sure to review the [prerequisites and background on the integration](../README.md). + +## Running the Examples + +First, start the worker: +```bash +uv run openai_agents/handoffs/run_worker.py +``` + +Then run the workflow: + +### Message Filter Workflow +Demonstrates agent handoffs with message history filtering: +```bash +uv run openai_agents/handoffs/run_message_filter_workflow.py +``` + +## Workflow Pattern + +The workflow demonstrates a 4-step conversation with message filtering: + +1. **Introduction**: User greets first agent with name +2. **Tool Usage**: First agent generates random number using function tool +3. **Agent Switch**: Conversation moves to second agent for general questions +4. **Spanish Handoff**: Second agent detects Spanish and hands off to Spanish specialist + +During the Spanish handoff, message filtering occurs: +- All tool-related messages are removed from history +- First two messages are dropped (demonstration of selective context) +- Filtered conversation continues with Spanish agent + +The workflow returns both the final response and complete message history for inspection. + +## Omitted Examples + +The following patterns from the [reference repository](https://github.com/openai/openai-agents-python/tree/main/examples/handoffs) are not included in this Temporal adaptation: + +- **Message Filter Streaming**: Streaming capabilities are not yet available in the Temporal integration \ No newline at end of file diff --git a/openai_agents/handoffs/run_message_filter_workflow.py b/openai_agents/handoffs/run_message_filter_workflow.py new file mode 100644 index 000000000..7ecb9f478 --- /dev/null +++ b/openai_agents/handoffs/run_message_filter_workflow.py @@ -0,0 +1,38 @@ +import asyncio +import json + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.handoffs.workflows.message_filter_workflow import ( + MessageFilterWorkflow, +) + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + MessageFilterWorkflow.run, + "Sora", + id="message-filter-workflow", + task_queue="openai-agents-handoffs-task-queue", + ) + + print(f"Final output: {result.final_output}") + print("\n===Final messages===\n") + + # Print the final message history to see the effect of the message filter + for message in result.final_messages: + print(json.dumps(message, indent=2)) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/handoffs/run_worker.py b/openai_agents/handoffs/run_worker.py new file mode 100644 index 000000000..8941f4d85 --- /dev/null +++ b/openai_agents/handoffs/run_worker.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import asyncio +from datetime import timedelta + +from temporalio.client import Client +from temporalio.contrib.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin +from temporalio.worker import Worker + +from openai_agents.handoffs.workflows.message_filter_workflow import ( + MessageFilterWorkflow, +) + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin( + model_params=ModelActivityParameters( + start_to_close_timeout=timedelta(seconds=60) + ) + ), + ], + ) + + worker = Worker( + client, + task_queue="openai-agents-handoffs-task-queue", + workflows=[ + MessageFilterWorkflow, + ], + activities=[ + # No custom activities needed for these workflows + ], + ) + await worker.run() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/handoffs/workflows/message_filter_workflow.py b/openai_agents/handoffs/workflows/message_filter_workflow.py new file mode 100644 index 000000000..8adc9453f --- /dev/null +++ b/openai_agents/handoffs/workflows/message_filter_workflow.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import List + +from agents import Agent, HandoffInputData, Runner, function_tool, handoff +from agents.extensions import handoff_filters +from agents.items import TResponseInputItem +from temporalio import workflow + + +@dataclass +class MessageFilterResult: + final_output: str + final_messages: List[TResponseInputItem] + + +@function_tool +def random_number_tool(max: int) -> int: + """Return a random integer between 0 and the given maximum.""" + return workflow.random().randint(0, max) + + +def spanish_handoff_message_filter( + handoff_message_data: HandoffInputData, +) -> HandoffInputData: + # First, we'll remove any tool-related messages from the message history + handoff_message_data = handoff_filters.remove_all_tools(handoff_message_data) + + # Second, we'll also remove the first two items from the history, just for demonstration + history = ( + tuple(handoff_message_data.input_history[2:]) + if isinstance(handoff_message_data.input_history, tuple) + else handoff_message_data.input_history + ) + + return HandoffInputData( + input_history=history, + pre_handoff_items=tuple(handoff_message_data.pre_handoff_items), + new_items=tuple(handoff_message_data.new_items), + ) + + +@workflow.defn +class MessageFilterWorkflow: + @workflow.run + async def run(self, user_name: str = "Sora") -> MessageFilterResult: + first_agent = Agent( + name="Assistant", + instructions="Be extremely concise.", + tools=[random_number_tool], + ) + + spanish_agent = Agent( + name="Spanish Assistant", + instructions="You only speak Spanish and are extremely concise.", + handoff_description="A Spanish-speaking assistant.", + ) + + second_agent = Agent( + name="Assistant", + instructions=( + "Be a helpful assistant. If the user speaks Spanish, handoff to the Spanish assistant." + ), + handoffs=[ + handoff(spanish_agent, input_filter=spanish_handoff_message_filter) + ], + ) + + # 1. Send a regular message to the first agent + result = await Runner.run(first_agent, input=f"Hi, my name is {user_name}.") + + # 2. Ask it to generate a number + result = await Runner.run( + first_agent, + input=result.to_input_list() + + [ + { + "content": "Can you generate a random number between 0 and 100?", + "role": "user", + } + ], + ) + + # 3. Call the second agent + result = await Runner.run( + second_agent, + input=result.to_input_list() + + [ + { + "content": "I live in New York City. What's the population of the city?", + "role": "user", + } + ], + ) + + # 4. Cause a handoff to occur + result = await Runner.run( + second_agent, + input=result.to_input_list() + + [ + { + "content": "Por favor habla en español. ¿Cuál es mi nombre y dónde vivo?", + "role": "user", + } + ], + ) + + # Return the final result and message history + return MessageFilterResult( + final_output=result.final_output, final_messages=result.to_input_list() + ) diff --git a/openai_agents/hosted_mcp/README.md b/openai_agents/hosted_mcp/README.md new file mode 100644 index 000000000..78a371311 --- /dev/null +++ b/openai_agents/hosted_mcp/README.md @@ -0,0 +1,39 @@ +# Hosted MCP Examples + +Integration with hosted MCP (Model Context Protocol) servers using OpenAI agents in Temporal workflows. + +*Adapted from [OpenAI Agents SDK hosted_mcp examples](https://github.com/openai/openai-agents-python/tree/main/examples/hosted_mcp)* + +Before running these examples, be sure to review the [prerequisites and background on the integration](../README.md). + +## Running the Examples + +First, start the worker (supports all MCP workflows): +```bash +uv run openai_agents/hosted_mcp/run_worker.py +``` + +Then run individual examples in separate terminals: + +### Simple MCP Connection +Connect to a hosted MCP server without approval requirements (trusted servers): +```bash +uv run openai_agents/hosted_mcp/run_simple_mcp_workflow.py +``` + +### MCP with Approval Callbacks +Connect to a hosted MCP server with approval workflow for tool execution: +```bash +uv run openai_agents/hosted_mcp/run_approval_mcp_workflow.py +``` + +## MCP Server Configuration + +Both examples default to using the GitMCP server (`https://gitmcp.io/openai/codex`) which provides repository analysis capabilities. The workflows can be easily modified to use different MCP servers by changing the `server_url` parameter. + +### Approval Workflow Notes + +The approval example demonstrates the callback structure for tool approvals in a Temporal context. In this implementation: + +- The approval callback automatically approves requests for demonstration purposes +- In production environments, approvals would typically be handled by communicating with a human user. Because the approval executes in the Temporal workflow, you can use signals or updates to communicate approval status. diff --git a/openai_agents/hosted_mcp/run_approval_mcp_workflow.py b/openai_agents/hosted_mcp/run_approval_mcp_workflow.py new file mode 100644 index 000000000..8821c78a7 --- /dev/null +++ b/openai_agents/hosted_mcp/run_approval_mcp_workflow.py @@ -0,0 +1,30 @@ +import asyncio + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.hosted_mcp.workflows.approval_mcp_workflow import ApprovalMCPWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + ApprovalMCPWorkflow.run, + "Which language is this repo written in?", + id="approval-mcp-workflow", + task_queue="openai-agents-hosted-mcp-task-queue", + ) + + print(f"Result: {result}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/hosted_mcp/run_simple_mcp_workflow.py b/openai_agents/hosted_mcp/run_simple_mcp_workflow.py new file mode 100644 index 000000000..5e0c064f5 --- /dev/null +++ b/openai_agents/hosted_mcp/run_simple_mcp_workflow.py @@ -0,0 +1,30 @@ +import asyncio + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.hosted_mcp.workflows.simple_mcp_workflow import SimpleMCPWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + SimpleMCPWorkflow.run, + "Which language is this repo written in?", + id="simple-mcp-workflow", + task_queue="openai-agents-hosted-mcp-task-queue", + ) + + print(f"Result: {result}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/hosted_mcp/run_worker.py b/openai_agents/hosted_mcp/run_worker.py new file mode 100644 index 000000000..fb25f7b6b --- /dev/null +++ b/openai_agents/hosted_mcp/run_worker.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import asyncio +from datetime import timedelta + +from temporalio.client import Client +from temporalio.contrib.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin +from temporalio.worker import Worker + +from openai_agents.hosted_mcp.workflows.approval_mcp_workflow import ApprovalMCPWorkflow +from openai_agents.hosted_mcp.workflows.simple_mcp_workflow import SimpleMCPWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin( + model_params=ModelActivityParameters( + start_to_close_timeout=timedelta(seconds=60) + ) + ), + ], + ) + + worker = Worker( + client, + task_queue="openai-agents-hosted-mcp-task-queue", + workflows=[ + SimpleMCPWorkflow, + ApprovalMCPWorkflow, + ], + activities=[ + # No custom activities needed for these workflows + ], + ) + await worker.run() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/hosted_mcp/workflows/approval_mcp_workflow.py b/openai_agents/hosted_mcp/workflows/approval_mcp_workflow.py new file mode 100644 index 000000000..1b5b7b6f9 --- /dev/null +++ b/openai_agents/hosted_mcp/workflows/approval_mcp_workflow.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from agents import ( + Agent, + HostedMCPTool, + MCPToolApprovalFunctionResult, + MCPToolApprovalRequest, + Runner, +) +from temporalio import workflow + + +def approval_callback(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult: + """Simple approval callback that logs the request and approves by default. + + In a real application, user input would be provided through a UI or API. + The approval callback executes within the Temporal workflow, so the application + can use signals or updates to receive user input. + """ + workflow.logger.info(f"MCP tool approval requested for: {request.data.name}") + + result: MCPToolApprovalFunctionResult = {"approve": True} + return result + + +@workflow.defn +class ApprovalMCPWorkflow: + @workflow.run + async def run( + self, question: str, server_url: str = "https://gitmcp.io/openai/codex" + ) -> str: + agent = Agent( + name="Assistant", + tools=[ + HostedMCPTool( + tool_config={ + "type": "mcp", + "server_label": "gitmcp", + "server_url": server_url, + "require_approval": "always", + }, + on_approval_request=approval_callback, + ) + ], + ) + + result = await Runner.run(agent, question) + return result.final_output diff --git a/openai_agents/hosted_mcp/workflows/simple_mcp_workflow.py b/openai_agents/hosted_mcp/workflows/simple_mcp_workflow.py new file mode 100644 index 000000000..2fac64bc5 --- /dev/null +++ b/openai_agents/hosted_mcp/workflows/simple_mcp_workflow.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from agents import Agent, HostedMCPTool, Runner +from temporalio import workflow + + +@workflow.defn +class SimpleMCPWorkflow: + @workflow.run + async def run( + self, question: str, server_url: str = "https://gitmcp.io/openai/codex" + ) -> str: + agent = Agent( + name="Assistant", + tools=[ + HostedMCPTool( + tool_config={ + "type": "mcp", + "server_label": "gitmcp", + "server_url": server_url, + "require_approval": "never", + } + ) + ], + ) + + result = await Runner.run(agent, question) + return result.final_output diff --git a/openai_agents/tools/README.md b/openai_agents/tools/README.md new file mode 100644 index 000000000..6f65e432d --- /dev/null +++ b/openai_agents/tools/README.md @@ -0,0 +1,61 @@ +# Tools Examples + +Demonstrations of various OpenAI agent tools integrated with Temporal workflows. + +*Adapted from [OpenAI Agents SDK tools examples](https://github.com/openai/openai-agents-python/tree/main/examples/tools)* + +Before running these examples, be sure to review the [prerequisites and background on the integration](../README.md). + +## Setup + +### Knowledge Base Setup (Required for File Search) +Create a vector store with sample documents for file search testing: +```bash +uv run openai_agents/tools/setup_knowledge_base.py +``` + +This script: +- Creates 6 sample documents +- Uploads files to OpenAI with proper cleanup using context managers +- Creates an assistant with vector store for file search capabilities +- Updates workflow files with the new vector store ID automatically + +## Running the Examples + +First, start the worker (supports all tools): +```bash +uv run openai_agents/tools/run_worker.py +``` + +Then run individual examples in separate terminals: + +### Code Interpreter +Execute Python code for mathematical calculations and data analysis: +```bash +uv run openai_agents/tools/run_code_interpreter_workflow.py +``` + +### File Search +Search through uploaded documents using vector similarity: +```bash +uv run openai_agents/tools/run_file_search_workflow.py +``` + +### Image Generation +Generate images: +```bash +uv run openai_agents/tools/run_image_generator_workflow.py +``` + +### Web Search +Search the web for current information with location context: +```bash +uv run openai_agents/tools/run_web_search_workflow.py +``` + + +## Omitted Examples + +The following tools from the [reference repository](https://github.com/openai/openai-agents-python/tree/main/examples/tools) are not included in this Temporal adaptation: + +- **Computer Use**: Complex browser automation not suitable for distributed systems implementation. \ No newline at end of file diff --git a/openai_agents/tools/run_code_interpreter_workflow.py b/openai_agents/tools/run_code_interpreter_workflow.py new file mode 100644 index 000000000..2b8197124 --- /dev/null +++ b/openai_agents/tools/run_code_interpreter_workflow.py @@ -0,0 +1,32 @@ +import asyncio + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.tools.workflows.code_interpreter_workflow import ( + CodeInterpreterWorkflow, +) + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + CodeInterpreterWorkflow.run, + "What is the square root of 273 * 312821 plus 1782?", + id="code-interpreter-workflow", + task_queue="openai-agents-tools-task-queue", + ) + + print(f"Result: {result}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/run_file_search_workflow.py b/openai_agents/tools/run_file_search_workflow.py new file mode 100644 index 000000000..09b8bb574 --- /dev/null +++ b/openai_agents/tools/run_file_search_workflow.py @@ -0,0 +1,33 @@ +import asyncio + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.tools.workflows.file_search_workflow import FileSearchWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + FileSearchWorkflow.run, + args=[ + "Be concise, and tell me 1 sentence about Arrakis I might not know.", + "vs_68855c27140c8191849b5f1887d8d335", # Vector store with Arrakis knowledge + ], + id="file-search-workflow", + task_queue="openai-agents-tools-task-queue", + ) + + print(f"Result: {result}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/run_image_generator_workflow.py b/openai_agents/tools/run_image_generator_workflow.py new file mode 100644 index 000000000..77a60d267 --- /dev/null +++ b/openai_agents/tools/run_image_generator_workflow.py @@ -0,0 +1,60 @@ +import asyncio +import base64 +import os +import subprocess +import sys +import tempfile + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.tools.workflows.image_generator_workflow import ( + ImageGeneratorWorkflow, +) + + +def open_file(path: str) -> None: + if sys.platform.startswith("darwin"): + subprocess.run(["open", path], check=False) # macOS + elif os.name == "nt": # Windows + os.startfile(path) # type: ignore + elif os.name == "posix": + subprocess.run(["xdg-open", path], check=False) # Linux/Unix + else: + print(f"Don't know how to open files on this platform: {sys.platform}") + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + ImageGeneratorWorkflow.run, + "Create an image of a frog eating a pizza, comic book style.", + id="image-generator-workflow", + task_queue="openai-agents-tools-task-queue", + ) + + print(f"Text result: {result.final_output}") + + if result.image_data: + # Save and open the image + with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: + tmp.write(base64.b64decode(result.image_data)) + temp_path = tmp.name + + print(f"Image saved to: {temp_path}") + # Open the image + open_file(temp_path) + else: + print("No image data found in result") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/run_web_search_workflow.py b/openai_agents/tools/run_web_search_workflow.py new file mode 100644 index 000000000..dd7f992f0 --- /dev/null +++ b/openai_agents/tools/run_web_search_workflow.py @@ -0,0 +1,33 @@ +import asyncio + +from temporalio.client import Client +from temporalio.contrib.openai_agents import OpenAIAgentsPlugin + +from openai_agents.tools.workflows.web_search_workflow import WebSearchWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin(), + ], + ) + + # Execute a workflow + result = await client.execute_workflow( + WebSearchWorkflow.run, + args=[ + "search the web for 'local sports news' and give me 1 interesting update in a sentence.", + "New York", + ], + id="web-search-workflow", + task_queue="openai-agents-tools-task-queue", + ) + + print(f"Result: {result}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/run_worker.py b/openai_agents/tools/run_worker.py new file mode 100644 index 000000000..a58df4706 --- /dev/null +++ b/openai_agents/tools/run_worker.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import asyncio +from datetime import timedelta + +from temporalio.client import Client +from temporalio.contrib.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin +from temporalio.worker import Worker + +from openai_agents.tools.workflows.code_interpreter_workflow import ( + CodeInterpreterWorkflow, +) +from openai_agents.tools.workflows.file_search_workflow import FileSearchWorkflow +from openai_agents.tools.workflows.image_generator_workflow import ( + ImageGeneratorWorkflow, +) +from openai_agents.tools.workflows.web_search_workflow import WebSearchWorkflow + + +async def main(): + # Create client connected to server at the given address + client = await Client.connect( + "localhost:7233", + plugins=[ + OpenAIAgentsPlugin( + model_params=ModelActivityParameters( + start_to_close_timeout=timedelta(seconds=60) + ) + ), + ], + ) + + worker = Worker( + client, + task_queue="openai-agents-tools-task-queue", + workflows=[ + CodeInterpreterWorkflow, + FileSearchWorkflow, + ImageGeneratorWorkflow, + WebSearchWorkflow, + ], + activities=[ + # No custom activities needed for these workflows + ], + ) + await worker.run() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/setup_knowledge_base.py b/openai_agents/tools/setup_knowledge_base.py new file mode 100644 index 000000000..fc467805e --- /dev/null +++ b/openai_agents/tools/setup_knowledge_base.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +""" +Setup script to create vector store with sample documents for testing FileSearchWorkflow. +Creates documents about Arrakis/Dune and uploads them to OpenAI for file search testing. +""" + +import asyncio +import os +import tempfile +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Dict, List + +from openai import AsyncOpenAI + +# Sample knowledge base content +KNOWLEDGE_BASE = { + "arrakis_overview": """ +Arrakis: The Desert Planet + +Arrakis, also known as Dune, is the third planet of the Canopus system. This harsh desert world is the sole source of the spice melange, the most valuable substance in the known universe. + +Key characteristics: +- Single biome: Desert covering the entire planet +- No natural precipitation +- Extreme temperature variations between day and night +- Home to the giant sandworms (Shai-Hulud) +- Indigenous population: the Fremen + +The planet's ecology is entirely dependent on the sandworms, which produce the spice as a byproduct of their life cycle. Water is incredibly scarce, leading to the development of stillsuits and other water conservation technologies. +""", + "spice_melange": """ +The Spice Melange + +Melange, commonly known as "the spice," is the most important substance in the Dune universe. This geriatric spice extends life, expands consciousness, and is essential for space navigation. + +Properties of Spice: +- Extends human lifespan significantly +- Enhances mental abilities and prescient vision +- Required for Guild Navigators to fold space +- Highly addictive with fatal withdrawal symptoms +- Turns eyes blue over time (the "Eyes of Ibad") + +Production: +The spice is created through the interaction of sandworms with pre-spice masses in the deep desert. The presence of water is toxic to sandworms, making Arrakis the only known source of spice in the universe. + +Economic Impact: +Control of spice production grants immense political and economic power, making Arrakis the most strategically important planet in the Imperium. +""", + "sandworms": """ +Sandworms of Arrakis + +The sandworms, known to the Fremen as Shai-Hulud ("Old Man of the Desert"), are colossal creatures that dominate Arrakis. These massive beings can grow to lengths of over 400 meters and live for thousands of years. + +Characteristics: +- Enormous size: up to 400+ meters in length +- Extreme sensitivity to water and moisture +- Produce the spice melange as part of their life cycle +- Territorial and attracted to rhythmic vibrations +- Crystalline teeth capable of crushing rock and metal + +Life Cycle: +Sandworms begin as sandtrout, small creatures that sequester water. They eventually metamorphose into the giant sandworms through a complex process involving spice production. + +Cultural Significance: +The Fremen worship sandworms as semi-divine beings and have developed elaborate rituals around them, including the dangerous practice of sandworm riding. +""", + "fremen_culture": """ +The Fremen of Arrakis + +The Fremen are the indigenous people of Arrakis, perfectly adapted to life in the harsh desert environment. Their culture revolves around water conservation, survival, and reverence for the sandworms. + +Cultural Practices: +- Water discipline: Every drop of moisture is preserved +- Stillsuits: Advanced technology to recycle body moisture +- Desert survival skills passed down through generations +- Ritualistic relationship with sandworms +- Sietch communities: Hidden underground settlements + +Religious Beliefs: +The Fremen follow a syncretic religion combining elements of Islam, Buddhism, and Christianity, adapted to their desert environment. They believe in prophecies of a messiah who will transform Arrakis. + +Military Prowess: +Despite their seemingly primitive lifestyle, the Fremen are formidable warriors, using their intimate knowledge of the desert and unconventional tactics to great effect. +""", + "house_atreides": """ +House Atreides and Arrakis + +House Atreides, led by Duke Leto Atreides, was granted control of Arrakis by Emperor Shaddam IV in a political trap designed to destroy the noble house. This transition from House Harkonnen marked the beginning of the events in Dune. + +Key Figures: +- Duke Leto Atreides: Noble leader focused on honor and justice +- Lady Jessica: Bene Gesserit concubine and mother of Paul +- Paul Atreides: Heir to the duchy and potential Kwisatz Haderach +- Duncan Idaho: Loyal swordmaster and warrior +- Gurney Halleck: Weapons master and troubadour + +The Atreides approach to ruling Arrakis differed dramatically from the Harkonnens, seeking to work with the Fremen rather than exploit them. This philosophy, while noble, ultimately led to their downfall when the Emperor and Harkonnens betrayed them. + +Legacy: +Though House Atreides was destroyed in the coup, Paul's survival and alliance with the Fremen would eventually lead to an even greater destiny. +""", + "ecology_arrakis": """ +The Ecology of Arrakis + +Arrakis presents a unique ecosystem entirely based on the water cycle created by sandworms and sandtrout. This closed ecological system has evolved over millennia to support life in extreme desert conditions. + +Water Cycle: +- Sandtrout sequester all available water deep underground +- This creates the desert conditions necessary for spice production +- Adult sandworms are killed by water, maintaining the cycle +- Plants and animals have evolved extreme water conservation + +Flora and Fauna: +- Desert plants with deep root systems and water storage +- Small desert animals adapted to minimal water consumption +- No large surface water bodies exist naturally +- All life forms show evolutionary adaptation to water scarcity + +The ecosystem is incredibly fragile - any significant introduction of water could disrupt the entire balance and potentially eliminate spice production, fundamentally changing the planet and the universe's economy. +""", +} + + +@asynccontextmanager +async def temporary_files(content_dict: Dict[str, str]): + """Context manager to create and cleanup temporary files.""" + temp_files = [] + try: + for name, content in content_dict.items(): + temp_file = tempfile.NamedTemporaryFile( + mode="w", suffix=".txt", prefix=f"{name}_", delete=False + ) + temp_file.write(content) + temp_file.close() + temp_files.append((name, temp_file.name)) + + yield temp_files + finally: + for _, temp_path in temp_files: + try: + os.unlink(temp_path) + except OSError: + pass + + +async def upload_files_to_openai(temp_files: List[tuple[str, str]]) -> List[str]: + """Upload temporary files to OpenAI and return file IDs.""" + client = AsyncOpenAI() + file_ids = [] + + for name, temp_path in temp_files: + try: + with open(temp_path, "rb") as f: + file_obj = await client.files.create(file=f, purpose="assistants") + file_ids.append(file_obj.id) + print(f"Uploaded {name}: {file_obj.id}") + except Exception as e: + print(f"Error uploading {name}: {e}") + + return file_ids + + +async def create_vector_store_with_assistant(file_ids: List[str]) -> str: + """Create an assistant with vector store containing the uploaded files.""" + client = AsyncOpenAI() + + try: + assistant = await client.beta.assistants.create( + name="Arrakis Knowledge Assistant", + instructions="You are an expert on Arrakis and the Dune universe. Use the uploaded files to answer questions about the desert planet, spice, sandworms, Fremen culture, and related topics.", + model="gpt-4o", + tools=[{"type": "file_search"}], + tool_resources={ + "file_search": { + "vector_stores": [ + { + "file_ids": file_ids, + "metadata": {"name": "Arrakis Knowledge Base"}, + } + ] + } + }, + ) + + # Extract vector store ID from assistant + if assistant.tool_resources and assistant.tool_resources.file_search: + vector_store_ids = assistant.tool_resources.file_search.vector_store_ids + if vector_store_ids: + return vector_store_ids[0] + + raise Exception("No vector store ID found in assistant response") + + except Exception as e: + print(f"Error creating assistant: {e}") + raise + + +def update_workflow_files(vector_store_id: str): + """Update workflow files with the new vector store ID.""" + import re + + files_to_update = ["run_file_search_workflow.py"] + + # Pattern to match any vector store ID with the specific comment + pattern = r'(vs_[a-f0-9]+)",\s*#\s*Vector store with Arrakis knowledge' + replacement = f'{vector_store_id}", # Vector store with Arrakis knowledge' + + for filename in files_to_update: + file_path = Path(__file__).parent / filename + if file_path.exists(): + try: + content = file_path.read_text() + if re.search(pattern, content): + updated_content = re.sub(pattern, replacement, content) + file_path.write_text(updated_content) + print(f"Updated {filename} with vector store ID") + else: + print(f"No matching pattern found in {filename}") + except Exception as e: + print(f"Error updating {filename}: {e}") + + +async def main(): + """Main function to set up the knowledge base.""" + # Check for API key + if not os.getenv("OPENAI_API_KEY"): + print("Error: OPENAI_API_KEY environment variable not set") + print("Please set your OpenAI API key:") + print("export OPENAI_API_KEY='your-api-key-here'") + return + + print("Setting up Arrakis knowledge base...") + + try: + # Create temporary files and upload them + async with temporary_files(KNOWLEDGE_BASE) as temp_files: + print(f"Created {len(temp_files)} temporary files") + + file_ids = await upload_files_to_openai(temp_files) + + if not file_ids: + print("Error: No files were successfully uploaded") + return + + print(f"Successfully uploaded {len(file_ids)} files") + + # Create vector store via assistant + vector_store_id = await create_vector_store_with_assistant(file_ids) + + print(f"Created vector store: {vector_store_id}") + + # Update workflow files + update_workflow_files(vector_store_id) + + print() + print("=" * 60) + print("KNOWLEDGE BASE SETUP COMPLETE") + print("=" * 60) + print(f"Vector Store ID: {vector_store_id}") + print(f"Files indexed: {len(file_ids)}") + print("Content: Arrakis/Dune universe knowledge") + print("=" * 60) + + except Exception as e: + print(f"Setup failed: {e}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/openai_agents/tools/workflows/code_interpreter_workflow.py b/openai_agents/tools/workflows/code_interpreter_workflow.py new file mode 100644 index 000000000..6715bc505 --- /dev/null +++ b/openai_agents/tools/workflows/code_interpreter_workflow.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from agents import Agent, CodeInterpreterTool, Runner +from temporalio import workflow + + +@workflow.defn +class CodeInterpreterWorkflow: + @workflow.run + async def run(self, question: str) -> str: + agent = Agent( + name="Code interpreter", + instructions="You love doing math.", + tools=[ + CodeInterpreterTool( + tool_config={ + "type": "code_interpreter", + "container": {"type": "auto"}, + }, + ) + ], + ) + + result = await Runner.run(agent, question) + return result.final_output diff --git a/openai_agents/tools/workflows/file_search_workflow.py b/openai_agents/tools/workflows/file_search_workflow.py new file mode 100644 index 000000000..915dcec42 --- /dev/null +++ b/openai_agents/tools/workflows/file_search_workflow.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from agents import Agent, FileSearchTool, Runner +from temporalio import workflow + + +@workflow.defn +class FileSearchWorkflow: + @workflow.run + async def run(self, question: str, vector_store_id: str) -> str: + agent = Agent( + name="File searcher", + instructions="You are a helpful agent.", + tools=[ + FileSearchTool( + max_num_results=3, + vector_store_ids=[vector_store_id], + include_search_results=True, + ) + ], + ) + + result = await Runner.run(agent, question) + return result.final_output diff --git a/openai_agents/tools/workflows/image_generator_workflow.py b/openai_agents/tools/workflows/image_generator_workflow.py new file mode 100644 index 000000000..7c58091b1 --- /dev/null +++ b/openai_agents/tools/workflows/image_generator_workflow.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +from agents import Agent, ImageGenerationTool, Runner +from temporalio import workflow + + +@dataclass +class ImageGenerationResult: + final_output: str + image_data: Optional[str] = None + + +@workflow.defn +class ImageGeneratorWorkflow: + @workflow.run + async def run(self, prompt: str) -> ImageGenerationResult: + agent = Agent( + name="Image generator", + instructions="You are a helpful agent.", + tools=[ + ImageGenerationTool( + tool_config={"type": "image_generation", "quality": "low"}, + ) + ], + ) + + result = await Runner.run(agent, prompt) + + # Extract image data if available + image_data = None + for item in result.new_items: + if ( + item.type == "tool_call_item" + and item.raw_item.type == "image_generation_call" + and (img_result := item.raw_item.result) + ): + image_data = img_result + break + + return ImageGenerationResult( + final_output=result.final_output, image_data=image_data + ) diff --git a/openai_agents/tools/workflows/web_search_workflow.py b/openai_agents/tools/workflows/web_search_workflow.py new file mode 100644 index 000000000..8b505ac14 --- /dev/null +++ b/openai_agents/tools/workflows/web_search_workflow.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from agents import Agent, Runner, WebSearchTool +from temporalio import workflow + + +@workflow.defn +class WebSearchWorkflow: + @workflow.run + async def run(self, question: str, user_city: str = "New York") -> str: + agent = Agent( + name="Web searcher", + instructions="You are a helpful agent.", + tools=[ + WebSearchTool(user_location={"type": "approximate", "city": user_city}) + ], + ) + + result = await Runner.run(agent, question) + return result.final_output