Skip to content
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

openai[minor],core[minor]: Add support for passing strict in openai tools #13

Open
wants to merge 2 commits into
base: cloned_main_c5fb8
Choose a base branch
from

Conversation

local-dev-korbit-ai-mentor[bot]
Copy link

@local-dev-korbit-ai-mentor local-dev-korbit-ai-mentor bot commented Aug 15, 2024

Will require bumping the min core verison on openai

Description by Korbit AI

Note

This feature is in early access. You can enable or disable it in the Korbit Console.

What change is being made?

Add support for passing a strict parameter in OpenAI tools to enforce strict schema adherence when generating function calls.

Why are these changes being made?

This change allows users to ensure that the model output strictly follows the defined JSON Schema, which is particularly useful for structured outputs. The default behavior is enabled for models starting with "gpt-". This enhancement improves the reliability and predictability of function calls in OpenAI tools.

Summary by CodeRabbit

  • New Features

    • Introduced a strict option for enhanced control over function call adherence to schemas.
    • Added a supportsStrictToolCalling property to improve configurability of tool interactions.
    • Enhanced ChatOpenAI class to support strict adherence to JSON Schema during tool calling.
  • Bug Fixes

    • Updated dependencies to incorporate improvements and potential bug fixes from the openai library.
  • Tests

    • Added comprehensive unit tests for the strict tool calling functionality in the ChatOpenAI class.
    • Improved testing framework setup for enhanced reliability and readability.

Copy link
Author

Clone of the PR langchain-ai/langchainjs#6418

Copy link

korbit-ai bot commented Aug 15, 2024

My review is in progress 📖 - I will have feedback for you in a few minutes!

Copy link

coderabbitai bot commented Aug 15, 2024

Walkthrough

The recent changes introduce a new strict property across various interfaces and functions within the LangChain framework, enhancing control over function calls and tool interactions. The strict property ensures that model outputs adhere to JSON Schema specifications, providing better validation and error handling. Additionally, updates to the ChatOpenAI class and related tests improve the robustness of tool calling, making interactions more predictable and reliable.

Changes

File Path Change Summary
langchain-core/src/language_models/base.ts Added an optional strict property to the FunctionDefinition interface for precise schema adherence.
langchain-core/src/utils/function_calling.ts Enhanced convertToOpenAITool function to accept a fields parameter for strict adherence control.
libs/langchain-openai/package.json Updated OpenAI dependency version from ^4.49.1 to ^4.55.0.
libs/langchain-openai/src/chat_models.ts Added strict to ChatOpenAICallOptions and updated constructor logic to support strict tool calling.
libs/langchain-openai/src/tests/chat_models.test.ts Introduced unit tests for strict tool calling in the ChatOpenAI class.
libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts Added Jest imports to enhance testing capabilities for structured output tests.
libs/langchain-openai/src/types.ts Introduced supportsStrictToolCalling property to the OpenAIChatInput interface to indicate support for strict mode.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ChatOpenAI
    participant Tool

    User->>ChatOpenAI: Call with strict=true
    ChatOpenAI->>Tool: Invoke tool with strict adherence
    Tool-->>ChatOpenAI: Return output
    ChatOpenAI-->>User: Return structured output
Loading

Poem

In a world of code, hopping with glee,
A new strict property adds clarity! 🐇✨
With tools and functions, all snug and tight,
Outputs now sparkle, oh what a sight!
So let's celebrate with joy in our hearts,
For every change here, a new adventure starts! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

Copy link

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

I have reviewed your code and found 3 potential issues.

}

return tool as ToolDefinition;
Copy link

Choose a reason for hiding this comment

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

category Functionality severity potentially major

The convertToOpenAITool function is not returning the modified toolDef object. Instead, it's returning the original tool parameter, which means any modifications made to toolDef (including setting the strict field) are lost. To fix this, replace the last line return tool as ToolDefinition; with return toolDef;.

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

Comment on lines +58 to +59
// This will fail since we're not returning a valid response in our mocked fetch function.
await expect(modelWithTools.invoke("What's the weather like?")).rejects.toThrow();
Copy link

Choose a reason for hiding this comment

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

category Functionality severity potentially major

The test cases are currently expecting the modelWithTools.invoke() call to throw an error, but the mock implementation is returning a successful response. This mismatch could lead to false positives in your tests. Consider either:

  1. Modifying the mock to return an error response:
mockFetch.mockRejectedValue(new Error('Mock API error'));
  1. Or, if the intention is to test successful responses, update the test expectation:
await expect(modelWithTools.invoke("What's the weather like?")).resolves.not.toThrow();

