|
| 1 | +import asyncio |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +from agents import Agent, Runner, gen_trace_id, trace |
| 5 | + |
| 6 | +# This tool is still in experimental phase and the details could be changed until being GAed. |
| 7 | +from agents.extensions.experimental.codex import ( |
| 8 | + CodexToolStreamEvent, |
| 9 | + CommandExecutionItem, |
| 10 | + ErrorItem, |
| 11 | + FileChangeItem, |
| 12 | + ItemCompletedEvent, |
| 13 | + ItemStartedEvent, |
| 14 | + ItemUpdatedEvent, |
| 15 | + McpToolCallItem, |
| 16 | + ReasoningItem, |
| 17 | + ThreadErrorEvent, |
| 18 | + ThreadOptions, |
| 19 | + ThreadStartedEvent, |
| 20 | + TodoListItem, |
| 21 | + TurnCompletedEvent, |
| 22 | + TurnFailedEvent, |
| 23 | + TurnOptions, |
| 24 | + TurnStartedEvent, |
| 25 | + WebSearchItem, |
| 26 | + codex_tool, |
| 27 | +) |
| 28 | + |
| 29 | +# This example runs the Codex CLI via the Codex tool wrapper. |
| 30 | +# You can configure the CLI path with CODEX_PATH or CodexOptions(codex_path_override="..."). |
| 31 | +# codex_tool accepts options as keyword arguments or a plain dict. |
| 32 | +# For example: codex_tool(sandbox_mode="read-only") or codex_tool({"sandbox_mode": "read-only"}). |
| 33 | +# The prompt below asks Codex to use the $openai-knowledge skill (Docs MCP) for API lookups. |
| 34 | + |
| 35 | + |
| 36 | +async def on_codex_stream(payload: CodexToolStreamEvent) -> None: |
| 37 | + event = payload.event |
| 38 | + |
| 39 | + if isinstance(event, ThreadStartedEvent): |
| 40 | + log(f"codex thread started: {event.thread_id}") |
| 41 | + return |
| 42 | + if isinstance(event, TurnStartedEvent): |
| 43 | + log("codex turn started") |
| 44 | + return |
| 45 | + if isinstance(event, TurnCompletedEvent): |
| 46 | + usage = event.usage |
| 47 | + log(f"codex turn completed, usage: {usage}") |
| 48 | + return |
| 49 | + if isinstance(event, TurnFailedEvent): |
| 50 | + error = event.error.message |
| 51 | + log(f"codex turn failed: {error}") |
| 52 | + return |
| 53 | + if isinstance(event, ThreadErrorEvent): |
| 54 | + log(f"codex stream error: {event.message}") |
| 55 | + return |
| 56 | + |
| 57 | + if not isinstance(event, (ItemStartedEvent, ItemUpdatedEvent, ItemCompletedEvent)): |
| 58 | + return |
| 59 | + |
| 60 | + item = event.item |
| 61 | + |
| 62 | + if isinstance(item, ReasoningItem): |
| 63 | + text = item.text |
| 64 | + log(f"codex reasoning ({event.type}): {text}") |
| 65 | + return |
| 66 | + if isinstance(item, CommandExecutionItem): |
| 67 | + command = item.command |
| 68 | + output = item.aggregated_output |
| 69 | + output_preview = output[-200:] if isinstance(output, str) else "" |
| 70 | + status = item.status |
| 71 | + log(f"codex command {event.type}: {command} | status={status} | output={output_preview}") |
| 72 | + return |
| 73 | + if isinstance(item, McpToolCallItem): |
| 74 | + server = item.server |
| 75 | + tool = item.tool |
| 76 | + status = item.status |
| 77 | + log(f"codex mcp {event.type}: {server}.{tool} | status={status}") |
| 78 | + return |
| 79 | + if isinstance(item, FileChangeItem): |
| 80 | + changes = item.changes |
| 81 | + status = item.status |
| 82 | + log(f"codex file change {event.type}: {status} | {changes}") |
| 83 | + return |
| 84 | + if isinstance(item, WebSearchItem): |
| 85 | + log(f"codex web search {event.type}: {item.query}") |
| 86 | + return |
| 87 | + if isinstance(item, TodoListItem): |
| 88 | + items = item.items |
| 89 | + log(f"codex todo list {event.type}: {len(items)} items") |
| 90 | + return |
| 91 | + if isinstance(item, ErrorItem): |
| 92 | + log(f"codex error {event.type}: {item.message}") |
| 93 | + |
| 94 | + |
| 95 | +def _timestamp() -> str: |
| 96 | + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 97 | + |
| 98 | + |
| 99 | +def log(message: str) -> None: |
| 100 | + timestamp = _timestamp() |
| 101 | + lines = str(message).splitlines() or [""] |
| 102 | + for line in lines: |
| 103 | + print(f"{timestamp} {line}") |
| 104 | + |
| 105 | + |
| 106 | +async def main() -> None: |
| 107 | + agent = Agent( |
| 108 | + name="Codex Agent", |
| 109 | + instructions=( |
| 110 | + "Use the codex tool to inspect the workspace and answer the question. " |
| 111 | + "When skill names, which usually starts with `$`, are mentioned, " |
| 112 | + "you must rely on the codex tool to use the skill and answer the question.\n\n" |
| 113 | + "When you send the final answer, you must include the following info at the end:\n\n" |
| 114 | + "Run `codex resume <thread_id>` to continue the codex session." |
| 115 | + ), |
| 116 | + tools=[ |
| 117 | + # Run local Codex CLI as a sub process |
| 118 | + codex_tool( |
| 119 | + sandbox_mode="workspace-write", |
| 120 | + default_thread_options=ThreadOptions( |
| 121 | + # You can pass a Codex instance to customize CLI details |
| 122 | + # codex=Codex(executable_path="/path/to/codex", base_url="..."), |
| 123 | + model="gpt-5.2-codex", |
| 124 | + model_reasoning_effort="low", |
| 125 | + network_access_enabled=True, |
| 126 | + web_search_enabled=False, |
| 127 | + approval_policy="never", # We'll update this example once the HITL is implemented |
| 128 | + ), |
| 129 | + default_turn_options=TurnOptions( |
| 130 | + # Abort Codex CLI if no events arrive within this many seconds. |
| 131 | + idle_timeout_seconds=60, |
| 132 | + ), |
| 133 | + on_stream=on_codex_stream, |
| 134 | + ) |
| 135 | + ], |
| 136 | + ) |
| 137 | + trace_id = gen_trace_id() |
| 138 | + log(f"View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}") |
| 139 | + |
| 140 | + with trace("Codex tool example", trace_id=trace_id): |
| 141 | + # Use a skill that requires network access and MCP server settings |
| 142 | + log("Using $openai-knowledge skill to fetch the latest realtime model name...") |
| 143 | + result = await Runner.run( |
| 144 | + agent, |
| 145 | + "You must use `$openai-knowledge` skill to fetch the latest realtime model name.", |
| 146 | + ) |
| 147 | + log(result.final_output) |
| 148 | + # The latest realtime model name, according to the $openai-knowledge skill, is gpt-realtime. |
| 149 | + |
| 150 | + # Use a skill that runs local command and analyzes the output |
| 151 | + log( |
| 152 | + "Using $test-coverage-improver skill to analyze the test coverage of the project and improve it..." |
| 153 | + ) |
| 154 | + result = await Runner.run( |
| 155 | + agent, |
| 156 | + "You must use `$test-coverage-improver` skill to analyze the test coverage of the project and improve it.", |
| 157 | + ) |
| 158 | + log(result.final_output) |
| 159 | + # (Aa few suggestions for improving the test coverage will be displayed.) |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + asyncio.run(main()) |
0 commit comments