Support view_image inputs in imagegen edits

This commit is contained in:
Aaron Friel
2026-06-02 05:12:05 +00:00
committed by Friel
parent cb63ee7f5d
commit 7d6e7c71ca
4 changed files with 116 additions and 44 deletions
@@ -1,11 +1,12 @@
The `image_gen.imagegen` tool enables image generation from descriptions and editing of existing images based on specific instructions. Use it when:
- The user requests an image based on a scene description, such as a diagram, portrait, comic, meme, or any other visual.
- The user wants to modify an attached or previously generated image with specific changes, including adding or removing elements, altering colors, improving quality/resolution, or transforming the style (e.g., cartoon, oil painting).
- The user wants to modify an attached image, an image loaded with `view_image`, or a previously generated image with specific changes, including adding or removing elements, altering colors, improving quality/resolution, or transforming the style (e.g., cartoon, oil painting).
Guidelines:
- Set `action` to `generate` when the user asks for a brand new image.
- Set `action` to `edit` when the user asks to modify an existing image from the conversation history.
- For edits, eligible image inputs are attached user images, images loaded with `view_image`, and previously generated images. The tool uses at most five images: latest attached user images plus later eligible image outputs. If more than five are available, older later outputs are dropped first while preserving the newest later output when possible, then older attached user images are dropped if needed.
- Directly generate the image without reconfirmation or clarification.
- After each image generation, do not mention anything related to download. Do not summarize the image. Do not ask followup question. Do not say ANYTHING after you generate an image.
- Always use this tool for image editing unless the user explicitly requests otherwise. Do not use the `python` tool for image editing unless specifically instructed.
+76 -9
View File
@@ -13,6 +13,7 @@ use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::VIEW_IMAGE_TOOL_NAME;
use codex_tools::ResponsesApiNamespaceTool;
use pretty_assertions::assert_eq;
@@ -207,6 +208,58 @@ fn edit_reuses_images_from_prior_standalone_imagegen_calls() {
);
}
#[test]
fn edit_reuses_images_from_view_image_calls() {
let history = vec![
ResponseItem::FunctionCall {
id: None,
name: VIEW_IMAGE_TOOL_NAME.to_string(),
namespace: None,
arguments: "{}".to_string(),
call_id: "view-image-1".to_string(),
},
image_function_output("view-image-1", "viewed"),
];
assert_eq!(
edit_request("change the lighting", &history),
expected_edit_request("change the lighting", &["data:image/png;base64,viewed"])
);
}
#[test]
fn edit_keeps_newest_view_image_outputs_when_over_limit() {
let history = (1..=6)
.flat_map(|index| {
let call_id = format!("view-image-{index}");
vec![
ResponseItem::FunctionCall {
id: None,
name: VIEW_IMAGE_TOOL_NAME.to_string(),
namespace: None,
arguments: "{}".to_string(),
call_id: call_id.clone(),
},
image_function_output(&call_id, &index.to_string()),
]
})
.collect::<Vec<_>>();
assert_eq!(
edit_request("change the lighting", &history),
expected_edit_request(
"change the lighting",
&[
"data:image/png;base64,2",
"data:image/png;base64,3",
"data:image/png;base64,4",
"data:image/png;base64,5",
"data:image/png;base64,6",
]
)
);
}
#[test]
fn edit_keeps_newest_standalone_generated_images_when_over_limit() {
let history = (1..=6)
@@ -295,18 +348,32 @@ fn generated_item(result: &str) -> ResponseItem {
}
fn generated_function_output(call_id: &str, result: &str) -> ResponseItem {
image_function_output_with_text(call_id, result, Some("generated image save hint"))
}
fn image_function_output(call_id: &str, result: &str) -> ResponseItem {
image_function_output_with_text(call_id, result, /*text*/ None)
}
fn image_function_output_with_text(
call_id: &str,
result: &str,
text: Option<&str>,
) -> ResponseItem {
let mut body = vec![FunctionCallOutputContentItem::InputImage {
image_url: format!("data:image/png;base64,{result}"),
detail: Some(DEFAULT_IMAGE_DETAIL),
}];
if let Some(text) = text {
body.push(FunctionCallOutputContentItem::InputText {
text: text.to_string(),
});
}
ResponseItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::ContentItems(vec![
FunctionCallOutputContentItem::InputImage {
image_url: format!("data:image/png;base64,{result}"),
detail: Some(DEFAULT_IMAGE_DETAIL),
},
FunctionCallOutputContentItem::InputText {
text: "generated image save hint".to_string(),
},
]),
body: FunctionCallOutputBody::ContentItems(body),
success: Some(true),
},
}
+18 -16
View File
@@ -18,6 +18,7 @@ use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::VIEW_IMAGE_TOOL_NAME;
use codex_tools::ResponsesApiNamespace;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ResponsesApiTool;
@@ -148,7 +149,7 @@ fn request_for_action(
}
}
/// Selects edit context using the hosted imagegen anchor and truncation behavior.
/// Selects edit context using the latest user image anchor and truncation behavior.
fn edit_images(history: &[ResponseItem]) -> Vec<ImageUrl> {
let latest_uploaded_images = history.iter().enumerate().rev().find_map(|(index, item)| {
let ResponseItem::Message { role, content, .. } = item else {
@@ -170,11 +171,11 @@ fn edit_images(history: &[ResponseItem]) -> Vec<ImageUrl> {
});
let (user_images, follow_up_start) = latest_uploaded_images
.map_or_else(|| (Vec::new(), 0), |(index, images)| (images, index + 1));
let mut generated_images = Vec::new();
let mut follow_up_images = Vec::new();
for item in &history[follow_up_start..] {
match item {
ResponseItem::ImageGenerationCall { result, .. } if !result.is_empty() => {
generated_images.push(ImageUrl {
follow_up_images.push(ImageUrl {
image_url: format!("data:image/png;base64,{result}"),
});
}
@@ -184,16 +185,17 @@ fn edit_images(history: &[ResponseItem]) -> Vec<ImageUrl> {
item,
ResponseItem::FunctionCall {
name,
namespace: Some(namespace),
namespace,
call_id: function_call_id,
..
} if function_call_id == call_id
&& name == IMAGEGEN_TOOL_NAME
&& namespace == IMAGE_GEN_NAMESPACE
&& ((name == IMAGEGEN_TOOL_NAME
&& namespace.as_deref() == Some(IMAGE_GEN_NAMESPACE))
|| (name == VIEW_IMAGE_TOOL_NAME && namespace.is_none()))
)
}) =>
{
generated_images.extend(output.content_items().into_iter().flatten().filter_map(
follow_up_images.extend(output.content_items().into_iter().flatten().filter_map(
|item| match item {
FunctionCallOutputContentItem::InputImage { image_url, .. } => {
Some(ImageUrl {
@@ -222,24 +224,24 @@ fn edit_images(history: &[ResponseItem]) -> Vec<ImageUrl> {
| ResponseItem::Other => {}
}
}
truncate_images(user_images, generated_images)
truncate_images(user_images, follow_up_images)
}
/// Truncates edit inputs while preserving the newest generated image when possible.
/// Truncates edit inputs while preserving the newest follow-up image when possible.
fn truncate_images(
mut user_images: Vec<ImageUrl>,
mut generated_images: Vec<ImageUrl>,
mut follow_up_images: Vec<ImageUrl>,
) -> Vec<ImageUrl> {
let mut excess = (user_images.len() + generated_images.len()).saturating_sub(MAX_EDIT_IMAGES);
let drop_generated = excess.min(generated_images.len().saturating_sub(1));
generated_images.drain(..drop_generated);
excess -= drop_generated;
let mut excess = (user_images.len() + follow_up_images.len()).saturating_sub(MAX_EDIT_IMAGES);
let drop_follow_up = excess.min(follow_up_images.len().saturating_sub(1));
follow_up_images.drain(..drop_follow_up);
excess -= drop_follow_up;
let drop_user = excess.min(user_images.len());
user_images.drain(..drop_user);
excess -= drop_user;
generated_images.drain(..excess);
follow_up_images.drain(..excess);
user_images.extend(generated_images);
user_images.extend(follow_up_images);
user_images
}
@@ -11,7 +11,7 @@ Generates or edits images for the current project (for example website assets, g
This skill has exactly two top-level modes:
- **Default built-in tool mode (preferred):** built-in `image_gen` tool for normal image generation, editing, and simple transparent-image requests. Does not require `OPENAI_API_KEY`.
- **Default built-in tool mode (preferred):** built-in `image_gen.imagegen` tool for normal image generation, editing, and simple transparent-image requests. Does not require `OPENAI_API_KEY`.
- **Fallback CLI mode:** `scripts/image_gen.py` CLI. Use when the user explicitly asks for the CLI/API/model path, or after the user explicitly confirms a true model-native transparency fallback with `gpt-image-1.5`. Requires `OPENAI_API_KEY`.
Within CLI fallback, the CLI exposes three subcommands:
@@ -21,10 +21,10 @@ Within CLI fallback, the CLI exposes three subcommands:
- `generate-batch`
Rules:
- Use the built-in `image_gen` tool by default for normal image generation and editing requests.
- Use the built-in `image_gen.imagegen` tool by default for normal image generation and editing requests.
- Do not switch to CLI fallback for ordinary quality, size, or file-path control.
- If the user explicitly asks for a transparent image/background, stay on built-in `image_gen` first: prompt for a flat removable chroma-key background, then remove it locally with the installed helper at `$CODEX_HOME/skills/.system/imagegen/scripts/remove_chroma_key.py`.
- Never silently switch from built-in `image_gen` or CLI `gpt-image-2` to CLI `gpt-image-1.5`. Treat this as a model/path downgrade and ask the user before doing it, unless the user has already explicitly requested `gpt-image-1.5`, `scripts/image_gen.py`, or CLI fallback.
- If the user explicitly asks for a transparent image/background, stay on built-in `image_gen.imagegen` first: prompt for a flat removable chroma-key background, then remove it locally with the installed helper at `$CODEX_HOME/skills/.system/imagegen/scripts/remove_chroma_key.py`.
- Never silently switch from built-in `image_gen.imagegen` or CLI `gpt-image-2` to CLI `gpt-image-1.5`. Treat this as a model/path downgrade and ask the user before doing it, unless the user has already explicitly requested `gpt-image-1.5`, `scripts/image_gen.py`, or CLI fallback.
- If a transparent request appears too complex for clean chroma-key removal, asks for true/native transparency, or local removal fails validation, explain that true transparency requires CLI `gpt-image-1.5 --background transparent --output-format png` because `gpt-image-2` does not support `background=transparent`, then ask whether to proceed. Run the CLI fallback only after the user confirms.
- The word `batch` by itself does not mean CLI fallback. If the user asks for many assets or says to batch-generate assets without explicitly asking for CLI/API/model controls, stay on the built-in path and issue one built-in call per requested asset or variant.
- If the built-in tool fails or is unavailable, tell the user the CLI fallback exists and that it requires `OPENAI_API_KEY`. Proceed only if the user explicitly asks for that fallback.
@@ -34,7 +34,7 @@ Rules:
Built-in save-path policy:
- In built-in tool mode, Codex saves generated images under `$CODEX_HOME/*` by default.
- Do not describe or rely on OS temp as the default built-in destination.
- Do not describe or rely on a destination-path argument (if any) on the built-in `image_gen` tool. If a specific location is needed, generate first and then move or copy the selected output from `$CODEX_HOME/generated_images/...`.
- Do not describe or rely on a destination-path argument on the built-in `image_gen.imagegen` tool. If a specific location is needed, generate first and then move or copy the selected output from `$CODEX_HOME/generated_images/...`.
- Save-path precedence in built-in mode:
1. If the user names a destination, move or copy the selected output there.
2. If the image is meant for the current project, move or copy the final selected image into the workspace before finishing.
@@ -78,14 +78,16 @@ Intent:
- If the user provides no images, treat the request as **generate**.
Built-in edit semantics:
- Built-in edit mode is for images already visible in the conversation context, such as attached images or images generated earlier in the thread.
- If the user wants to edit a local image file with the built-in tool, first load it with built-in `view_image` tool so the image is visible in the conversation context, then proceed with the built-in edit flow.
- Built-in edit mode is for eligible images in the conversation history: attached user images, local images loaded with `view_image`, and images generated earlier in the thread by built-in image generation.
- Built-in edits consume at most five images. Selection starts from the latest user message that contains attached images: keep those attached images, then add later eligible `view_image` or generated-image outputs. If there is no user message with attached images, use eligible `view_image` and generated-image outputs from the history.
- If more than five eligible images are available, older later outputs are dropped first while preserving the newest later output when possible; then older attached user images are dropped if needed.
- If the user wants to edit a local image file with the built-in tool, first load it with built-in `view_image` so the image becomes an eligible edit input, then proceed with the built-in edit flow.
- Do not promise arbitrary filesystem-path editing through the built-in tool.
- If a local file still needs direct file-path control, masks, or other explicit CLI-only parameters, use the explicit CLI fallback only when the user asks for it.
- For edits, preserve invariants aggressively and save non-destructively by default.
Execution strategy:
- In the built-in default path, produce many assets or variants by issuing one `image_gen` call per requested asset or variant.
- In the built-in default path, produce many assets or variants by issuing one `image_gen.imagegen` call per requested asset or variant.
- In the CLI fallback path, use the CLI `generate-batch` subcommand only when the user explicitly chose CLI mode and needs many prompts/assets.
- For many distinct assets, do not use `n` as a substitute for separate prompts. `n` is for variants of one prompt; distinct assets need distinct built-in calls or distinct CLI `generate-batch` jobs.
@@ -101,13 +103,13 @@ Assume the user wants a new image unless they clearly ask to change an existing
- reference image
- edit target
- supporting insert/style/compositing input
7. If the edit target is only on the local filesystem and you are staying on the built-in path, inspect it with `view_image` first so the image is available in conversation context.
8. If the user asked for a photo, illustration, sprite, product image, banner, or other explicitly raster-style asset, use `image_gen` rather than substituting SVG/HTML/CSS placeholders. If the request is for an icon, logo, or UI graphic that should match existing repo-native SVG/vector/code assets, prefer editing those directly instead.
7. If the edit target is only on the local filesystem and you are staying on the built-in path, inspect it with `view_image` first so the image is available as an eligible built-in edit input.
8. If the user asked for a photo, illustration, sprite, product image, banner, or other explicitly raster-style asset, use `image_gen.imagegen` rather than substituting SVG/HTML/CSS placeholders. If the request is for an icon, logo, or UI graphic that should match existing repo-native SVG/vector/code assets, prefer editing those directly instead.
9. Augment the prompt based on specificity:
- If the user's prompt is already specific and detailed, normalize it into a clear spec without adding creative requirements.
- If the user's prompt is generic, add tasteful augmentation only when it materially improves output quality.
10. Use the built-in `image_gen` tool by default.
11. For transparent-output requests, follow the transparent image guidance below: generate with built-in `image_gen` on a flat chroma-key background, copy the selected output into the workspace or `tmp/imagegen/`, run the installed `$CODEX_HOME/skills/.system/imagegen/scripts/remove_chroma_key.py` helper, and validate the alpha result before using it. If this path looks unsuitable or fails, ask before switching to CLI `gpt-image-1.5`.
10. Use the built-in `image_gen.imagegen` tool by default.
11. For transparent-output requests, follow the transparent image guidance below: generate with built-in `image_gen.imagegen` on a flat chroma-key background, copy the selected output into the workspace or `tmp/imagegen/`, run the installed `$CODEX_HOME/skills/.system/imagegen/scripts/remove_chroma_key.py` helper, and validate the alpha result before using it. If this path looks unsuitable or fails, ask before switching to CLI `gpt-image-1.5`.
12. Inspect outputs and validate: subject, style, composition, text accuracy, and invariants/avoid items.
13. Iterate with a single targeted change, then re-check.
14. For preview-only work, render the image inline; the underlying file may remain at the default `$CODEX_HOME/generated_images/...` path.
@@ -118,10 +120,10 @@ Assume the user wants a new image unless they clearly ask to change an existing
## Transparent image requests
Transparent-image requests still use built-in `image_gen` first. Because the built-in tool does not expose a true transparent-background control, create a removable chroma-key source image and then convert the key color to alpha locally.
Transparent-image requests still use built-in `image_gen.imagegen` first. Because the built-in tool does not expose a true transparent-background control, create a removable chroma-key source image and then convert the key color to alpha locally.
Default sequence:
1. Use built-in `image_gen` to generate the requested subject on a perfectly flat solid chroma-key background.
1. Use built-in `image_gen.imagegen` to generate the requested subject on a perfectly flat solid chroma-key background.
2. Choose a key color that is unlikely to appear in the subject: default `#00ff00`, use `#ff00ff` for green subjects, and avoid `#0000ff` for blue subjects.
3. After generation, move or copy the selected source image from `$CODEX_HOME/generated_images/...` into the workspace or `tmp/imagegen/`.
4. Run the installed helper path, not a project-relative script path:
@@ -202,7 +204,7 @@ Edit:
- identity-preserve — try-on, person-in-scene; lock face/body/pose.
- precise-object-edit — remove/replace a specific element (including interior swaps).
- lighting-weather — time-of-day/season/atmosphere changes only.
- background-extraction — transparent background / clean cutout. Use built-in `image_gen` with chroma-key removal first for simple opaque subjects; ask before using CLI true transparency for complex subjects.
- background-extraction — transparent background / clean cutout. Use built-in `image_gen.imagegen` with chroma-key removal first for simple opaque subjects; ask before using CLI true transparency for complex subjects.
- style-transfer — apply reference style while changing subject/scene.
- compositing — multi-image insert/merge with matched lighting/perspective.
- sketch-to-render — drawing/line art to photoreal render.
@@ -231,7 +233,7 @@ Avoid: <negative constraints>
Notes:
- `Asset type` and `Input images` are prompt scaffolding, not dedicated CLI flags.
- `Scene/backdrop` refers to the visual setting. It is not the same as the fallback CLI `background` parameter, which controls output transparency behavior.
- Fallback-only execution notes such as `Quality:`, `Input fidelity:`, masks, output format, and output paths belong in the CLI path only. Do not treat them as built-in `image_gen` tool arguments.
- Fallback-only execution notes such as `Quality:`, `Input fidelity:`, masks, output format, and output paths belong in the CLI path only. Do not treat them as built-in `image_gen.imagegen` tool arguments.
Augmentation rules:
- Keep it short.
@@ -307,7 +309,7 @@ Popular `gpt-image-2` sizes:
## Fallback CLI mode only
### Temp and output conventions
These conventions apply only to the CLI fallback. They do not describe built-in `image_gen` output behavior.
These conventions apply only to the CLI fallback. They do not describe built-in `image_gen.imagegen` output behavior.
- Use `tmp/imagegen/` for intermediate files (for example JSONL batches); delete them when done.
- Write final artifacts under `output/imagegen/`.
- Use `--out` or `--out-dir` to control output paths; keep filenames stable and descriptive.
@@ -331,7 +333,7 @@ Portability note:
### Environment
- `OPENAI_API_KEY` must be set for live API calls.
- Do not ask the user for `OPENAI_API_KEY` when using the built-in `image_gen` tool.
- Do not ask the user for `OPENAI_API_KEY` when using the built-in `image_gen.imagegen` tool.
- Never ask the user to paste the full key in chat. Ask them to set it locally and confirm when ready.
If the key is missing, give the user these steps: