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 #7

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

Conversation

korbit-ai[bot]
Copy link

@korbit-ai korbit-ai bot commented Aug 15, 2024

User description

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 strict parameter is enabled by default for models starting with "gpt-". This enhancement improves the reliability and predictability of function calls in OpenAI tools.


PR Type

enhancement, tests


Description

  • Added support for a strict parameter in OpenAI tools to enforce strict schema adherence.
  • Enhanced ChatOpenAI to handle the strict parameter, with default behavior based on model name.
  • Updated convertToOpenAITool function to include strict parameter in tool definitions.
  • Added comprehensive tests to verify the behavior of the strict parameter.
  • Updated openai dependency version in package.json.

Changes walkthrough 📝

Relevant files
Enhancement
base.ts
Add `strict` parameter to FunctionDefinition interface     

langchain-core/src/language_models/base.ts

  • Added strict parameter to FunctionDefinition interface.
  • Documented the purpose and behavior of the strict parameter.
  • +9/-0     
    function_calling.ts
    Update convertToOpenAITool to handle strict parameter       

    langchain-core/src/utils/function_calling.ts

  • Updated convertToOpenAITool function to accept strict parameter.
  • Modified logic to include strict in tool definition.
  • +17/-2   
    chat_models.ts
    Implement strict parameter handling in ChatOpenAI               

    libs/langchain-openai/src/chat_models.ts

  • Added strict parameter to ChatOpenAICallOptions.
  • Implemented logic to determine default strict value based on model
    name.
  • Updated methods to pass strict parameter when binding tools.
  • +29/-8   
    types.ts
    Add supportsStrictToolCalling to OpenAIChatInput                 

    libs/langchain-openai/src/types.ts

  • Added supportsStrictToolCalling to OpenAIChatInput.
  • Documented default behavior based on model name.
  • +7/-0     
    Tests
    chat_models.test.ts
    Add tests for strict parameter in ChatOpenAI                         

    libs/langchain-openai/src/tests/chat_models.test.ts

  • Added tests for strict parameter in tool binding.
  • Verified behavior for models with names starting with "gpt-".
  • +212/-0 
    chat_models_structured_output.int.test.ts
    Update imports in structured output integration test         

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

    • Imported test and expect from @jest/globals.
    +1/-0     
    Dependencies
    package.json
    Update openai dependency version                                                 

    libs/langchain-openai/package.json

    • Updated openai dependency version to ^4.55.0.
    +1/-1     

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Summary by CodeRabbit

    • New Features

      • Added a strict option to enhance control over function call generation and schema adherence.
      • Introduced new properties and interfaces to improve configuration clarity for the ChatOpenAI class.
    • Bug Fixes

      • Upgraded OpenAI library dependency to ensure compatibility and leverage new features.
    • Tests

      • Added a comprehensive test suite to validate strict tool calling functionality in the ChatOpenAI class, ensuring correct handling of the strict parameter across various configurations.

    Copy link
    Author

    korbit-ai bot commented Aug 15, 2024

    Clone of the PR langchain-ai/langchainjs#6418

    Copy link
    Author

    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 enhance the LangChain integration with OpenAI services by introducing a strict option for function definitions and tool calling within the ChatOpenAI class. This allows for precise adherence to JSON Schema, improving usability and control over output formats. Additionally, dependency updates ensure compatibility with the latest OpenAI library features. The modifications are complemented by a robust suite of tests to validate the new functionality and configurations.

    Changes

    Files Change Summary
    langchain-core/src/language_models/base.ts Introduced an optional strict property to the FunctionDefinition interface, enhancing schema adherence for function calls.
    langchain-core/src/utils/function_calling.ts Updated convertToOpenAITool function to accept a fields parameter, allowing for strict adherence to JSON Schema when strict is true.
    libs/langchain-openai/package.json Updated openai package version from ^4.49.1 to ^4.55.0 to leverage new features and improvements.
    libs/langchain-openai/src/chat_models.ts Added strict property to ChatOpenAICallOptions, modified constructor to accept ChatOpenAIFields, and introduced supportsStrictToolCalling property to manage strictness in tool calling.
    libs/langchain-openai/src/tests/chat_models.test.ts Created a test suite to validate strict tool calling functionality, ensuring proper handling of the strict parameter in methods such as bindTools and bind.
    libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts Added Jest import for enhanced testing capabilities, ensuring structured output tests for ChatOpenAI are properly executed.
    libs/langchain-openai/src/types.ts Introduced supportsStrictToolCalling to the OpenAIChatInput interface, indicating model support for strict configurations based on model name.

    Sequence Diagram(s)

    sequenceDiagram
        participant User
        participant ChatOpenAI
        participant Tool
    
        User->>ChatOpenAI: Create instance with fields including strict
        ChatOpenAI->>Tool: Bind tools with strict settings
        Tool-->>ChatOpenAI: Confirm tool binding
        ChatOpenAI->>User: Return structured output with strict adherence
    
    Loading

    🐰 In a world of JSON clear,
    Where strictness brings us cheer,
    With tools that heed the call,
    Compliance standing tall.
    Our code now hops with glee,
    Thanks to updates, bright and free! 🌟


    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
    Author

    @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
    Author

    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

    There's an issue with the return statement in the convertToOpenAITool function. Currently, it's returning the original tool parameter, which hasn't been modified with the strict field. Instead, it should return the toolDef variable, which contains the updated tool definition. Please update the return statement to return toolDef; to ensure the function returns the correctly modified tool definition.

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

    @@ -3,6 +3,7 @@ import { zodToJsonSchema } from "zod-to-json-schema";
    import { ChatPromptTemplate } from "@langchain/core/prompts";
    import { AIMessage } from "@langchain/core/messages";
    import { ChatOpenAI } from "../chat_models.js";
    import { test, expect } from "@jest/globals";
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Functionality

    It appears that you've added an import for 'test' and 'expect' from '@jest/globals'. However, these are typically globally available in Jest test files without explicit imports. To improve code cleanliness and avoid potential conflicts, you can remove this redundant import line.

    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
    Author

    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' field has been added to the OpenAIChatInput interface, which is a good addition. However, it would be helpful to add a comment explaining how this field is used in the actual implementation. For example, does setting this to true enforce strict adherence to the tool's schema? How does it affect the model's behavior when calling tools? Adding this information would make the code more self-documenting and easier for other developers to understand and use correctly.

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

    @furwellness furwellness reopened this Aug 20, 2024
    @furwellness furwellness changed the base branch from cloned_main_c5fb8 to main August 20, 2024 23:48
    @codiumai-pr-agent-free codiumai-pr-agent-free bot added enhancement New feature or request tests labels Aug 20, 2024
    @furwellness
    Copy link
    Owner

    /review

    Copy link

    codiumai-pr-agent-free bot commented Aug 20, 2024

    PR Reviewer Guide 🔍

    (Review updated until commit 005ef36)

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

    Potential Bug
    The supportsStrictToolCalling property is set based on the model name, but it's not clear if this is the most reliable method. There might be cases where this assumption is incorrect.

    Code Duplication
    The logic for handling the strict parameter is duplicated in multiple methods. Consider refactoring to a single helper method.

    @furwellness
    Copy link
    Owner

    @coderabbitai full review

    Copy link

    coderabbitai bot commented Aug 20, 2024

    Actions performed

    Full review triggered.

    Copy link

    Persistent review updated to latest commit 005ef36

    Copy link

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Add a type guard to prevent potential runtime errors when accessing properties of possibly undefined objects

    Consider using a type guard to ensure that options is not undefined before accessing
    its properties, to prevent potential runtime errors.

    libs/langchain-openai/src/chat_models.ts [602-605]

     function isStructuredToolArray(
       tools?: unknown[]
     ): tools is StructuredToolInterface[] {
    +  if (!tools) return false;
       return (
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Adding a type guard is a significant improvement as it prevents potential runtime errors, enhancing the robustness and reliability of the code.

    9
    Enhancement
    Simplify conditional logic using optional chaining and nullish coalescing operators

    Consider using optional chaining and nullish coalescing operators to simplify the
    conditional logic for determining the supportsStrictToolCalling value.

    libs/langchain-openai/src/chat_models.ts [559-562]

    -this.supportsStrictToolCalling = 
    -fields?.supportsStrictToolCalling !== undefined
    -  ? fields.supportsStrictToolCalling
    -  : this.modelName.startsWith("gpt-");
    +this.supportsStrictToolCalling = fields?.supportsStrictToolCalling ?? this.modelName.startsWith("gpt-");
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: This suggestion simplifies the code and reduces potential errors by using modern JavaScript features, improving both readability and maintainability.

    8
    Use a more descriptive variable name for better code readability

    Consider using a more descriptive variable name instead of strict to better convey
    its purpose. For example, enforceStrictSchema or useStrictToolSchema would be more
    informative.

    libs/langchain-openai/src/chat_models.ts [585]

    -const strict = kwargs?.strict !== undefined ? kwargs.strict : this.supportsStrictToolCalling;
    +const enforceStrictSchema = kwargs?.strict !== undefined ? kwargs.strict : this.supportsStrictToolCalling;
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: The suggestion improves code readability by using a more descriptive variable name, which helps in understanding the purpose of the variable. However, it is not crucial for functionality.

    6
    Maintainability
    Extract logic for determining strict mode into a separate method

    Consider extracting the logic for determining the strict value into a separate
    method for better code organization and reusability.

    libs/langchain-openai/src/chat_models.ts [601]

    -const strict = options?.strict !== undefined ? options.strict : this.supportsStrictToolCalling;
    +const strict = this.determineStrictMode(options?.strict);
     
    +// Add this method to the class:
    +// private determineStrictMode(optionsStrict?: boolean): boolean {
    +//   return optionsStrict !== undefined ? optionsStrict : this.supportsStrictToolCalling;
    +// }
    +
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Extracting the logic into a separate method enhances code organization and reusability, making the codebase easier to maintain and understand.

    7

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

    Outside diff range, codebase verification and nitpick comments (2)
    libs/langchain-openai/src/types.ts (1)

    159-164: Add Documentation for supportsStrictToolCalling

    The supportsStrictToolCalling property is a valuable addition. Consider adding documentation to explain its purpose and impact on model behavior when calling tools.

    +  /**
    +   * Indicates whether the model supports the 'strict' argument for tool usage.
    +   * This affects how strictly the model adheres to the tool's schema.
    +   */
    libs/langchain-openai/src/tests/chat_models_structured_output.int.test.ts (1)

    6-6: Remove Redundant Import of test and expect

    The import statement for test and expect is redundant as these are globally available in Jest test files. Consider removing it for cleaner code.

    -import { test, expect } from "@jest/globals";
    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between 9db8299 and 005ef36.

    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 (8)
    libs/langchain-openai/package.json (1)

    40-40: Dependency Update: Verify Compatibility with OpenAI v4.55.0

    The openai package has been updated to version ^4.55.0. Ensure that the codebase is compatible with this version and take advantage of any new features or improvements.

    Run the following script to verify compatibility with the new version:

    langchain-core/src/utils/function_calling.ts (1)

    37-44: LGTM! Addition of strict Parameter

    The addition of the strict parameter to the convertToOpenAITool function enhances flexibility and control over tool output formats.

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

    236-244: Well-documented addition of the strict property.

    The strict property is a valuable addition to the FunctionDefinition interface, providing enhanced control over schema adherence. The accompanying documentation is clear and informative.

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

    302-308: Well-documented addition of the strict property.

    The strict property in the ChatOpenAICallOptions interface is a valuable addition, providing enhanced control over model responses. The documentation is clear and informative.


    310-311: Introduction of ChatOpenAIFields interface enhances clarity.

    The ChatOpenAIFields interface consolidates configuration options, improving clarity and maintainability. This change is well-integrated into the constructor.


    454-459: Well-documented addition of supportsStrictToolCalling property.

    The supportsStrictToolCalling property enhances the flexibility of the ChatOpenAI class by indicating support for the strict argument. The documentation is clear and informative.


    Line range hint 460-562: Constructor modifications streamline configuration.

    The constructor modifications in the ChatOpenAI class streamline the configuration process and ensure proper initialization of the supportsStrictToolCalling property. These changes are well-implemented.


    Line range hint 585-639: Consistent integration of the strict parameter in methods.

    The integration of the strict parameter in methods like bindTools and invocationParams ensures consistent application, enhancing control over tool interactions.

    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 Statement in convertToOpenAITool

    The return statement currently returns the original tool parameter. It should return the toolDef variable, which contains the updated tool definition with the strict field.

    Fix the return statement as follows:

    -  return tool as ToolDefinition;
    +  return toolDef;

    Committable suggestion was skipped due to low confidence.

    expect(mockFetch).toHaveBeenCalled();
    const [_url, options] = mockFetch.mock.calls[0];

    if (options && options.body) {
    Copy link

    Choose a reason for hiding this comment

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

    Use Optional Chaining for Safety

    Consider using optional chaining to safely access properties and avoid potential runtime errors.

    -    if (options && options.body) {
    +    if (options?.body) {

    Also applies to: 110-110, 154-154, 199-199

    Tools
    Biome

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

    Unsafe fix: Change to an optional chain.

    (lint/complexity/useOptionalChain)

    process.env.LANGCHAIN_TRACING_V2 = oldLangChainTracingValue;
    } else {
    // If it was undefined, remove the environment variable
    delete process.env.LANGCHAIN_TRACING_V2;
    Copy link

    Choose a reason for hiding this comment

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

    Avoid Using the delete Operator

    Using the delete operator can impact performance. Consider setting the variable to undefined instead.

    -      delete process.env.LANGCHAIN_TRACING_V2;
    +      process.env.LANGCHAIN_TRACING_V2 = undefined;
    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
    delete process.env.LANGCHAIN_TRACING_V2;
    process.env.LANGCHAIN_TRACING_V2 = undefined;
    Tools
    Biome

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

    Unsafe fix: Use an undefined assignment instead.

    (lint/performance/noDelete)

    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.

    2 participants