Skip to content

update openai - #1190

Merged
isamu merged 2 commits into
receptron:mainfrom
isamu:openAI5.12.2
Aug 12, 2025
Merged

isamu merged 2 commits into
receptron:mainfrom
isamu:openAI5.12.2

Conversation

@isamu

@isamu isamu commented Aug 11, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes

    • Safer handling of non-function tool calls to prevent errors and improve agent reliability during complex interactions.
  • Chores

    • Updated OpenAI client dependency to a newer minor version for compatibility and stability.

@coderabbitai

coderabbitai Bot commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a type guard for tool_call handling across OpenAI agent converters so non-function tool calls yield an empty name and empty arguments object instead of causing undefined access or JSON parse errors. Also updates the OpenAI SDK dependency to ^5.12.2. No exported/public API changes.

Changes

Cohort / File(s) Summary
OpenAI agent tool-call handling
llm_agents/openai_agent/src/openai_agent.ts, llm_agents/openai_agent/lib/openai_agent.js, llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts
Guard tool_call by type; set name to "" and arguments to {} when type !== "function"; parse arguments only for function-type calls. Add an inline comment annotating expected function tool-call shape.
Dependency update
llm_agents/openai_agent/package.json
Bump dependencies.openai from ^5.11.0 to ^5.12.2.

Sequence Diagram(s)

sequenceDiagram
    participant Client as OpenAI response
    participant Conv as convToolCall / convertOpenAIChatCompletion
    participant Parser as JSON.parse

    Client->>Conv: returns message with tool_call (type + function?)
    alt tool_call.type == "function"
        Conv->>Conv: name = tool_call.function.name
        Conv->>Parser: parse(tool_call.function.arguments)
        Parser-->>Conv: arguments object
    else non-function tool_call
        Conv->>Conv: name = ""
        Conv->>Parser: parse("{}")
        Parser-->>Conv: {}
    end
    Conv-->>Client: sanitized tool object (name, arguments)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I twitch my ears at guarded calls,
No more tripping over undefined walls.
Empty paws for non-functions, neat—
Parse-safe burrows under my feet.
With fresher carrots (5.12.2) in stash,
I hop through tools in one clean dash. 🐇✨

✨ 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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: 1

🔭 Outside diff range comments (4)
llm_agents/openai_agent/lib/openai_agent.js (2)

17-22: Harden failure path and logging for argument parsing

Return an empty object on parse failure to keep the output shape stable, and log as an error with context.

-            try {
-                return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}");
-            }
-            catch (__e) {
-                console.log(__e);
-                return undefined;
-            }
+            try {
+                return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}");
+            }
+            catch (__e) {
+                console.error("Failed to parse tool_call.arguments", { id: tool_call.id, type: tool_call.type, error: __e });
+                return {};
+            }

55-61: Unprotected JSON.parse may throw when response_format is set

If text is not valid JSON (model outputs plain text), this will throw and abort the call path.

-        if (maybeResponseFormat && text) {
-            const parsed = JSON.parse(text);
-            if (typeof parsed === "object" && parsed !== null) {
-                return parsed;
-            }
-        }
+        if (maybeResponseFormat && text) {
+            try {
+                const parsed = JSON.parse(text);
+                if (typeof parsed === "object" && parsed !== null) {
+                    return parsed;
+                }
+            } catch (e) {
+                // Non-JSON content; ignore and fall through.
+            }
+        }
llm_agents/openai_agent/src/openai_agent.ts (2)

53-60: Stabilize error handling: prefer {} over undefined and improve logging

Keep the return shape stable and log with more context.

   arguments: (() => {
     try {
-        return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}");
+      return JSON.parse(tool_call.type === "function" ? tool_call.function.arguments : "{}");
     } catch (__e) {
-      console.log(__e);
-      return undefined;
+      console.error("Failed to parse tool_call.arguments", { id: tool_call.id, type: tool_call.type, error: __e });
+      return {};
     }
   })(),

103-111: Unprotected JSON.parse on text when response_format is requested

