Base: codex-main originale (prima del fork aKode)
This commit is contained in:
10
codex-rs/ext/image-generation/BUILD.bazel
Normal file
10
codex-rs/ext/image-generation/BUILD.bazel
Normal file
@@ -0,0 +1,10 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "image-generation",
|
||||
compile_data = [
|
||||
"imagegen_description.md",
|
||||
"imagegen_gif_description.md",
|
||||
],
|
||||
crate_name = "codex_image_generation_extension",
|
||||
)
|
||||
43
codex-rs/ext/image-generation/Cargo.toml
Normal file
43
codex-rs/ext/image-generation/Cargo.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "codex-image-generation-extension"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "codex_image_generation_extension"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-attachment-store = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-extension-items = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-tools = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-image = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
http = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true, features = ["png"] }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
18
codex-rs/ext/image-generation/imagegen_description.md
Normal file
18
codex-rs/ext/image-generation/imagegen_description.md
Normal file
@@ -0,0 +1,18 @@
|
||||
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).
|
||||
|
||||
Guidelines:
|
||||
- imagegen needs a few minutes to finish. In code-mode, use the first-line @exec directive to give the initial call 120 seconds and the same yield for any waits that follow. Once it finishes, return the image with generatedImage(result).
|
||||
- Avoid printing the full result or its base64 image data with `text()` or `notify()`; print only small metadata when needed.
|
||||
- Set `transparent_background` to true when the request calls for a transparent background, including background removal or a cutout; set it to false otherwise. For edits, preserve existing transparency unless the user asks to change it.
|
||||
- Omit both `referenced_image_paths` and `num_last_images_to_include` when generating a brand new image.
|
||||
- For edits, use `referenced_image_paths` when every target image has a local file path.
|
||||
- If you have not seen a local image yet, use `view_image` to inspect it before editing.
|
||||
- Use `num_last_images_to_include` only when at least one target image has no local file path.
|
||||
- Set `num_last_images_to_include` to the smallest number of recent conversation images that includes every target image, up to 5.
|
||||
- Never provide both `referenced_image_paths` and `num_last_images_to_include`.
|
||||
- If neither mechanism can include every target image, ask the user to attach the missing images again.
|
||||
- Directly generate the image without reconfirmation or clarification unless required images must be attached again.
|
||||
- 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.
|
||||
@@ -0,0 +1,4 @@
|
||||
GIF guidelines:
|
||||
- Use imagegen only for simple GIFs with 2–16 frames. For more complex animations or more than 16 frames, use other tools instead.
|
||||
- Set `gif` to request GIF output. Use `{}` for the defaults (9 frames, 200 ms per frame), or set `frame_count` and `frame_duration_ms`.
|
||||
- To edit a previously generated GIF, first inspect its frames, then create a spritesheet with equal-sized cells in a regular grid. Pass that spritesheet through `referenced_image_paths` and set `gif` to generate the new GIF. Do not pass the GIF itself as an edit input.
|
||||
76
codex-rs/ext/image-generation/src/artifact.rs
Normal file
76
codex-rs/ext/image-generation/src/artifact.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
const GENERATED_IMAGE_ARTIFACTS_DIR: &str = "generated_images";
|
||||
const MAX_IMAGE_GENERATION_OUTPUT_HINT_BYTES: usize = 1024;
|
||||
|
||||
/// Identify GIFs from their encoded header so transport and filenames preserve animation.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum GeneratedImageFormat {
|
||||
Png,
|
||||
Gif,
|
||||
}
|
||||
|
||||
impl GeneratedImageFormat {
|
||||
pub(crate) fn from_base64(result: &str) -> Self {
|
||||
let result = result.trim();
|
||||
if result.starts_with("R0lGODdh") || result.starts_with("R0lGODlh") {
|
||||
Self::Gif
|
||||
} else {
|
||||
Self::Png
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mime_type(self) -> &'static str {
|
||||
match self {
|
||||
Self::Png => "image/png",
|
||||
Self::Gif => "image/gif",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the extension-owned artifact path for a generated image.
|
||||
pub(crate) fn image_generation_artifact_path(
|
||||
save_root: &AbsolutePathBuf,
|
||||
session_id: &str,
|
||||
call_id: &str,
|
||||
format: GeneratedImageFormat,
|
||||
) -> AbsolutePathBuf {
|
||||
let sanitize = |value: &str| {
|
||||
let mut sanitized: String = value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if sanitized.is_empty() {
|
||||
sanitized = "generated_image".to_string();
|
||||
}
|
||||
sanitized
|
||||
};
|
||||
|
||||
let extension = match format {
|
||||
GeneratedImageFormat::Png => "png",
|
||||
GeneratedImageFormat::Gif => "gif",
|
||||
};
|
||||
save_root
|
||||
.join(GENERATED_IMAGE_ARTIFACTS_DIR)
|
||||
.join(sanitize(session_id))
|
||||
.join(format!("{}.{extension}", sanitize(call_id)))
|
||||
}
|
||||
|
||||
/// Returns the model-facing generated-image path hint, or omits it if it is too large.
|
||||
pub(crate) fn image_generation_output_hint(
|
||||
image_output_dir: impl Display,
|
||||
image_output_path: impl Display,
|
||||
) -> Option<String> {
|
||||
let hint = format!(
|
||||
"Generated images are saved to {image_output_dir} as {image_output_path} by default.\nIf you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.\nThe generated image is already displayed to the user. There is no need to render it in the final response as a Markdown image or file link."
|
||||
);
|
||||
(hint.len() <= MAX_IMAGE_GENERATION_OUTPUT_HINT_BYTES).then_some(hint)
|
||||
}
|
||||
158
codex-rs/ext/image-generation/src/backend.rs
Normal file
158
codex-rs/ext/image-generation/src/backend.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageRequestError;
|
||||
use codex_api::ImageResponse;
|
||||
use codex_api::ImagesClient;
|
||||
use codex_api::ReqwestTransport;
|
||||
use codex_api::map_api_error;
|
||||
use codex_core::X_CODEX_TURN_METADATA_HEADER;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::default_client::add_originator_header;
|
||||
use codex_login::default_client::create_transport_for_routes_async;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
const X_CODEX_IMAGE_TURN_ID_HEADER: &str = "x-codex-image-turn-id";
|
||||
|
||||
pub(crate) struct ImageBackendError {
|
||||
message: String,
|
||||
codex_error: CodexErr,
|
||||
imagegen_request_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ImageBackendError {
|
||||
fn from_image_request(error: ImageRequestError) -> Self {
|
||||
let (error, imagegen_request_id) = error.into_parts();
|
||||
let message = error.to_string();
|
||||
Self {
|
||||
message,
|
||||
codex_error: map_api_error(error),
|
||||
imagegen_request_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_message(message: String) -> Self {
|
||||
Self {
|
||||
codex_error: CodexErr::Stream(message.clone()),
|
||||
message,
|
||||
imagegen_request_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
pub(crate) fn codex_error(&self) -> &CodexErr {
|
||||
&self.codex_error
|
||||
}
|
||||
|
||||
pub(crate) fn imagegen_request_id(&self) -> Option<&str> {
|
||||
self.imagegen_request_id.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CodexImagesBackend {
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
originator: Option<String>,
|
||||
}
|
||||
|
||||
impl CodexImagesBackend {
|
||||
/// Creates a backend that sends image requests through the active model provider.
|
||||
pub(crate) fn new(
|
||||
provider: SharedModelProvider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
originator: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
provider,
|
||||
http_client_factory,
|
||||
originator,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the provider and auth required for the current image API request.
|
||||
async fn client(&self) -> Result<ImagesClient<ReqwestTransport>, ImageBackendError> {
|
||||
let setup = codex_model_provider::resolve_request(
|
||||
self.provider.as_ref(),
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
self.http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
let transport = create_transport_for_routes_async(
|
||||
setup.http_client_factory,
|
||||
ClientRouteClass::Api,
|
||||
setup.redirect_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
Ok(ImagesClient::new(
|
||||
transport,
|
||||
setup.api_provider,
|
||||
setup.api_auth,
|
||||
))
|
||||
}
|
||||
|
||||
/// Sends a standalone image generation request through the configured Images client.
|
||||
pub(crate) async fn generate(
|
||||
&self,
|
||||
request: ImageGenerationRequest,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> Result<(ImageResponse, Option<String>), ImageBackendError> {
|
||||
self.client()
|
||||
.await?
|
||||
.generate(
|
||||
&request,
|
||||
image_request_headers(self.originator.as_deref(), turn_id, codex_turn_metadata),
|
||||
)
|
||||
.await
|
||||
.map_err(ImageBackendError::from_image_request)
|
||||
}
|
||||
|
||||
/// Sends a standalone image edit request through the configured Images client.
|
||||
pub(crate) async fn edit(
|
||||
&self,
|
||||
request: ImageEditRequest,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> Result<(ImageResponse, Option<String>), ImageBackendError> {
|
||||
self.client()
|
||||
.await?
|
||||
.edit(
|
||||
&request,
|
||||
image_request_headers(self.originator.as_deref(), turn_id, codex_turn_metadata),
|
||||
)
|
||||
.await
|
||||
.map_err(ImageBackendError::from_image_request)
|
||||
}
|
||||
}
|
||||
|
||||
fn image_request_headers(
|
||||
originator: Option<&str>,
|
||||
turn_id: &str,
|
||||
codex_turn_metadata: Option<&str>,
|
||||
) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Ok(turn_id) = HeaderValue::from_str(turn_id) {
|
||||
headers.insert(X_CODEX_IMAGE_TURN_ID_HEADER, turn_id);
|
||||
}
|
||||
if let Some(originator) = originator {
|
||||
add_originator_header(&mut headers, originator);
|
||||
}
|
||||
|
||||
if let Some(metadata) = codex_turn_metadata
|
||||
&& let Ok(metadata) = HeaderValue::from_str(metadata)
|
||||
{
|
||||
headers.insert(X_CODEX_TURN_METADATA_HEADER, metadata);
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
137
codex-rs/ext/image-generation/src/extension.rs
Normal file
137
codex-rs/ext/image-generation/src/extension.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadOriginator;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolContributor;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use crate::backend::CodexImagesBackend;
|
||||
use crate::tool::ImageGenerationTool;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ImageGenerationExtension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
resolve_save_root: Arc<SaveRootResolver>,
|
||||
}
|
||||
|
||||
type SaveRootResolver = dyn Fn(&Config) -> Option<AbsolutePathBuf> + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ImageGenerationExtensionConfig {
|
||||
available: bool,
|
||||
gif_enabled: bool,
|
||||
http_client_factory: HttpClientFactory,
|
||||
provider: ModelProviderInfo,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
impl ImageGenerationExtensionConfig {
|
||||
/// Resolves the image provider and save root for a thread.
|
||||
fn from_config(config: &Config, resolve_save_root: &SaveRootResolver) -> Self {
|
||||
Self {
|
||||
available: config.model_provider.is_openai()
|
||||
|| config.model_provider.requires_openai_auth
|
||||
|| config.model_provider.uses_openai_actor_authorization(),
|
||||
gif_enabled: config.features.image_generation_animation_enabled(),
|
||||
http_client_factory: config.http_client_factory(),
|
||||
provider: config.model_provider.clone(),
|
||||
save_root: resolve_save_root(config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for ImageGenerationExtension {
|
||||
/// Seeds image-generation configuration when a thread begins.
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input
|
||||
.thread_store
|
||||
.insert(ImageGenerationExtensionConfig::from_config(
|
||||
input.config,
|
||||
self.resolve_save_root.as_ref(),
|
||||
));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for ImageGenerationExtension {
|
||||
/// Refreshes image-generation configuration after thread configuration changes.
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
thread_store.insert(ImageGenerationExtensionConfig::from_config(
|
||||
new_config,
|
||||
self.resolve_save_root.as_ref(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for ImageGenerationExtension {
|
||||
/// Creates the image-generation tool exposed by this installed extension.
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
let Some(config) = thread_store.get::<ImageGenerationExtensionConfig>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !config.available {
|
||||
return Vec::new();
|
||||
}
|
||||
let auth = thread_store
|
||||
.get::<codex_model_provider::ProviderAuthContext>()
|
||||
.unwrap_or_else(|| {
|
||||
Arc::new(codex_model_provider::ProviderAuthContext {
|
||||
credentials: Arc::clone(&self.auth_manager),
|
||||
runtime_auth: None,
|
||||
})
|
||||
});
|
||||
|
||||
vec![Arc::new(ImageGenerationTool::new(
|
||||
CodexImagesBackend::new(
|
||||
auth.model_provider(config.provider.clone()),
|
||||
config.http_client_factory.clone(),
|
||||
thread_store
|
||||
.get::<ThreadOriginator>()
|
||||
.map(|originator| originator.0.clone()),
|
||||
),
|
||||
config.save_root.clone(),
|
||||
thread_store.level_id().to_string(),
|
||||
config.gif_enabled,
|
||||
))]
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the standalone image-generation extension contributors.
|
||||
pub fn install(
|
||||
registry: &mut ExtensionRegistryBuilder<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
resolve_save_root: impl Fn(&Config) -> Option<AbsolutePathBuf> + Send + Sync + 'static,
|
||||
) {
|
||||
let extension = Arc::new(ImageGenerationExtension {
|
||||
auth_manager,
|
||||
resolve_save_root: Arc::new(resolve_save_root),
|
||||
});
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.tool_contributor(extension);
|
||||
}
|
||||
9
codex-rs/ext/image-generation/src/lib.rs
Normal file
9
codex-rs/ext/image-generation/src/lib.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
mod artifact;
|
||||
mod backend;
|
||||
mod extension;
|
||||
mod tool;
|
||||
|
||||
pub use extension::install;
|
||||
|
||||
pub(crate) const IMAGE_GEN_NAMESPACE: &str = "image_gen";
|
||||
pub(crate) const IMAGEGEN_TOOL_NAME: &str = "imagegen";
|
||||
691
codex-rs/ext/image-generation/src/tests.rs
Normal file
691
codex-rs/ext/image-generation/src/tests.rs
Normal file
@@ -0,0 +1,691 @@
|
||||
use base64::Engine;
|
||||
use codex_api::ImageBackground;
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageQuality;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_items::image_generation::ImageGenerationFailure;
|
||||
use codex_extension_items::image_generation::ImageGenerationInputImage;
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::UsageLimitReachedError;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ToolEnvironment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use super::GeneratedImageOutput;
|
||||
use super::ImageRequest;
|
||||
use super::ImagegenArgs;
|
||||
use super::PreparedImageRequest;
|
||||
use super::imagegen_tool_spec;
|
||||
use super::request_for_call_args;
|
||||
use super::usage_limit_failure;
|
||||
use crate::IMAGE_GEN_NAMESPACE;
|
||||
use crate::IMAGEGEN_TOOL_NAME;
|
||||
use crate::artifact::image_generation_artifact_path;
|
||||
use crate::artifact::image_generation_output_hint;
|
||||
|
||||
const RESULT: &str = "cG5n";
|
||||
|
||||
#[test]
|
||||
fn test_usage_limit_failure_without_an_exhausted_window_reset() {
|
||||
for (limit_id, expected) in [
|
||||
(
|
||||
Some("imagegen_premium"),
|
||||
Some(ImageGenerationFailure::UsageLimitExceeded {
|
||||
limit_id: "imagegen_premium".to_string(),
|
||||
resets_at: None,
|
||||
}),
|
||||
),
|
||||
(Some("premium"), None),
|
||||
(None, None),
|
||||
] {
|
||||
let error = CodexErr::UsageLimitReached(UsageLimitReachedError {
|
||||
plan_type: None,
|
||||
resets_at: None,
|
||||
limit_window_minutes: None,
|
||||
rate_limits: Some(Box::new(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"limit_id": limit_id,
|
||||
"primary": {"used_percent": 100.0},
|
||||
"secondary": {"used_percent": 50.0, "resets_at": 3000}
|
||||
}))
|
||||
.expect("rate limit snapshot"),
|
||||
)),
|
||||
promo_message: None,
|
||||
rate_limit_reached_type: None,
|
||||
});
|
||||
|
||||
assert_eq!(usage_limit_failure(&error), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn referenced_files_record_the_exact_bytes_read_for_each_request() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let root = AbsolutePathBuf::from_absolute_path(directory.path()).expect("absolute root");
|
||||
let first = root.join("first.png");
|
||||
let second = root.join("second.png");
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let environment =
|
||||
ToolEnvironment::new("test".to_string(), PathUri::from_abs_path(&root), &access);
|
||||
let args = ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "combine the references".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![second.clone(), first.clone()]),
|
||||
num_last_images_to_include: None,
|
||||
};
|
||||
let png = |color| {
|
||||
let image = image::RgbaImage::from_pixel(1, 1, image::Rgba(color));
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
image
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.expect("encode PNG");
|
||||
bytes.into_inner()
|
||||
};
|
||||
let second_bytes = png([0, 255, 0, 255]);
|
||||
std::fs::write(second.as_path(), &second_bytes).expect("write second image");
|
||||
std::fs::write(root.join("unused.png").as_path(), png([0, 0, 255, 255]))
|
||||
.expect("write unused image");
|
||||
|
||||
// Reusing a path after replacing its contents must produce a new observation.
|
||||
for first_bytes in [png([255, 0, 0, 255]), png([255, 255, 0, 255])] {
|
||||
std::fs::write(first.as_path(), &first_bytes).expect("write first image");
|
||||
let inputs = [(&second, &second_bytes), (&first, &first_bytes)];
|
||||
let expected = PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: inputs
|
||||
.iter()
|
||||
.map(|(_, bytes)| ImageReference::Inline {
|
||||
image_url: format!(
|
||||
"data:image/png;base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
),
|
||||
})
|
||||
.collect(),
|
||||
prompt: args.prompt.clone(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: inputs
|
||||
.iter()
|
||||
.map(|(path, bytes)| ImageGenerationInputImage {
|
||||
path: (*path).clone(),
|
||||
sha256: format!("{:x}", Sha256::digest(bytes)),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
request_for_call_args(&args, &[], std::slice::from_ref(&environment))
|
||||
.await
|
||||
.expect("edit request"),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn unreadable_or_invalid_reference_does_not_build_an_edit_request() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let root = AbsolutePathBuf::from_absolute_path(directory.path()).expect("absolute root");
|
||||
let invalid = root.join("invalid.png");
|
||||
std::fs::write(invalid.as_path(), b"not an image").expect("write invalid image");
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let environment =
|
||||
ToolEnvironment::new("test".to_string(), PathUri::from_abs_path(&root), &access);
|
||||
for path in [root.join("missing.png"), invalid] {
|
||||
let args = ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "edit the reference".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![path]),
|
||||
num_last_images_to_include: None,
|
||||
};
|
||||
assert!(
|
||||
request_for_call_args(&args, &[], std::slice::from_ref(&environment))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_path_sanitizes_session_and_call_ids() {
|
||||
let save_root = AbsolutePathBuf::current_dir().expect("current directory should be absolute");
|
||||
|
||||
assert_eq!(
|
||||
image_generation_artifact_path(
|
||||
&save_root,
|
||||
"../session",
|
||||
"../call",
|
||||
super::GeneratedImageFormat::Png
|
||||
),
|
||||
save_root
|
||||
.join("generated_images")
|
||||
.join("___session")
|
||||
.join("___call.png")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_reserved_image_gen_namespace() {
|
||||
let ToolSpec::Namespace(spec) = imagegen_tool_spec(/*gif_enabled*/ false) else {
|
||||
panic!("imagegen should advertise a namespace tool");
|
||||
};
|
||||
assert_eq!(spec.name, IMAGE_GEN_NAMESPACE);
|
||||
let ResponsesApiNamespaceTool::Function(function) = &spec.tools[0] else {
|
||||
panic!("imagegen should advertise a function tool");
|
||||
};
|
||||
assert_eq!(function.name, IMAGEGEN_TOOL_NAME);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imagegen_code_mode_declaration_describes_generated_image_result() {
|
||||
let spec = imagegen_tool_spec(/*gif_enabled*/ false);
|
||||
let definitions = codex_tools::collect_code_mode_tool_definitions(
|
||||
[&spec],
|
||||
/*code_mode_input_schema_max_bytes*/ None,
|
||||
);
|
||||
let [definition] = definitions.as_slice() else {
|
||||
panic!("imagegen should produce one code-mode declaration");
|
||||
};
|
||||
let (_, return_type) = definition
|
||||
.description
|
||||
.rsplit_once("): Promise<")
|
||||
.expect("imagegen declaration should return a promise");
|
||||
assert_eq!(
|
||||
return_type,
|
||||
"{ image_url: string; output_hint?: string; }>; };\n```"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imagegen_output_schema_does_not_change_direct_api_serialization() {
|
||||
let spec = imagegen_tool_spec(/*gif_enabled*/ false);
|
||||
let mut without_output_schema = spec.clone();
|
||||
let ToolSpec::Namespace(namespace) = &mut without_output_schema else {
|
||||
panic!("imagegen should advertise a namespace tool");
|
||||
};
|
||||
let ResponsesApiNamespaceTool::Function(function) = &mut namespace.tools[0] else {
|
||||
panic!("imagegen should advertise a function tool");
|
||||
};
|
||||
function.output_schema = None;
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(spec).expect("tool spec should serialize"),
|
||||
serde_json::to_value(without_output_schema).expect("tool spec should serialize")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omitted_references_generate_with_fixed_defaults() {
|
||||
assert_eq!(
|
||||
request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "paint a moonlit lake".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: None,
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("generation request should build"),
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Generate(ImageGenerationRequest {
|
||||
output: None,
|
||||
prompt: "paint a moonlit lake".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_selects_newest_images_in_chronological_order() {
|
||||
let history = vec![
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
input_image("user-1"),
|
||||
input_image("user-2"),
|
||||
ContentItem::InputText {
|
||||
text: "edit these".to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCall {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
name: "mcp_image".to_string(),
|
||||
namespace: None,
|
||||
arguments: "{}".to_string(),
|
||||
call_id: "mcp-call".to_string(),
|
||||
encrypted_function_args: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("mcp-call".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: image_output("mcp"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCall {
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
status: Some("completed".to_string()),
|
||||
call_id: "code-mode-call".to_string(),
|
||||
name: "exec".to_string(),
|
||||
namespace: None,
|
||||
input: String::new(),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCallOutput {
|
||||
id: None,
|
||||
call_id: "code-mode-call".to_string(),
|
||||
name: Some("exec".to_string()),
|
||||
output: image_output("code-mode"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::ImageGenerationCall {
|
||||
encrypted_content: None,
|
||||
id: Some(ResponseItemId::with_suffix("ig", "generated-call")),
|
||||
status: "completed".to_string(),
|
||||
revised_prompt: None,
|
||||
result: "generated".to_string(),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: None,
|
||||
name: Some("notifications".to_string()),
|
||||
namespace: Some("slack".to_string()),
|
||||
output: image_output("standalone"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(5),
|
||||
},
|
||||
&history,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("history-backed edit request should build"),
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(expected_edit_request(
|
||||
"change the lighting",
|
||||
&["user-2", "mcp", "code-mode", "generated", "standalone"],
|
||||
)),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_passes_file_backed_image_to_edit_request() {
|
||||
let request = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
input_image("older-inline-image"),
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("a selected file-backed image should be passed through");
|
||||
|
||||
assert_eq!(
|
||||
request,
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: vec![ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
}],
|
||||
prompt: "change the lighting".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Tool-output file references must count toward the window instead of exposing an older image.
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_passes_file_backed_tool_output_to_edit_request() {
|
||||
let request = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("older-inline-output".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: image_output("older-inline-image"),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
ResponseItem::CustomToolCallOutput {
|
||||
id: None,
|
||||
call_id: "newer-file-backed-output".to_string(),
|
||||
name: Some("view_image".to_string()),
|
||||
output: FunctionCallOutputPayload::from_content_items(vec![
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
]),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect("a selected file-backed tool output should be passed through");
|
||||
|
||||
assert_eq!(
|
||||
request,
|
||||
PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
output: None,
|
||||
images: vec![ImageReference::File {
|
||||
file_id: "newer-file-backed-image".to_string(),
|
||||
}],
|
||||
prompt: "change the lighting".to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_image_selectors_return_tool_error() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(vec![
|
||||
"/tmp/image.png"
|
||||
.try_into()
|
||||
.expect("test path should be absolute"),
|
||||
]),
|
||||
num_last_images_to_include: Some(1),
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("conflicting selectors should fail");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"provide only one of `referenced_image_paths` or `num_last_images_to_include`"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn too_many_referenced_image_paths_return_tool_error() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: Some(
|
||||
(0..6)
|
||||
.map(|index| {
|
||||
format!("/tmp/image-{index}.png")
|
||||
.try_into()
|
||||
.expect("test path should be absolute")
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
num_last_images_to_include: None,
|
||||
},
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("too many paths should fail before reading files");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"`referenced_image_paths` must contain at most 5 paths"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recent_image_fallback_requires_requested_count() {
|
||||
let error = request_for_call_args(
|
||||
&ImagegenArgs {
|
||||
gif: None,
|
||||
prompt: "change the lighting".to_string(),
|
||||
transparent_background: false,
|
||||
referenced_image_paths: None,
|
||||
num_last_images_to_include: Some(2),
|
||||
},
|
||||
&[ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![input_image("only-image")],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("history-backed edit should require the requested image count");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"requested the last 2 conversation images, but only 1 were available"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_returns_image_input_and_output_hint() {
|
||||
let output_hint =
|
||||
image_generation_output_hint("/tmp", "/tmp/call-1.png").expect("hint should fit");
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: Some(output_hint.clone()),
|
||||
};
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: response_output,
|
||||
..
|
||||
} = output.to_response_item("call-1", &function_payload())
|
||||
else {
|
||||
panic!("imagegen should return function tool output");
|
||||
};
|
||||
let FunctionCallOutputBody::ContentItems(content_items) = response_output.body else {
|
||||
panic!("imagegen output should contain generated image bytes");
|
||||
};
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{RESULT}")
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText { text: output_hint },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_returns_generated_image_helper_input_in_code_mode() {
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: Some("generated image save hint".to_string()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
"output_hint": "generated image save hint",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_output_omits_oversized_output_hint() {
|
||||
let long_path = "x".repeat(1024);
|
||||
let output = GeneratedImageOutput {
|
||||
result: RESULT.to_string(),
|
||||
output_hint: image_generation_output_hint("/tmp", long_path),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
})
|
||||
);
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: response_output,
|
||||
..
|
||||
} = output.to_response_item("call-1", &function_payload())
|
||||
else {
|
||||
panic!("imagegen should return function tool output");
|
||||
};
|
||||
let FunctionCallOutputBody::ContentItems(content_items) = response_output.body else {
|
||||
panic!("imagegen output should contain generated image bytes");
|
||||
};
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{RESULT}")
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn input_image(image: &str) -> ContentItem {
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
},
|
||||
detail: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn image_output(image: &str) -> FunctionCallOutputPayload {
|
||||
FunctionCallOutputPayload::from_content_items(vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
},
|
||||
detail: None,
|
||||
}])
|
||||
}
|
||||
|
||||
fn expected_edit_request(prompt: &str, images: &[&str]) -> ImageEditRequest {
|
||||
ImageEditRequest {
|
||||
output: None,
|
||||
images: images
|
||||
.iter()
|
||||
.map(|image| ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{image}"),
|
||||
})
|
||||
.collect(),
|
||||
prompt: prompt.to_string(),
|
||||
background: Some(ImageBackground::Opaque),
|
||||
model: "gpt-image-2".to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn function_payload() -> ToolPayload {
|
||||
ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
}
|
||||
}
|
||||
821
codex-rs/ext/image-generation/src/tool.rs
Normal file
821
codex-rs/ext/image-generation/src/tool.rs
Normal file
@@ -0,0 +1,821 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use codex_api::GifOptions;
|
||||
use codex_api::ImageBackground;
|
||||
use codex_api::ImageEditRequest;
|
||||
use codex_api::ImageGenerationRequest;
|
||||
use codex_api::ImageOutput;
|
||||
use codex_api::ImageQuality;
|
||||
use codex_attachment_store::UploadRequest;
|
||||
use codex_attachment_store::UploadResult;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_extension_api::ExtensionTurnItem;
|
||||
use codex_extension_api::FunctionCallError;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolEnvironment;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_api::parse_tool_input_schema;
|
||||
use codex_extension_items::ExtensionItem;
|
||||
use codex_extension_items::image_generation::GeneratedImageRef;
|
||||
use codex_extension_items::image_generation::ImageGenerationFailure;
|
||||
use codex_extension_items::image_generation::ImageGenerationInputImage;
|
||||
use codex_extension_items::image_generation::ImageGenerationItem;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ImageGenerationBeginEvent;
|
||||
use codex_protocol::protocol::ImageGenerationEndEvent;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ResponsesApiTool;
|
||||
use codex_tools::ToolExposure;
|
||||
use codex_tools::default_namespace_description;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_image::PromptImageMode;
|
||||
use codex_utils_image::load_for_prompt_bytes;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use schemars::JsonSchema;
|
||||
use schemars::r#gen::SchemaSettings;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::IMAGE_GEN_NAMESPACE;
|
||||
use crate::IMAGEGEN_TOOL_NAME;
|
||||
use crate::artifact::GeneratedImageFormat;
|
||||
use crate::artifact::image_generation_artifact_path;
|
||||
use crate::artifact::image_generation_output_hint;
|
||||
use crate::backend::CodexImagesBackend;
|
||||
|
||||
const IMAGE_MODEL: &str = "gpt-image-2";
|
||||
const MAX_EDIT_IMAGES: usize = 5;
|
||||
const MAX_EXECUTOR_GENERATED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_EXECUTOR_GENERATED_IMAGE_BASE64_BYTES: usize =
|
||||
MAX_EXECUTOR_GENERATED_IMAGE_BYTES.div_ceil(3) * 4;
|
||||
const IMAGEGEN_DESCRIPTION: &str = include_str!("../imagegen_description.md");
|
||||
const IMAGEGEN_GIF_DESCRIPTION: &str = include_str!("../imagegen_gif_description.md");
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ImageGenerationTool {
|
||||
backend: CodexImagesBackend,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
thread_id: String,
|
||||
gif_enabled: bool,
|
||||
}
|
||||
|
||||
impl ImageGenerationTool {
|
||||
/// Creates an image-generation tool backed by an image API executor.
|
||||
pub(crate) fn new(
|
||||
backend: CodexImagesBackend,
|
||||
save_root: Option<AbsolutePathBuf>,
|
||||
thread_id: String,
|
||||
gif_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
backend,
|
||||
save_root,
|
||||
thread_id,
|
||||
gif_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ImagegenArgs {
|
||||
prompt: String,
|
||||
/// Set this to create a simple looping GIF with 2–16 frames. Use {} for defaults.
|
||||
gif: Option<GifOptions>,
|
||||
/// Whether the output should have a transparent background. Defaults to false.
|
||||
#[serde(default)]
|
||||
transparent_background: bool,
|
||||
#[schemars(length(max = 5))]
|
||||
referenced_image_paths: Option<Vec<AbsolutePathBuf>>,
|
||||
#[schemars(range(min = 1, max = 5))]
|
||||
num_last_images_to_include: Option<usize>,
|
||||
}
|
||||
|
||||
fn legacy_end_event(item: &ImageGenerationItem) -> EventMsg {
|
||||
EventMsg::ImageGenerationEnd(ImageGenerationEndEvent {
|
||||
call_id: item.id.clone(),
|
||||
status: item.status.clone(),
|
||||
revised_prompt: item.revised_prompt.clone(),
|
||||
image: item.image.clone(),
|
||||
transparent_background: item.transparent_background,
|
||||
failure: item.failure.clone(),
|
||||
saved_path: item.saved_path.clone(),
|
||||
input_images: item.input_images.clone(),
|
||||
generation_id: item.generation_id.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn extension_turn_item(item: ImageGenerationItem, legacy_event: EventMsg) -> ExtensionTurnItem {
|
||||
ExtensionTurnItem {
|
||||
item: ExtensionItem::ImageGeneration(item),
|
||||
legacy_events: vec![legacy_event],
|
||||
}
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> for ImageGenerationTool {
|
||||
/// Keeps the tool in the existing image-generation Responses namespace.
|
||||
fn tool_name(&self) -> ToolName {
|
||||
ToolName::namespaced(IMAGE_GEN_NAMESPACE, IMAGEGEN_TOOL_NAME)
|
||||
}
|
||||
|
||||
/// Advertises a rewritten prompt, background choice, and optional edit references.
|
||||
fn spec(&self) -> ToolSpec {
|
||||
imagegen_tool_spec(self.gif_enabled)
|
||||
}
|
||||
|
||||
/// Exposes image generation directly and through the nested code-mode tool surface.
|
||||
fn exposure(&self) -> ToolExposure {
|
||||
ToolExposure::Direct
|
||||
}
|
||||
|
||||
/// Executes the selected image operation and returns the completed image result.
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> codex_extension_api::ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
{
|
||||
Box::pin(self.handle_call(call))
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageGenerationTool {
|
||||
async fn handle_call(
|
||||
&self,
|
||||
call: ToolCall<'_>,
|
||||
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
||||
let args = parse_args(&call)?;
|
||||
if args.gif.is_some() && !self.gif_enabled {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"GIF output is unavailable in this session.".to_string(),
|
||||
));
|
||||
}
|
||||
let PreparedImageRequest {
|
||||
request,
|
||||
input_images,
|
||||
} = request_for_call_args(&args, call.conversation_history.items(), &call.environments)
|
||||
.await?;
|
||||
call.turn_item_emitter
|
||||
.emit_started(extension_turn_item(
|
||||
ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "in_progress".to_string(),
|
||||
revised_prompt: None,
|
||||
image: GeneratedImageRef::Inline {
|
||||
result: String::new(),
|
||||
},
|
||||
transparent_background: None,
|
||||
failure: None,
|
||||
saved_path: None,
|
||||
input_images: Vec::new(),
|
||||
imagegen_request_id: None,
|
||||
generation_id: None,
|
||||
},
|
||||
EventMsg::ImageGenerationBegin(ImageGenerationBeginEvent {
|
||||
call_id: call.call_id.clone(),
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
let result = match request {
|
||||
ImageRequest::Generate(request) => {
|
||||
self.backend
|
||||
.generate(request, &call.turn_id, call.codex_turn_metadata.as_deref())
|
||||
.await
|
||||
}
|
||||
ImageRequest::Edit(request) => {
|
||||
self.backend
|
||||
.edit(request, &call.turn_id, call.codex_turn_metadata.as_deref())
|
||||
.await
|
||||
}
|
||||
}
|
||||
.map_err(|error| {
|
||||
(
|
||||
format!("image generation failed: {}", error.message()),
|
||||
usage_limit_failure(error.codex_error()),
|
||||
error.imagegen_request_id().map(str::to_string),
|
||||
)
|
||||
})
|
||||
.and_then(|(response, imagegen_request_id)| {
|
||||
let transparent_background = match response.background {
|
||||
Some(ImageBackground::Transparent) => Some(true),
|
||||
Some(ImageBackground::Opaque) => Some(false),
|
||||
Some(ImageBackground::Auto) | None => None,
|
||||
};
|
||||
match response.data.into_iter().next() {
|
||||
Some(data) => Ok((
|
||||
data.b64_json,
|
||||
transparent_background,
|
||||
imagegen_request_id,
|
||||
data.generation_id,
|
||||
)),
|
||||
None => Err((
|
||||
"image generation returned no image data".to_string(),
|
||||
None,
|
||||
imagegen_request_id,
|
||||
)),
|
||||
}
|
||||
});
|
||||
let (result, transparent_background, imagegen_request_id, generation_id) = match result {
|
||||
Ok(result) => result,
|
||||
Err((message, failure, imagegen_request_id)) => {
|
||||
let item = ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "failed".to_string(),
|
||||
revised_prompt: Some(args.prompt),
|
||||
image: GeneratedImageRef::Inline {
|
||||
result: String::new(),
|
||||
},
|
||||
transparent_background: None,
|
||||
failure,
|
||||
saved_path: None,
|
||||
input_images: Vec::new(),
|
||||
imagegen_request_id,
|
||||
generation_id: None,
|
||||
};
|
||||
let legacy_event = legacy_end_event(&item);
|
||||
call.turn_item_emitter
|
||||
.emit_completed(extension_turn_item(item, legacy_event))
|
||||
.await;
|
||||
return Err(FunctionCallError::RespondToModel(message));
|
||||
}
|
||||
};
|
||||
// TODO(anp): Migrate image tool path arguments and saved-path events to PathUri so image
|
||||
// operations can use the primary environment even when its paths are foreign to the host.
|
||||
let saved_path = save_image_generation_result(
|
||||
self.save_root.as_ref(),
|
||||
call.environments
|
||||
.iter()
|
||||
.find(|environment| environment.cwd.to_abs_path().is_ok()),
|
||||
&self.thread_id,
|
||||
&call.call_id,
|
||||
&result,
|
||||
)
|
||||
.await;
|
||||
// The UI item retains its attachment-store reference, while the model-facing output keeps
|
||||
// the original image so Core can prepare and upload it separately.
|
||||
let image = match BASE64_STANDARD.decode(result.trim().as_bytes()) {
|
||||
Ok(data) => {
|
||||
let request = UploadRequest {
|
||||
thread_id: self.thread_id.clone(),
|
||||
ephemeral: call.ephemeral,
|
||||
file_name: None,
|
||||
tags: HashMap::from([("usage".to_string(), "image_gen".to_string())]),
|
||||
data,
|
||||
};
|
||||
match call.attachment_store.upload(request).await {
|
||||
Ok(UploadResult::File { file_id }) => GeneratedImageRef::File { file_id },
|
||||
Ok(UploadResult::Inline { bytes }) => GeneratedImageRef::Inline {
|
||||
result: BASE64_STANDARD.encode(bytes),
|
||||
},
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
kind = ?error.kind(),
|
||||
"failed to upload generated image"
|
||||
);
|
||||
GeneratedImageRef::Inline {
|
||||
result: result.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!("failed to decode generated image for upload: {error}");
|
||||
GeneratedImageRef::Inline {
|
||||
result: result.clone(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let item = ImageGenerationItem {
|
||||
id: call.call_id.clone(),
|
||||
status: "completed".to_string(),
|
||||
revised_prompt: Some(args.prompt),
|
||||
image,
|
||||
transparent_background,
|
||||
failure: None,
|
||||
saved_path: saved_path.clone(),
|
||||
input_images,
|
||||
imagegen_request_id,
|
||||
generation_id,
|
||||
};
|
||||
let legacy_event = legacy_end_event(&item);
|
||||
call.turn_item_emitter
|
||||
.emit_completed(extension_turn_item(item, legacy_event))
|
||||
.await;
|
||||
let output_hint = saved_path.as_ref().and_then(|output_path| {
|
||||
let output_dir = output_path.parent()?;
|
||||
image_generation_output_hint(output_dir.display(), output_path.display())
|
||||
});
|
||||
Ok(Box::new(GeneratedImageOutput {
|
||||
result,
|
||||
output_hint,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_limit_failure(error: &CodexErr) -> Option<ImageGenerationFailure> {
|
||||
let CodexErrorDetails::UsageLimitReached(usage_limit) = error.details() else {
|
||||
return None;
|
||||
};
|
||||
let rate_limits = usage_limit.rate_limits.as_deref()?;
|
||||
let limit_id = rate_limits.limit_id.as_deref()?;
|
||||
if !matches!(limit_id, "image_gen" | "imagegen_premium") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let resets_at = if let Some(reset_at) = usage_limit.resets_at.as_ref() {
|
||||
Some(reset_at.timestamp())
|
||||
} else {
|
||||
[rate_limits.primary.as_ref(), rate_limits.secondary.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|window| window.used_percent >= 100.0)
|
||||
.filter_map(|window| window.resets_at)
|
||||
.max()
|
||||
};
|
||||
|
||||
Some(ImageGenerationFailure::UsageLimitExceeded {
|
||||
limit_id: limit_id.to_string(),
|
||||
resets_at,
|
||||
})
|
||||
}
|
||||
|
||||
async fn save_image_generation_result(
|
||||
save_root: Option<&AbsolutePathBuf>,
|
||||
environment: Option<&ToolEnvironment<'_>>,
|
||||
session_id: &str,
|
||||
call_id: &str,
|
||||
result: &str,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let (output_dir, save_result) = match save_root {
|
||||
Some(save_root) => {
|
||||
let path = image_generation_artifact_path(
|
||||
save_root,
|
||||
session_id,
|
||||
call_id,
|
||||
GeneratedImageFormat::from_base64(result),
|
||||
);
|
||||
let output_dir = path.parent().unwrap_or_else(|| save_root.clone());
|
||||
let save_result: io::Result<AbsolutePathBuf> = async {
|
||||
let bytes = BASE64_STANDARD
|
||||
.decode(result.trim().as_bytes())
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
LOCAL_FS
|
||||
.create_directory(
|
||||
&PathUri::from_abs_path(&parent),
|
||||
CreateDirectoryOptions {
|
||||
recursive: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
LOCAL_FS
|
||||
.write_file(
|
||||
&PathUri::from_abs_path(&path),
|
||||
bytes,
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
Ok(path)
|
||||
}
|
||||
.await;
|
||||
(output_dir, save_result)
|
||||
}
|
||||
None => {
|
||||
let environment = environment?;
|
||||
let cwd = environment.cwd.to_abs_path().ok()?;
|
||||
let fs = environment.fs();
|
||||
let output_dir = cwd.join("generated_images");
|
||||
let save_result: io::Result<AbsolutePathBuf> = async {
|
||||
let result = result.trim();
|
||||
if result.len() > MAX_EXECUTOR_GENERATED_IMAGE_BASE64_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"generated image exceeds the executor file size limit",
|
||||
));
|
||||
}
|
||||
let bytes = BASE64_STANDARD
|
||||
.decode(result.as_bytes())
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if bytes.len() > MAX_EXECUTOR_GENERATED_IMAGE_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"generated image exceeds the executor file size limit",
|
||||
));
|
||||
}
|
||||
|
||||
let artifact_path = image_generation_artifact_path(
|
||||
&cwd,
|
||||
session_id,
|
||||
call_id,
|
||||
GeneratedImageFormat::from_base64(result),
|
||||
);
|
||||
let path = output_dir.join(artifact_path.as_path().file_name().unwrap_or_default());
|
||||
if let Some(parent) = path.parent() {
|
||||
let parent_uri = PathUri::from_abs_path(&parent);
|
||||
fs.create_directory(
|
||||
&parent_uri,
|
||||
CreateDirectoryOptions {
|
||||
recursive: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Full-access executor contexts do not prevent symlinked output directories.
|
||||
let metadata = fs.get_metadata(&parent_uri, Default::default()).await?;
|
||||
if metadata.is_symlink || !metadata.is_directory {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"generated image directory is not a real directory",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Existing destination hardlinks could otherwise overwrite files outside the workspace.
|
||||
let path_uri = PathUri::from_abs_path(&path);
|
||||
match fs.get_metadata(&path_uri, Default::default()).await {
|
||||
Ok(_) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"generated image destination already exists",
|
||||
));
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
|
||||
fs.write_file(&path_uri, bytes, Default::default()).await?;
|
||||
Ok(path)
|
||||
}
|
||||
.await;
|
||||
(output_dir, save_result)
|
||||
}
|
||||
};
|
||||
|
||||
match save_result {
|
||||
Ok(path) => Some(path),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
call_id = %call_id,
|
||||
output_dir = %output_dir.display(),
|
||||
"failed to save generated image: {error}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ImageRequest {
|
||||
Generate(ImageGenerationRequest),
|
||||
Edit(ImageEditRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct PreparedImageRequest {
|
||||
request: ImageRequest,
|
||||
input_images: Vec<ImageGenerationInputImage>,
|
||||
}
|
||||
|
||||
struct LoadedInputImage {
|
||||
image: ImageReference,
|
||||
identity: ImageGenerationInputImage,
|
||||
}
|
||||
|
||||
async fn request_for_call_args(
|
||||
args: &ImagegenArgs,
|
||||
history: &[ResponseItem],
|
||||
environments: &[ToolEnvironment<'_>],
|
||||
) -> Result<PreparedImageRequest, FunctionCallError> {
|
||||
let background = if args.transparent_background {
|
||||
ImageBackground::Transparent
|
||||
} else {
|
||||
ImageBackground::Opaque
|
||||
};
|
||||
let paths = args.referenced_image_paths.as_deref().unwrap_or_default();
|
||||
if paths.len() > MAX_EDIT_IMAGES {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"`referenced_image_paths` must contain at most {MAX_EDIT_IMAGES} paths"
|
||||
)));
|
||||
}
|
||||
let mut input_images = Vec::with_capacity(paths.len());
|
||||
let images = match (paths.is_empty(), args.num_last_images_to_include) {
|
||||
(true, None) => {
|
||||
return Ok(PreparedImageRequest {
|
||||
request: ImageRequest::Generate(ImageGenerationRequest {
|
||||
prompt: args.prompt.clone(),
|
||||
output: args.gif.map(ImageOutput::Gif),
|
||||
background: Some(background),
|
||||
model: IMAGE_MODEL.to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images,
|
||||
});
|
||||
}
|
||||
(false, None) => {
|
||||
let Some(environment) = environments
|
||||
.iter()
|
||||
.find(|environment| environment.cwd.to_abs_path().is_ok())
|
||||
else {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"referenced image paths are unavailable in this session".to_string(),
|
||||
));
|
||||
};
|
||||
let mut images = Vec::with_capacity(paths.len());
|
||||
for path in paths {
|
||||
let input = load_input_image(path, environment).await?;
|
||||
images.push(input.image);
|
||||
input_images.push(input.identity);
|
||||
}
|
||||
images
|
||||
}
|
||||
(true, Some(count)) => {
|
||||
if !(1..=MAX_EDIT_IMAGES).contains(&count) {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"`num_last_images_to_include` must be between 1 and {MAX_EDIT_IMAGES}"
|
||||
)));
|
||||
}
|
||||
// Pathless images have no stable reference, so this bounded window may include newer
|
||||
// unrelated images. This remains best-effort until the harness provides stable refs.
|
||||
recent_images(history, count)?
|
||||
}
|
||||
(false, Some(_)) => {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"provide only one of `referenced_image_paths` or \
|
||||
`num_last_images_to_include`"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(PreparedImageRequest {
|
||||
request: ImageRequest::Edit(ImageEditRequest {
|
||||
images,
|
||||
prompt: args.prompt.clone(),
|
||||
output: args.gif.map(ImageOutput::Gif),
|
||||
background: Some(background),
|
||||
model: IMAGE_MODEL.to_string(),
|
||||
n: None,
|
||||
quality: Some(ImageQuality::Auto),
|
||||
size: Some("auto".to_string()),
|
||||
}),
|
||||
input_images,
|
||||
})
|
||||
}
|
||||
|
||||
fn recent_images(
|
||||
history: &[ResponseItem],
|
||||
count: usize,
|
||||
) -> Result<Vec<ImageReference>, FunctionCallError> {
|
||||
let mut images = Vec::with_capacity(count);
|
||||
'history: for item in history.iter().rev() {
|
||||
let mut image_references = Vec::new();
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
image_references.extend(content.iter().rev().filter_map(|item| match item {
|
||||
ContentItem::InputImage { image, .. } => Some(image.clone()),
|
||||
ContentItem::InputText { .. }
|
||||
| ContentItem::InputAudio { .. }
|
||||
| ContentItem::OutputText { .. } => None,
|
||||
}));
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
image_references.extend(output_images(output).cloned());
|
||||
}
|
||||
ResponseItem::ImageGenerationCall { result, .. } if !result.is_empty() => {
|
||||
image_references.push(ImageReference::Inline {
|
||||
image_url: format!("data:image/png;base64,{result}"),
|
||||
});
|
||||
}
|
||||
ResponseItem::AdditionalTools { .. }
|
||||
| ResponseItem::Reasoning { .. }
|
||||
| ResponseItem::AgentMessage { .. }
|
||||
| ResponseItem::LocalShellCall { .. }
|
||||
| ResponseItem::FunctionCall { .. }
|
||||
| ResponseItem::ToolSearchCall { .. }
|
||||
| ResponseItem::CustomToolCall { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
| ResponseItem::WebSearchCall { .. }
|
||||
| ResponseItem::ImageGenerationCall { .. }
|
||||
| ResponseItem::Compaction { .. }
|
||||
| ResponseItem::ConfigurationUpdate { .. }
|
||||
| ResponseItem::CompactionTrigger { .. }
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
| ResponseItem::Other => {}
|
||||
}
|
||||
for image in image_references {
|
||||
images.push(image);
|
||||
if images.len() == count {
|
||||
break 'history;
|
||||
}
|
||||
}
|
||||
}
|
||||
if images.len() != count {
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"requested the last {count} conversation images, but only {} were available",
|
||||
images.len()
|
||||
)));
|
||||
}
|
||||
images.reverse();
|
||||
Ok(images)
|
||||
}
|
||||
|
||||
/// Extracts image references from a tool output in newest-first order.
|
||||
fn output_images(output: &FunctionCallOutputPayload) -> impl Iterator<Item = &ImageReference> + '_ {
|
||||
output
|
||||
.content_items()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.rev()
|
||||
.filter_map(|item| match item {
|
||||
FunctionCallOutputContentItem::InputImage { image, .. } => Some(image),
|
||||
FunctionCallOutputContentItem::InputText { .. }
|
||||
| FunctionCallOutputContentItem::InputAudio { .. }
|
||||
| FunctionCallOutputContentItem::EncryptedContent { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn load_input_image(
|
||||
path: &AbsolutePathBuf,
|
||||
environment: &ToolEnvironment<'_>,
|
||||
) -> Result<LoadedInputImage, FunctionCallError> {
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
let bytes = environment
|
||||
.fs()
|
||||
.read_file(&path_uri, Default::default())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"unable to read referenced image at `{}`: {error}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let sha256 = format!("{:x}", Sha256::digest(&bytes));
|
||||
let image = load_for_prompt_bytes(path.as_path(), bytes, PromptImageMode::Original).map_err(
|
||||
|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"unable to process referenced image at `{}`: {error}",
|
||||
path.display()
|
||||
))
|
||||
},
|
||||
)?;
|
||||
Ok(LoadedInputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: image.into_data_url(),
|
||||
},
|
||||
identity: ImageGenerationInputImage {
|
||||
path: path.clone(),
|
||||
sha256,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses the strict model-facing arguments for an image-generation call.
|
||||
fn parse_args(call: &ToolCall<'_>) -> Result<ImagegenArgs, FunctionCallError> {
|
||||
serde_json::from_str(call.function_arguments()?)
|
||||
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
|
||||
}
|
||||
|
||||
/// Builds the namespace function schema exposed to the model.
|
||||
fn imagegen_tool_spec(gif_enabled: bool) -> ToolSpec {
|
||||
let mut schema_value = serde_json::to_value(
|
||||
SchemaSettings::draft2019_09()
|
||||
.with(|settings| settings.inline_subschemas = true)
|
||||
.into_generator()
|
||||
.into_root_schema_for::<ImagegenArgs>(),
|
||||
)
|
||||
.unwrap_or_else(|err| panic!("imagegen schema should serialize: {err}"));
|
||||
let Value::Object(ref mut schema) = schema_value else {
|
||||
unreachable!("imagegen root schema must be an object");
|
||||
};
|
||||
if !gif_enabled && let Some(Value::Object(properties)) = schema.get_mut("properties") {
|
||||
properties.remove("gif");
|
||||
}
|
||||
let mut input_schema = Map::new();
|
||||
for key in ["properties", "required", "type", "additionalProperties"] {
|
||||
if let Some(value) = schema.remove(key) {
|
||||
input_schema.insert(key.to_string(), value);
|
||||
}
|
||||
}
|
||||
ToolSpec::Namespace(ResponsesApiNamespace {
|
||||
name: IMAGE_GEN_NAMESPACE.to_string(),
|
||||
description: default_namespace_description(IMAGE_GEN_NAMESPACE),
|
||||
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
|
||||
name: IMAGEGEN_TOOL_NAME.to_string(),
|
||||
description: if gif_enabled {
|
||||
format!("{IMAGEGEN_DESCRIPTION}\n{IMAGEGEN_GIF_DESCRIPTION}")
|
||||
} else {
|
||||
IMAGEGEN_DESCRIPTION.to_string()
|
||||
},
|
||||
strict: false,
|
||||
parameters: parse_tool_input_schema(&Value::Object(input_schema))
|
||||
.unwrap_or_else(|err| panic!("imagegen input schema should parse: {err}")),
|
||||
output_schema: Some(
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"image_url": { "type": "string" },
|
||||
"output_hint": { "type": "string" }
|
||||
},
|
||||
"required": ["image_url"],
|
||||
"additionalProperties": false
|
||||
})
|
||||
.into(),
|
||||
),
|
||||
defer_loading: None,
|
||||
})],
|
||||
})
|
||||
}
|
||||
|
||||
struct GeneratedImageOutput {
|
||||
result: String,
|
||||
output_hint: Option<String>,
|
||||
}
|
||||
|
||||
impl ToolOutput for GeneratedImageOutput {
|
||||
/// Avoids copying image bytes into tool-call telemetry.
|
||||
fn log_output(&self) -> String {
|
||||
"[generated image]".to_string()
|
||||
}
|
||||
|
||||
/// Reports a completed images request as successful tool execution.
|
||||
fn success_for_logging(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns the object consumed by the code-mode `generatedImage()` helper.
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
|
||||
let mut result = Map::from_iter([(
|
||||
"image_url".to_string(),
|
||||
Value::String(format!(
|
||||
"data:{};base64,{}",
|
||||
GeneratedImageFormat::from_base64(&self.result).mime_type(),
|
||||
self.result
|
||||
)),
|
||||
)]);
|
||||
if let Some(output_hint) = &self.output_hint {
|
||||
result.insert(
|
||||
"output_hint".to_string(),
|
||||
Value::String(output_hint.clone()),
|
||||
);
|
||||
}
|
||||
Value::Object(result)
|
||||
}
|
||||
|
||||
/// Returns generated bytes and persisted-artifact context for model follow-up.
|
||||
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
|
||||
let mut content = vec![FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: format!(
|
||||
"data:{};base64,{}",
|
||||
GeneratedImageFormat::from_base64(&self.result).mime_type(),
|
||||
self.result
|
||||
),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}];
|
||||
if let Some(output_hint) = &self.output_hint {
|
||||
content.push(FunctionCallOutputContentItem::InputText {
|
||||
text: output_hint.clone(),
|
||||
});
|
||||
}
|
||||
ResponseInputItem::FunctionCallOutput {
|
||||
call_id: call_id.to_string(),
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::ContentItems(content),
|
||||
success: Some(true),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user