Skip to content

openai max token change to max_completion_tokens - #1221

Merged
isamu merged 2 commits into
receptron:mainfrom
isamu:max_token
Aug 22, 2025
Merged

isamu merged 2 commits into
receptron:mainfrom
isamu:max_token

Conversation

@isamu

@isamu isamu commented Aug 21, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added max_completion_tokens to OpenAI and OpenAI Fetch agents for explicit control of completion token limits, with automatic fallback to existing max_tokens.
  • Refactor

    • Updated public input/parameter schema to use max_completion_tokens instead of max_tokens, aligning interfaces while preserving backward compatibility.
  • Tests

    • Expanded test graph data to include a max_tokens-based params entry to exercise the new parameter mapping.

@isamu
isamu requested a review from snakajima August 21, 2025 23:49
@coderabbitai

coderabbitai Bot commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds max_completion_tokens to OpenAI and OpenAI Fetch agents, passes it to the OpenAI API with fallback to max_tokens, updates public input/param schemas to max_completion_tokens, and updates tests to include params.max_tokens for an LLM node.

Changes

Cohort / File(s) Summary
OpenAI Agent updates
llm_agents/openai_agent/src/openai_agent.ts
Added optional input max_completion_tokens; runtime uses max_completion_tokens: max_completion_tokens ?? max_tokens; public agent info renamed inputs/params from max_tokens → max_completion_tokens (backward-compatible alias preserved).
OpenAI Fetch Agent updates
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts
Added optional input max_completion_tokens; request payload uses max_completion_tokens: max_completion_tokens ?? max_tokens; agent info schemas updated to use max_completion_tokens in inputs and params (deprecated max_tokens supported as fallback).
Test graph config update
llm_agents/openai_agent/tests/graphData.ts
Added params: { max_tokens: 2000 } to the llm node in graphDataOpenAIMath; inputs unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Agent as OpenAI Agent
  participant OpenAI as OpenAI API

  Caller->>Agent: inputs { ..., max_completion_tokens?, max_tokens? }
  Note over Agent: limit = max_completion_tokens ?? max_tokens
  Agent->>OpenAI: request { ..., max_completion_tokens: limit }
  OpenAI-->>Agent: response/stream
  Agent-->>Caller: result
Loading
sequenceDiagram
  autonumber
  participant Caller
  participant FetchAgent as OpenAI Fetch Agent
  participant OpenAI as OpenAI API

  Caller->>FetchAgent: inputs { url/ctx..., max_completion_tokens?, max_tokens? }
  Note over FetchAgent: limit = max_completion_tokens ?? max_tokens
  FetchAgent->>OpenAI: request { ..., max_completion_tokens: limit }
  OpenAI-->>FetchAgent: response/stream
  FetchAgent-->>Caller: result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I twitch my ears at token bounds anew,
A hop, a skip—completion limits true.
Old tracks remain for paws to follow on,
While fresher trails in schemas now are drawn.
With 2k snacks or more within my pack,
I nibble prompts—then bounce right back! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 3

🧹 Nitpick comments (3)
llm_agents/openai_agent/tests/graphData.ts (1)

12-14: Good backward-compat coverage; add a companion case for the new field.

Using params.max_tokens here exercises the fallback path. Please also add a second fixture (or a table-driven variant) that sets params.max_completion_tokens to verify the new code path and the precedence (that max_completion_tokens wins when both are present). This aligns with OpenAI’s current guidance that reasoning models prefer max_completion_tokens, while older models still accept max_tokens. (help.openai.com)

Example additional fixture (outside this hunk):

export const graphDataOpenAIMathWithMaxCompletion = {
  version: 0.5,
  nodes: {
    inputData: { value: "hello, let me know the answer 1 + 1" },
    llm: {
      agent: "openAIAgent",
      inputs: { prompt: ":inputData" },
      params: { max_completion_tokens: 2000 },
    },
  },
};
llm_agents/openai_agent/src/openai_agent.ts (1)

128-131: Destructuring looks right and preserves precedence.

Reading both max_completion_tokens and max_tokens (with the former taking precedence) is the right trade-off while the ecosystem transitions. (help.openai.com)

Consider a short code comment noting “max_completion_tokens overrides max_tokens if both are provided” to avoid ambiguity for future readers.

llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (1)

118-122: HTTP payload uses the new param with fallback — consider an optional dual-send for older stacks.

Sending max_completion_tokens: max_completion_tokens ?? max_tokens aligns with current API guidance; older models continue to accept max_tokens while reasoning models require or prefer max_completion_tokens. (help.openai.com, community.openai.com)