Additionally, add more specific error assertions to ensure you're catching the expected errors. This will make your tests more robust and informative.

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

Comment on lines +159 to +164
/**
* Whether the model supports the 'strict' argument when passing in tools.
* Defaults to `true` if `modelName`/`model` starts with 'gpt-' otherwise
* defaults to `false`.
*/
supportsStrictToolCalling?: boolean;
Copy link

Choose a reason for hiding this comment

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

category Functionality

The new supportsStrictToolCalling property has been added, which is great for extending functionality. However, it would be beneficial to add a comment explaining when a user might want to override the default behavior. For example, you could add a note like: 'Set this to true for models that support strict tool calling, or false for those that don't. Only override if you're certain about the model's capabilities.'

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

@kavitaganeshan
Copy link

/review

@kavitaganeshan
Copy link

@coderabbitai review

Copy link

PR Reviewer Guide 🔍

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Key issues to review

Potential Bug
The strict parameter is being set based on the model name starting with 'gpt-', but this might not be accurate for all models or future OpenAI releases. Consider adding a more robust check or allowing users to explicitly set this parameter.

Code Duplication
The logic for setting the strict parameter is duplicated in multiple places. Consider refactoring this into a single method to improve maintainability.

Copy link

coderabbitai bot commented Aug 15, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@furwellness
Copy link
Owner

@coderabbitai review

Copy link

coderabbitai bot commented Aug 17, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

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, codebase verification and nitpick comments (1)
libs/langchain-openai/src/types.ts (1)

159-164: Add documentation for supportsStrictToolCalling.

The new supportsStrictToolCalling property should have documentation explaining its default behavior and when it should be overridden. This will help users understand its purpose and usage.

+  /**
+   * Set this to true for models that support strict tool calling, or false for those that don't.
+   * Only override if you're certain about the model's capabilities.
+   */
  supportsStrictToolCalling?: boolean;
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c5fb8bb and 717a996.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (7)
  • langchain-core/src/language_models/base.ts (1 hunks)
  • langchain-core/src/utils/function_calling.ts (1 hunks)
  • libs/langchain-openai/package.json (1 hunks)
  • libs/langchain-openai/src/chat_models.ts (7 hunks)
  • libs/langchain-openai/src/tests/chat_models.test.ts (1 hunks)
  • libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts (1 hunks)
  • libs/langchain-openai/src/types.ts (1 hunks)
Additional context used
Biome
libs/langchain-openai/src/tests/chat_models.test.ts

[error] 31-31: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 64-64: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 110-110: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 154-154: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 199-199: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Additional comments not posted (12)
libs/langchain-openai/package.json (1)

40-40: Verify compatibility with the updated OpenAI dependency.

The openai dependency has been updated from ^4.49.1 to ^4.55.0. Ensure that the rest of the codebase is compatible with this new version, as it may introduce breaking changes or new features.

libs/langchain-openai/src/tests/chat_models.test.ts (4)

58-59: Ensure mock setup matches test expectations.

The existing comment highlights a mismatch in the mock setup. Consider updating the mock to return an error if the test intends to check error handling, or adjust the test to expect a successful response.


105-106: Ensure mock setup matches test expectations.

The existing comment highlights a mismatch in the mock setup. Consider updating the mock to return an error if the test intends to check error handling, or adjust the test to expect a successful response.


149-150: Ensure mock setup matches test expectations.

The existing comment highlights a mismatch in the mock setup. Consider updating the mock to return an error if the test intends to check error handling, or adjust the test to expect a successful response.


194-195: Ensure mock setup matches test expectations.

The existing comment highlights a mismatch in the mock setup. Consider updating the mock to return an error if the test intends to check error handling, or adjust the test to expect a successful response.

libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts (2)

6-6: Import statement for Jest is appropriate.

The import of test and expect from @jest/globals is necessary and correctly implemented for the test cases.


Line range hint 8-90:
Test cases for structured output are well-structured and comprehensive.

The test cases effectively verify the functionality of structured output using Zod schemas and JSON schemas. They include appropriate assertions to ensure expected keys are present in the results.

langchain-core/src/language_models/base.ts (1)

237-244: Addition of strict property to FunctionDefinition is well-implemented.

The optional strict property is well-documented and enhances functionality by enforcing strict schema adherence. It integrates seamlessly with the existing interface.

libs/langchain-openai/src/chat_models.ts (4)

310-311: LGTM!

The introduction of the ChatOpenAIFields interface consolidates properties and enhances modularity and readability.


302-308: Verify the usage of the strict property.

