Skip to content

Return error when structured output is truncated due to max_tokens #427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions responses/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ func (r *ResponseService) New(ctx context.Context, body ResponseNewParams, opts
opts = append(r.Options[:], opts...)
path := "responses"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
if err != nil {
return nil, err
}

if res != nil && res.IncompleteDetails.Reason == "max_tokens" {
return nil, fmt.Errorf("structured output was truncated due to max_tokens limit (IncompleteDetails.Reason = 'max_tokens')")
}

return
}

Expand Down
33 changes: 33 additions & 0 deletions responses/response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"errors"
"os"
"strings"
"testing"

"github.com/openai/openai-go"
Expand Down Expand Up @@ -161,3 +162,35 @@ func TestResponseCancel(t *testing.T) {
t.Fatalf("err should be nil: %s", err.Error())
}
}

func TestResponseTruncatedByMaxTokens(t *testing.T) {
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := openai.NewClient(
option.WithBaseURL(baseURL),
option.WithAPIKey("My API Key"),
)

_, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
Model: shared.ResponsesModel("gpt-4o"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Tell me a long story about a dragon")},
Instructions: openai.String("Return a JSON with full story"),
MaxOutputTokens: openai.Int(5),
Temperature: openai.Float(1),
Text: responses.ResponseTextConfigParam{Format: responses.ResponseFormatTextConfigUnionParam{OfText: &shared.ResponseFormatTextParam{}}},
ParallelToolCalls: openai.Bool(false),
})

if err == nil {
t.Fatal("Expected error due to max_tokens truncation, but got nil")
}
if !strings.Contains(err.Error(), "truncated") {
t.Fatalf("Expected truncation-related error, got: %v", err)
}

}