Skip to content

fix(codex): inline remote Responses input files - #6522

Closed
builderHelen wants to merge 1 commit into
QuantumNous:mainfrom
builderHelen:fix/lm-2750-codex-remote-input-files
Closed

builderHelen wants to merge 1 commit into
QuantumNous:mainfrom
builderHelen:fix/lm-2750-codex-remote-input-files

Conversation

@builderHelen

@builderHelen builderHelen commented Jul 29, 2026 •

Copy link
Copy Markdown

📝 变更描述 / Description

Codex Responses can reject remote input_file.file_url values when the URL requires signed access or cannot be fetched by the upstream. The Codex adaptor now loads remote input files through the existing file-source cache and sends them as file_data data URIs. Inline files and image inputs are unchanged.

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

🔗 关联任务 / Related Issue

  • Internal tracking: LM-2750

✅ 提交前检查项 / Checklist

  • 人工确认
  • 深度理解
  • 范围聚焦
  • 本地验证
  • 安全合规

📸 运行证明 / Proof of Work

  • go test ./relay/channel/codex passes.
  • A Responses request containing a PDF file_data completes successfully through the Codex channel.
  • Tests cover remote URL rewriting, filename preservation, inline-file passthrough, and loader errors.

Summary by CodeRabbit

  • New Features

    • Remote input files are now embedded directly into requests as base64 data, enabling more reliable file processing.
    • File names are automatically preserved or derived when remote file references are converted.
    • Existing inline file data remains unchanged.
  • Bug Fixes

    • File loading and conversion errors are now surfaced instead of silently ignored.
  • Tests

    • Added coverage for remote file conversion, inline file preservation, and error handling.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Codex request conversion now recursively rewrites remote input_file URLs into embedded base64 data URLs, derives missing filenames, preserves inline files, and propagates loading or conversion errors. Unit tests cover rewriting, preservation, and error propagation.

Changes

Codex input file conversion

Layer / File(s) Summary
Remote input file rewriting
relay/channel/codex/input_file.go, relay/channel/codex/input_file_test.go
Recursive JSON rewriting loads remote files, replaces file_url with file_data, derives missing filenames, preserves inline files, and tests loader errors.
Responses request integration
relay/channel/codex/adaptor.go
Request conversion embeds loaded content as normalized MIME-typed base64 data URLs before existing response handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ConvertOpenAIResponsesRequest
  participant rewriteRemoteInputFiles
  participant service.LoadFileSource

  Client->>ConvertOpenAIResponsesRequest: submit input with file_url
  ConvertOpenAIResponsesRequest->>rewriteRemoteInputFiles: rewrite request.Input
  rewriteRemoteInputFiles->>service.LoadFileSource: load remote file
  service.LoadFileSource-->>rewriteRemoteInputFiles: file content and MIME type
  rewriteRemoteInputFiles-->>ConvertOpenAIResponsesRequest: rewritten input
  ConvertOpenAIResponsesRequest-->>Client: converted request
Loading

Poem

I’m a rabbit with a file in my pack,
Remote URLs become data tracks.
Base64 carrots, MIME tags bright,
Filenames hop into place just right.
Inline files stay snug and true—
Errors come hopping back to you.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: converting remote Responses input files into inline data.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/lm-2750-codex-remote-input-files
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@builderHelen

Copy link
Copy Markdown
Author

Closing because the deployment owner requires this compatibility fix to remain outside NewAPI. The implementation will move to the caller service.