The strict property has been added to the ChatOpenAICallOptions interface. Ensure that all instances where ChatOpenAICallOptions is used are updated to handle this new property appropriately.

Verification successful

The strict property is correctly integrated and tested.

The strict property in ChatOpenAICallOptions is actively used and tested in the codebase, ensuring its correct functionality.

  • File: libs/langchain-openai/src/chat_models.ts
  • Tests: libs/langchain-openai/src/tests/chat_models.test.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all instances where `ChatOpenAICallOptions` is used to ensure the `strict` property is handled.

# Test: Search for `ChatOpenAICallOptions` usage. Expect: Instances where `strict` is utilized.
rg --type typescript -A 5 $'ChatOpenAICallOptions'

Length of output: 84


Script:

#!/bin/bash
# Description: Verify all instances where `ChatOpenAICallOptions` is used to ensure the `strict` property is handled.

# Test: Search for `ChatOpenAICallOptions` usage. Expect: Instances where `strict` is utilized.
rg --type ts -A 5 $'ChatOpenAICallOptions'

Length of output: 9355


Script:

#!/bin/bash
# Description: Search for the usage of the `strict` property in the codebase to ensure it is handled properly.

# Test: Search for `strict` property usage. Expect: Instances where `strict` is assigned or used.
rg --type ts 'strict' -A 5

Length of output: 66796


Line range hint 585-639:
Verify the propagation of the strict argument.

The bindTools and invocationParams methods have been updated to include the strict argument. Ensure that this argument is correctly propagated and utilized in all relevant tool interactions.

Verification successful

Strict Argument Propagation Verified

The strict argument is correctly propagated and utilized in the bindTools and invocationParams methods. The presence of tests in libs/langchain-openai/src/tests/chat_models.test.ts confirms that the strict argument is being handled appropriately, including its default behavior for specific model names.

  • File: libs/langchain-openai/src/chat_models.ts
  • Test Coverage: libs/langchain-openai/src/tests/chat_models.test.ts

These findings indicate that the strict argument is integrated and tested as intended.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the propagation of the `strict` argument in `bindTools` and `invocationParams` methods.

# Test: Search for method calls and ensure `strict` is correctly utilized.
rg --type typescript -A 5 $'(bindTools|invocationParams)'

Length of output: 93


Script:

#!/bin/bash
# Description: Verify the propagation of the `strict` argument in `bindTools` and `invocationParams` methods.

# Test: Search for method calls and ensure `strict` is correctly utilized.
rg 'bindTools|invocationParams' -A 5

Length of output: 121694


Script:

#!/bin/bash
# Description: Search for the usage of the `strict` argument in the codebase to verify its propagation.

# Test: Search for the `strict` keyword in TypeScript files to ensure it is utilized correctly.
rg 'strict' --type ts

Length of output: 16972


Line range hint 459-562:
Verify the constructor logic for supportsStrictToolCalling.

The constructor has been updated to determine the supportsStrictToolCalling property based on the model name. Ensure that this logic is correct and consistent with the intended behavior for all models.

Verification successful

Constructor Logic for supportsStrictToolCalling is Correct

The constructor logic for determining supportsStrictToolCalling based on the model name is consistent with the intended behavior. It correctly sets this property for models whose names start with "gpt-", such as "gpt-3.5-turbo" and "gpt-4". No issues were found with this implementation.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the logic for determining `supportsStrictToolCalling` in the `ChatOpenAI` constructor.

# Test: Search for constructor calls and ensure `supportsStrictToolCalling` is correctly set.
rg --type typescript -A 10 $'new ChatOpenAI'

Length of output: 80


Script:

#!/bin/bash
# Description: Verify the logic for determining `supportsStrictToolCalling` in the `ChatOpenAI` constructor.

# Test: Search for constructor calls and ensure `supportsStrictToolCalling` is correctly set.
rg --type ts -A 10 $'new ChatOpenAI'

Length of output: 394577

Comment on lines +56 to +59
if (fields?.strict !== undefined) {
toolDef.function.strict = fields.strict;
}

Copy link

Choose a reason for hiding this comment

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

Fix the return value to include modifications.

The function is currently returning the original tool parameter instead of the modified toolDef. Ensure that the return statement reflects the intended changes, including the strict parameter.

-  return tool as ToolDefinition;
+  return toolDef;
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
if (fields?.strict !== undefined) {
toolDef.function.strict = fields.strict;
}
if (fields?.strict !== undefined) {
toolDef.function.strict = fields.strict;
}
return toolDef;

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

Successfully merging this pull request may close these issues.

3 participants