This can throw if the model returns non-JSON text.

-  const responseFormat = (() => {
-    if (maybeResponseFormat && text) {
-      const parsed = JSON.parse(text);
-      if (typeof parsed === "object" && parsed !== null) {
-        return parsed;
-      }
-    }
-    return null;
-  })();
+  const responseFormat = (() => {
+    if (maybeResponseFormat && text) {
+      try {
+        const parsed = JSON.parse(text);
+        if (typeof parsed === "object" && parsed !== null) {
+          return parsed;
+        }
+      } catch {
+        // Not JSON; ignore.
+      }
+    }
+    return null;
+  })();
🧹 Nitpick comments (4)
llm_agents/openai_agent/lib/openai_agent.js (2)

11-11: Nit: clarify union type in comment

Consider noting the full union (ChatCompletionMessageToolCall) and that only the “function” variant carries .function.*. Helps context when reading the guard.


30-38: Variable shadowing of tool_calls can confuse maintenance

Outer tool_calls holds converted calls while inner destructuring reuses the same name for the raw OpenAI shape. Consider renaming the outer to convertedToolCalls for clarity.

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

48-49: Nit: expand the comment to reference the union

Add that tool_call is OpenAI.Chat.Completions.ChatCompletionMessageToolCall and only the “function” variant exposes .function.*.


75-90: Avoid shadowing tool_calls

The local tool_calls (converted) and the destructured newMessage.tool_calls (raw) share the same name. Rename the converted one to convertedToolCalls to reduce confusion.

-  const tool_calls = functionResponses.map(convToolCall);
-  const tool = tool_calls && tool_calls.length > 0 ? tool_calls[0] : undefined;
+  const convertedToolCalls = functionResponses.map(convToolCall);
+  const tool = convertedToolCalls && convertedToolCalls.length > 0 ? convertedToolCalls[0] : undefined;
@@
   return {
     ...response,
     text,
     tool,
-    tool_calls,
+    tool_calls: convertedToolCalls,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b658ad0 and dbf629c.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • llm_agents/openai_agent/lib/openai_agent.js (1 hunks)
  • llm_agents/openai_agent/package.json (1 hunks)
  • llm_agents/openai_agent/src/openai_agent.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
llm_agents/openai_agent/src/openai_agent.ts (1)
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)
  • tool_call (10-10)
llm_agents/openai_agent/lib/openai_agent.js (1)
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)
  • tool_call (10-10)
🔇 Additional comments (3)
llm_agents/openai_agent/package.json (1)

32-33: Upgrade to openai ^5.12.2 looks good

Matches the code changes that guard tool_call.function access. No API surface changes detected.

llm_agents/openai_agent/lib/openai_agent.js (1)

14-18: Good guard against non-function tool calls

This prevents undefined access and JSON parse errors when tool_call.type !== "function".

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

52-56: Type guard is correct and prevents crashes on non-function tool calls

Solid change; matches the SDK’s union shape and avoids undefined access and bad JSON.parse.

Comment on lines +32 to 33
"openai": "^5.12.2"
},

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.

💡 Verification agent

🧩 Analysis chain

Verify lockfile update and runtime compatibility

Ensure yarn.lock/package-lock.json is updated and that all packages using openai are aligned on ^5.12.x. openai v5 requires Node 18+. Confirm engines across workspace.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "OpenAI dependency versions across the repo:"
fd -t f package.json | while read -r f; do
  ver="$(jq -r '.dependencies.openai // ""' "$f")"
  if [ -n "$ver" ]; then
    echo "$f => $ver"
  fi
done

echo
echo "Node engines across the repo (if defined):"
fd -t f package.json | while read -r f; do
  eng="$(jq -r '.engines.node // ""' "$f")"
  if [ -n "$eng" ]; then
    echo "$f => engines.node=$eng"
  fi
done

Length of output: 7590