Only if you encounter compatibility issues with very old deployments, you can include max_tokens when only that value is provided:

   const chatParams = {
     model: params.model || "gpt-4o",
     messages: messagesCopy as unknown as OpenAI.ChatCompletionMessageParam[],
     tools,
     tool_choice,
     max_completion_tokens: max_completion_tokens ?? max_tokens,
+    ...(max_completion_tokens == null && max_tokens != null ? { max_tokens } : {}),
     temperature: temperature ?? 0.7,
     stream: !!stream,
     response_format,
   };
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8a68cd1 and c11cff7.

📒 Files selected for processing (3)
  • llm_agents/openai_agent/src/openai_agent.ts (5 hunks)
  • llm_agents/openai_agent/tests/graphData.ts (1 hunks)
  • llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build (24.x)
  • GitHub Check: build (22.x)
🔇 Additional comments (5)
llm_agents/openai_agent/src/openai_agent.ts (3)

22-22: Type surface updated correctly.

Adding max_completion_tokens?: number keeps the public type in sync with the API evolution and allows you to keep max_tokens for back-compat in user inputs. (help.openai.com)


181-183: Verify OpenAI SDK Type Definitions for max_completion_tokens

I ran searches in the sandbox but didn’t find any TypeScript declaration files under node_modules/openai (likely because dependencies aren’t installed here). Please manually confirm in your local setup that your installed OpenAI SDK (v^5.12.2 per llm_agents/openai_agent/package.json) exports max_completion_tokens or maxCompletionTokens on ChatCompletionCreateParams. If it doesn’t, apply the optional fallback to include max_tokens only when max_completion_tokens is undefined:

 const chatParams: OpenAI.ChatCompletionCreateParams = {
   model: modelName,
   messages: messagesCopy as unknown as OpenAI.ChatCompletionMessageParam[],
   tools,
   tool_choice,
   max_completion_tokens: max_completion_tokens ?? max_tokens,
+  // Optional safety for older SDKs/models:
+  ...(max_completion_tokens == null && max_tokens != null ? { max_tokens } : {}),
   response_format,
 };

