|
| 1 | +"""Example: Using FileEditor tool with GPT-5.1 models via direct OpenAI API. |
| 2 | +
|
| 3 | +This mirrors the ApplyPatch example but uses FileEditor to create/modify/delete |
| 4 | +FACTS.txt. Useful for comparing Responses input/output behavior and logs. |
| 5 | +
|
| 6 | +Requirements: |
| 7 | +- OPENAI_API_KEY in the environment (or LLM_API_KEY) |
| 8 | +- Model: any openai/gpt-5.1* variant; default uses openai/gpt-5.1-codex-mini |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import os |
| 14 | + |
| 15 | +from pydantic import SecretStr |
| 16 | + |
| 17 | +from openhands.sdk import LLM, Agent, Conversation, get_logger |
| 18 | +from openhands.sdk.tool import Tool |
| 19 | +from openhands.tools.file_editor import FileEditorTool |
| 20 | +from openhands.tools.task_tracker import TaskTrackerTool |
| 21 | +from openhands.tools.terminal import TerminalTool |
| 22 | + |
| 23 | + |
| 24 | +logger = get_logger(__name__) |
| 25 | + |
| 26 | +api_key = os.getenv("OPENAI_API_KEY") or os.getenv("LLM_API_KEY") |
| 27 | +assert api_key, "Set OPENAI_API_KEY (or LLM_API_KEY) in your environment." |
| 28 | + |
| 29 | +model = os.getenv("LLM_MODEL", "openai/gpt-5.1-codex-mini") |
| 30 | +assert model.startswith("openai/gpt-5.1"), "Model must be an openai gpt-5.1 variant" |
| 31 | + |
| 32 | +llm = LLM( |
| 33 | + model=model, |
| 34 | + api_key=SecretStr(api_key), |
| 35 | + native_tool_calling=True, |
| 36 | + reasoning_summary=None, |
| 37 | + log_completions=True, |
| 38 | +) |
| 39 | + |
| 40 | +# Ensure registration |
| 41 | +_ = (TerminalTool, TaskTrackerTool, FileEditorTool) |
| 42 | + |
| 43 | +agent = Agent( |
| 44 | + llm=llm, |
| 45 | + tools=[Tool(name="terminal"), Tool(name="task_tracker"), Tool(name="file_editor")], |
| 46 | + system_prompt_kwargs={"cli_mode": True}, |
| 47 | +) |
| 48 | + |
| 49 | +conversation = Conversation(agent=agent, workspace=os.getcwd()) |
| 50 | + |
| 51 | +prompt = ( |
| 52 | + "You must use tools to perform all actions. Do not merely describe actions. " |
| 53 | + "Use the FileEditor tool to: " |
| 54 | + "1) create a FACTS.txt with a single line 'OpenHands SDK integrates tools.'; " |
| 55 | + "2) modify FACTS.txt by appending a second line 'FileEditor works.'; " |
| 56 | + "3) delete FACTS.txt using the terminal tool with: rm FACTS.txt." |
| 57 | +) |
| 58 | + |
| 59 | +conversation.send_message(prompt) |
| 60 | +conversation.run() |
| 61 | + |
| 62 | +print("Conversation finished.") |
| 63 | +print(f"EXAMPLE_COST: {llm.metrics.accumulated_cost}") |
0 commit comments