Add Node 18+ engine requirement and update lockfile

  • openai@^5.12.2 is only used in llm_agents/openai_agent/package.json—no version alignment issues.
  • No engines.node fields found; openai v5 requires Node 18+, so add to your workspace (e.g. root package.json and/or this package):
     {
       …
    +  "engines": {
    +    "node": ">=18"
    +  },
       "dependencies": {
         "openai": "^5.12.2"
       }
     }
  • After installing/upgrading, commit the updated yarn.lock or package-lock.json.
📝 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
"openai": "^5.12.2"
},
"engines": {
"node": ">=18"
},
"dependencies": {
"openai": "^5.12.2"
},
🤖 Prompt for AI Agents
In llm_agents/openai_agent/package.json around lines 32 to 33, add an
engines.node field requiring Node 18+ and update the repo lockfile: modify this
package.json (or root package.json) to include "engines": {"node": ">=18"} so it
aligns with openai@^5.12.2 requirements, then run a fresh install (npm install
or yarn install) to regenerate and commit the updated package-lock.json or
yarn.lock file alongside the package.json change.

@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

🔭 Outside diff range comments (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (1)

159-161: Fix streaming chunk concatenation order (can corrupt JSON framing).

New chunks are prepended to the buffer, reversing order and risking JSON parse failures across chunk boundaries. Append instead.

Apply this diff:

-      text_buffer = text + text_buffer;
+      text_buffer = text_buffer + text;
🧹 Nitpick comments (2)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (2)

164-176: Streaming path ignores tool_calls deltas.

Only delta.content is accumulated. If the assistant streams tool_calls, they’ll be dropped and tool won’t be populated, diverging from non-streaming behavior.

Minimal approach: detect and buffer tool_calls deltas alongside content, then surface them to convertOpenAIChatCompletion. I can draft a small helper to merge streamed tool_calls if you want.


134-139: Improve error messages with status/body for easier debugging.

Errors are generic. Include status and response body excerpt.

Example:

if (!stream) {
  if (response.ok) {
    const result = await response.json();
    return convertOpenAIChatCompletion(result, messagesCopy);
  }
  const errText = await response.text().catch(() => "");
  throw new Error(`OPENAI API Error: ${response.status} ${response.statusText} ${errText?.slice(0, 500)}`);
}

// streaming
if (response.status !== 200 || !reader) {
  const errText = await response.text().catch(() => "");
  throw new Error(`Request failed: ${response.status} ${response.statusText} ${errText?.slice(0, 500)}`);
}

Also applies to: 144-146

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dbf629c and a9a0f72.

📒 Files selected for processing (1)
  • llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
llm_agents/openai_fetch_agent/src/openai_fetch_agent.ts (4)
llm_agents/openai_fetch_agent/lib/bundle.cjs.js (1)
  • functionResponse (72-72)
llm_agents/openai_fetch_agent/lib/bundle.esm.js (1)
  • functionResponse (70-70)
llm_agents/openai_fetch_agent/lib/bundle.umd.js (1)
  • functionResponse (74-74)
llm_agents/openai_fetch_agent/lib/openai_fetch_agent.js (1)
  • functionResponse (9-9)
⏰ 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)

35-39: Solid type-guard for tool_calls; prevents undefined access and JSON.parse errors.

The guard on tool_call.type correctly avoids accessing function fields for non-function calls and defaults arguments to "{}".


1-1: Verify OpenAI SDK v5.12.2 type names; prefer importing types directly.

With SDK v5.x, top-level namespace type aliases can differ. Importing types from "openai/resources/chat/completions" is safer.

Suggested change (types only):

import OpenAI from "openai";
import type { ChatCompletion, ChatCompletionMessageParam } from "openai/resources/chat/completions";

// ...
const convertOpenAIChatCompletion = (response: ChatCompletion, messages: ChatCompletionMessageParam[]) => { /* ... */ }

Please confirm the current build passes type-checking with OpenAI ^5.12.2.

Also applies to: 25-25

@isamu
isamu merged commit 072e772 into receptron:main Aug 12, 2025
This was referenced Aug 13, 2025
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