• Open your local node_modules/openai/dist/*.d.ts (or equivalent) and search for:

  • max_completion_tokens
  • maxCompletionTokens
  • fallback field max_tokens within ChatCompletionCreateParams

• If those fields aren’t defined, add the above fallback.
• Otherwise, no changes are needed.


300-300: No backward-compatibility risk: unknown properties are allowed by default
The OpenAI agent’s JSON schemas don’t set additionalProperties: false, so any extra field—including max_tokens—will pass validation and be forwarded to the agent. Moreover, the code explicitly destructures and falls back on max_tokens when max_completion_tokens is absent, so existing graphs continue to work without a schema alias.

Likely an incorrect or invalid review comment.

llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)

11-11: Type surface updated correctly.

Adding max_completion_tokens?: number to OpenAIInputs keeps parity with the server parameter and helps future-proof callers. (help.openai.com)


65-68: Destructuring includes both fields with clear precedence.

Reading both max_completion_tokens and max_tokens and letting the new one win is the right approach during migration. (help.openai.com)

tools: { type: "object" },
tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
max_tokens: { type: "number" },
max_completion_tokens: { type: "number" },

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.

🛠️ Refactor suggestion

Mirror the alias in params schema as well.

For parity with inputs, keep params.max_tokens as a deprecated alias to avoid surprising users whose graphs set it there. (help.openai.com)

Apply analogous change under params.properties:

   params: {
     type: "object",
     properties: {
       model: { type: "string" },
       system: { type: "string" },
       tools: { type: "object" },
       tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
       max_completion_tokens: { type: "number" },
+      // Deprecated alias for compatibility with older graphs
+      max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
       verbose: { type: "boolean" },
       temperature: { type: "number" },
       baseURL: { type: "string" },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
max_completion_tokens: { type: "number" },
params: {
type: "object",
properties: {
model: { type: "string" },
system: { type: "string" },
tools: { type: "object" },
tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
max_completion_tokens: { type: "number" },
// Deprecated alias for compatibility with older graphs
max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
verbose: { type: "boolean" },
temperature: { type: "number" },
baseURL: { type: "string" },
🤖 Prompt for AI Agents
In llm_agents/openai_agent/src/openai_agent.ts around line 412, the params
schema defines max_completion_tokens but does not include the deprecated alias
params.max_tokens; add a params.properties entry for max_tokens that mirrors
max_completion_tokens (type "number") and mark it as a deprecated/alias field in
its description so existing graphs using params.max_tokens continue to work
while the canonical field remains params.max_completion_tokens.

tools: { type: "object" },
tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
max_tokens: { type: "number" },
max_completion_tokens: { type: "number" },

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.

🛠️ Refactor suggestion

Mirror the alias in params schema as well.

Same rationale as inputs: reduce friction for callers still using max_tokens. (help.openai.com)

Patch (outside this one line):

   params: {
     type: "object",
     properties: {
       model: { type: "string" },
       system: { type: "string" },
       tools: { type: "object" },
       tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
       max_completion_tokens: { type: "number" },
+      // Deprecated alias for compatibility with older graphs
+      max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
       verbose: { type: "boolean" },
       temperature: { type: "number" },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
max_completion_tokens: { type: "number" },
params: {
type: "object",
properties: {
model: { type: "string" },
system: { type: "string" },
tools: { type: "object" },
tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
max_completion_tokens: { type: "number" },
// Deprecated alias for compatibility with older graphs
max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
verbose: { type: "boolean" },
temperature: { type: "number" },
// …other properties…
}
}
🤖 Prompt for AI Agents
In llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts around line 365, the
params schema defines max_completion_tokens but doesn't provide the alias
max_tokens; add a schema entry for max_tokens that mirrors max_completion_tokens
(same type and validation) and ensure incoming max_tokens is mapped/accepted
equivalently to max_completion_tokens so callers using max_tokens continue to
work without breaking changes.

@isamu
isamu merged commit cc30efd into receptron:main Aug 22, 2025

@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: 0

♻️ Duplicate comments (2)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)

246-271: Keep a deprecated alias in the inputs schema to avoid rejecting existing graphs.

Schema validation will fail for callers still sending max_tokens even though runtime supports it. Add a deprecated alias to the schema.

       tool_choice: {
         anyOf: [{ type: "array" }, { type: "object" }],
       },
-      max_completion_tokens: { type: "number" },
+      max_completion_tokens: { type: "number" },
+      // Deprecated alias for compatibility with older graphs
+      max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
       verbose: { type: "boolean" },

360-374: Mirror the alias in params schema as well.

Same reasoning as inputs schema: accept max_tokens but mark it deprecated to avoid breaking existing graphs.

       tool_choice: { anyOf: [{ type: "array" }, { type: "object" }] },
-      max_completion_tokens: { type: "number" },
+      max_completion_tokens: { type: "number" },
+      // Deprecated alias for compatibility with older graphs
+      max_tokens: { type: "number", description: "Deprecated. Use max_completion_tokens." },
       verbose: { type: "boolean" },
🧹 Nitpick comments (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (1)

10-12: Prefer JSDoc deprecation to drive IDE hints.

You already kept the alias (good). Replace the inline comment with a JSDoc @deprecated so editors and type checkers surface deprecation warnings.

-  // Deprecated alias for compatibility with older graphs
-  max_tokens?: number;
+  /** @deprecated Use max_completion_tokens. Kept for compatibility with older graphs. */
+  max_tokens?: number;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c11cff7 and b0b1caf.

📒 Files selected for processing (2)
  • llm_agents/openai_agent/src/openai_agent.ts (5 hunks)
  • llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • llm_agents/openai_agent/src/openai_agent.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build (22.x)
  • GitHub Check: build (24.x)
🔇 Additional comments (2)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)

66-69: Backward-compatible destructuring looks good.

Pulling both max_completion_tokens and the legacy max_tokens from the merged inputs/params maintains flexibility and preserves the desired precedence (namedInputs override params). No issues.


114-123: Prefer conditional max_completion_tokens / max_tokens for broad model support

To ensure we don’t accidentally break older chat-completion models (e.g. gpt-3.5-turbo) that only recognize max_tokens, emit whichever parameter is appropriate instead of always sending max_completion_tokens. For example:

   const chatParams = {
     model: params.model || "gpt-4o",
     messages: messagesCopy as unknown as OpenAI.ChatCompletionMessageParam[],
     tools,
     tool_choice,
-    max_completion_tokens: max_completion_tokens ?? max_tokens,
+    ...(typeof max_completion_tokens === "number"
+      ? { max_completion_tokens }
+      : typeof max_tokens === "number"
+      ? { max_tokens }
+      : {}),
     temperature: temperature ?? 0.7,
     stream: !!stream,
     response_format,
   };

• Older chat models will reject unrecognized keys like max_completion_tokens.
• Newer/reasoning models prefer max_completion_tokens.
• A small unit or integration test could verify that, given different inputs, the correct wire param is emitted.

Please review your client usage to confirm that this change covers all downstream calls.

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.

2 participants