Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions native/codex/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use crate::{Input, Output, state::ConversationState};
#[derive(Deserialize)]
struct OpenParams {
model: String,
base_instructions: Option<String>,
instructions: Option<String>,
reasoning_effort: Option<ReasoningEffort>,
reasoning_summary: Option<ReasoningSummary>,
Expand Down Expand Up @@ -315,16 +316,23 @@ pub async fn open(
.models_manager_for_config(&config)
.get_model_info(&params.model, &config.to_models_manager_config())
.await;
let mut prompt = codex_prompts::render_model_instructions(&model_info);
let custom = params.base_instructions.is_some() || params.instructions.is_some();
let mut prompt = params
.base_instructions
.unwrap_or_else(|| codex_prompts::render_model_instructions(&model_info));
if let Some(instructions) = params.instructions {
prompt.push_str("\n\n");
if !prompt.is_empty() {
prompt.push_str("\n\n");
}
prompt.push_str(&instructions);
config.base_instructions_provenance = Some(BaseInstructionsProvenance::Custom);
}
config.base_instructions_provenance = Some(if custom {
BaseInstructionsProvenance::Custom
} else {
config.base_instructions_provenance = Some(BaseInstructionsProvenance::Model {
BaseInstructionsProvenance::Model {
model: model_info.slug.clone(),
});
}
}
});
config.base_instructions = Some(prompt);
let tool_policy = selection
.is_none()
Expand Down
60 changes: 60 additions & 0 deletions native/codex/tests/test_model_controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,66 @@
from openai_agents.codex.testing import MockModel


def test_base_instructions_replace_the_stock_prompt_and_survive_resume(
mock_model: MockModel,
) -> None:
for _ in range(3):
mock_model.reply("OK.")

async def chat() -> None:
storage = InMemorySessionStorage()
agent = Agent(
model="fixture-model",
base_instructions="You are a travel planner.",
instructions="Use metric units.",
)
first = await agent.run("Plan a walk.", storage=storage, environment=None)
async with Session.resume(first.session_id, storage=storage) as session:
await session.run("Continue.")
await Agent(model=agent.model, instructions=agent.instructions).run(
"Continue.", storage=storage, session_id=first.session_id, environment=None
)

asyncio.run(asyncio.wait_for(chat(), timeout=30))
first, resumed, default = mock_model.requests
stock_prefix = "You are a coding agent running in the Codex CLI"
for request in (first, resumed):
message = request["input"][0]
assert message["role"] == "developer"
assert message["content"] == [
{"type": "input_text", "text": "You are a travel planner.\n\nUse metric units."}
]
assert stock_prefix not in json.dumps(request)
message = default["input"][0]
assert message["role"] == "developer"
assert message["content"][0]["text"].startswith(stock_prefix)
assert message["content"][0]["text"].endswith("\n\nUse metric units.")
assert "You are a travel planner." not in json.dumps(default)


@pytest.mark.parametrize(
("base", "instructions", "expected"),
[
("You are a travel planner.", None, "You are a travel planner."),
("", "Use metric units.", "Use metric units."),
("", None, None),
],
ids=["base-only", "suffix-only", "no-base-or-suffix"],
)
def test_base_instructions_keep_separate_codex_context(
mock_model: MockModel, base: str, instructions: str | None, expected: str | None
) -> None:
mock_model.reply("OK.")
agent = Agent(model="fixture-model", base_instructions=base, instructions=instructions)
asyncio.run(asyncio.wait_for(agent.run("Plan a walk.", environment=None), timeout=20))
(request,) = mock_model.requests
assert "You are a coding agent running in the Codex CLI" not in json.dumps(request)
messages = [item for item in request["input"] if item.get("role") == "developer"]
if expected is not None:
assert messages.pop(0)["content"] == [{"type": "input_text", "text": expected}]
assert "<permissions instructions>" in json.dumps(messages)


def test_prompt_cache_identity_survives_turns_and_reopen(mock_model: MockModel) -> None:
for text in ("First.", "Second.", "Third.", "Fourth.", "Left.", "Right."):
mock_model.reply(text)
Expand Down
10 changes: 9 additions & 1 deletion src/openai_agents/codex/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Agent:
"""A human-readable name for the agent."""

instructions: str | None = None
"""Instructions to append to Codex's base instructions."""
"""Instructions to append to the default or custom base instructions."""

tools: list[Tool] = field(default_factory=list)
"""Tools to make available alongside the harness's default tools."""
Expand All @@ -61,6 +61,14 @@ class Agent:
subagents: bool | None = None
"""Set True to enable Codex collaboration, False to disable it, or use the model default."""

base_instructions: str | None = None
"""Optional replacement for Codex's model-specific prompt, before ``instructions``.

``None`` for the stock prompt, ``""`` for no base prompt.
No effect on separate Codex context (such as permissions and skills)
or on earlier prompts retained in conversation history.
"""

def as_tool(
self,
tool_name: str,
Expand Down
1 change: 1 addition & 0 deletions src/openai_agents/codex/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,7 @@ def _prepare_session(
"guardian": agent.guardian,
"subagents": agent.subagents,
"model": agent.model,
"base_instructions": agent.base_instructions,
"instructions": agent.instructions,
"reasoning_effort": agent.reasoning.effort if agent.reasoning else None,
"reasoning_summary": agent.reasoning.summary if agent.reasoning else None,
Expand Down
Loading