@builderHelen
builderHelen deleted the fix/lm-2750-codex-remote-input-files branch July 29, 2026 09:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@relay/channel/codex/input_file_test.go`:
- Around line 1-59: Update TestRewriteRemoteInputFiles and
TestRewriteRemoteInputFilesPreservesInlineAndPropagatesLoadErrors to use
testify/require for setup and fatal assertions instead of t.Fatalf, including
unmarshalling and error checks. Add the required testify/require import while
preserving the existing test coverage and non-fatal assertion behavior.

In `@relay/channel/codex/input_file.go`:
- Around line 3-9: Update rewriteRemoteInputFiles to use the repository’s
common.Marshal and common.Unmarshal wrappers for both serialization operations,
matching the convention in adaptor.go. Remove the direct encoding/json import
and add the appropriate common package reference while preserving the existing
input-rewrite behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c98c06e9-0bbf-4f46-a10d-3612701986c1

📥 Commits

Reviewing files that changed from the base of the PR and between cb4c8c0 and 9205600.

📒 Files selected for processing (3)
  • relay/channel/codex/adaptor.go
  • relay/channel/codex/input_file.go
  • relay/channel/codex/input_file_test.go

Comment on lines +1 to +59
package codex

import (
"encoding/json"
"errors"
"testing"
)

func TestRewriteRemoteInputFiles(t *testing.T) {
input := json.RawMessage(`[{"role":"user","content":[{"type":"input_text","text":"summarize"},{"type":"input_file","file_url":"https://files.example.com/attachments/47/file.pdf?verify=secret"}]}]`)

rewritten, err := rewriteRemoteInputFiles(input, func(fileURL string) (string, error) {
if fileURL != "https://files.example.com/attachments/47/file.pdf?verify=secret" {
t.Fatalf("loader URL = %q", fileURL)
}
return "data:application/pdf;base64,JVBERi0=", nil
})
if err != nil {
t.Fatalf("rewriteRemoteInputFiles() error = %v", err)
}

var decoded []map[string]any
if err := json.Unmarshal(rewritten, &decoded); err != nil {
t.Fatalf("unmarshal rewritten input: %v", err)
}
content := decoded[0]["content"].([]any)
file := content[1].(map[string]any)
if _, exists := file["file_url"]; exists {
t.Fatalf("rewritten input still contains file_url: %#v", file)
}
if file["file_data"] != "data:application/pdf;base64,JVBERi0=" {
t.Fatalf("file_data = %#v", file["file_data"])
}
if file["filename"] != "file.pdf" {
t.Fatalf("filename = %#v, want URL basename", file["filename"])
}
}

func TestRewriteRemoteInputFilesPreservesInlineAndPropagatesLoadErrors(t *testing.T) {
inline := json.RawMessage(`[{"role":"user","content":[{"type":"input_file","filename":"report.pdf","file_data":"data:application/pdf;base64,JVBERi0="}]}]`)
rewritten, err := rewriteRemoteInputFiles(inline, func(string) (string, error) {
t.Fatal("inline file must not invoke loader")
return "", nil
})
if err != nil {
t.Fatalf("inline rewrite error = %v", err)
}
if string(rewritten) != string(inline) {
t.Fatalf("inline input changed: %s", rewritten)
}

wantErr := errors.New("download failed")
_, err = rewriteRemoteInputFiles(json.RawMessage(`[{"type":"input_file","file_url":"https://files.example.com/report.pdf"}]`), func(string) (string, error) {
return "", wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("rewrite error = %v, want %v", err, wantErr)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Use testify/require for fatal assertions in this new test file.

All assertions here use t.Fatalf; per repo guidelines, new backend tests must use testify/require for setup/fatal checks (and testify/assert for non-fatal ones).

♻️ Proposed fix (representative diff)
 import (
 	"encoding/json"
 	"errors"
 	"testing"
+
+	"github.com/stretchr/testify/require"
 )

 func TestRewriteRemoteInputFiles(t *testing.T) {
 	input := json.RawMessage(`...`)

 	rewritten, err := rewriteRemoteInputFiles(input, func(fileURL string) (string, error) {
-		if fileURL != "https://files.example.com/attachments/47/file.pdf?verify=secret" {
-			t.Fatalf("loader URL = %q", fileURL)
-		}
+		require.Equal(t, "https://files.example.com/attachments/47/file.pdf?verify=secret", fileURL)
 		return "data:application/pdf;base64,JVBERi0=", nil
 	})
-	if err != nil {
-		t.Fatalf("rewriteRemoteInputFiles() error = %v", err)
-	}
+	require.NoError(t, err)

 	var decoded []map[string]any
-	if err := json.Unmarshal(rewritten, &decoded); err != nil {
-		t.Fatalf("unmarshal rewritten input: %v", err)
-	}
+	require.NoError(t, json.Unmarshal(rewritten, &decoded))
 	content := decoded[0]["content"].([]any)
 	file := content[1].(map[string]any)
-	if _, exists := file["file_url"]; exists {
-		t.Fatalf("rewritten input still contains file_url: %#v", file)
-	}
-	if file["file_data"] != "data:application/pdf;base64,JVBERi0=" {
-		t.Fatalf("file_data = %#v", file["file_data"])
-	}
-	if file["filename"] != "file.pdf" {
-		t.Fatalf("filename = %#v, want URL basename", file["filename"])
-	}
+	_, hasFileURL := file["file_url"]
+	require.False(t, hasFileURL, "rewritten input still contains file_url")
+	require.Equal(t, "data:application/pdf;base64,JVBERi0=", file["file_data"])
+	require.Equal(t, "file.pdf", file["filename"])
 }

Apply the same pattern to TestRewriteRemoteInputFilesPreservesInlineAndPropagatesLoadErrors.

As per coding guidelines, "New or substantially rewritten Go backend tests must use testify/require for setup and fatal assertions and testify/assert for non-fatal checks."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/codex/input_file_test.go` around lines 1 - 59, Update
TestRewriteRemoteInputFiles and
TestRewriteRemoteInputFilesPreservesInlineAndPropagatesLoadErrors to use
testify/require for setup and fatal assertions instead of t.Fatalf, including
unmarshalling and error checks. Add the required testify/require import while
preserving the existing test coverage and non-fatal assertion behavior.

Source: Coding guidelines

Comment on lines +3 to +9
import (
"encoding/json"
"fmt"
"net/url"
"path"
"strings"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Use common/json.go wrappers instead of encoding/json directly.

rewriteRemoteInputFiles calls json.Unmarshal (line 19) and json.Marshal (line 30) directly. The repo's adaptor.go already uses common.Marshal/common.Unmarshal for this exact kind of business-logic serialization; this new file should follow the same convention.

♻️ Proposed fix
 import (
-	"encoding/json"
 	"fmt"
 	"net/url"
 	"path"
 	"strings"
+
+	"github.com/QuantumNous/new-api/common"
 )
@@
-	var value any
-	if err := json.Unmarshal(input, &value); err != nil {
+	var value any
+	if err := common.Unmarshal(input, &value); err != nil {
 		return nil, fmt.Errorf("decode responses input: %w", err)
 	}
@@
-	rewritten, err := json.Marshal(value)
+	rewritten, err := common.Marshal(value)
 	if err != nil {
 		return nil, fmt.Errorf("encode responses input: %w", err)
 	}

As per coding guidelines, "All JSON marshal and unmarshal operations in business code must use the wrappers in common/json.go; do not directly call encoding/json operations."

Also applies to: 13-35

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/codex/input_file.go` around lines 3 - 9, Update
rewriteRemoteInputFiles to use the repository’s common.Marshal and
common.Unmarshal wrappers for both serialization operations, matching the
convention in adaptor.go. Remove the direct encoding/json import and add the
appropriate common package reference while preserving the existing input-rewrite
behavior.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant