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

feat: add structured output support (added in ollama 0.5.0) #92

Merged
merged 2 commits into from
Feb 3, 2025

Conversation

DustinReagan
Copy link
Contributor

@DustinReagan DustinReagan commented Feb 3, 2025

  • Updated openai.yaml to allow either the string 'json' or a json-serializable object that represents a json schema (no schema validation occurs).
  • added StructuredOutputInChat integration test.

Main outstanding issue is that the current generate.sh script as it stands will blow away the changes I made to the repos openapi.yaml file. IMO, the generate.sh script should target the repos version of the openapi.yaml file and not try to redownload it from the other source.

Addresses issue: #85

Summary by CodeRabbit

  • New Features

    • Enhanced API response formatting to now support both a simplified JSON mode and an extended schema-based structure, offering added flexibility for API responses.
  • Tests

    • Introduced integration tests to verify that chat interactions return structured outputs with accurate temperature and location details.

Copy link

coderabbitai bot commented Feb 3, 2025

Walkthrough

This pull request updates the OpenAPI specification for the Ollama API by replacing the simple ResponseFormat string definition with a oneOf construct for enhanced flexibility. Additionally, a new integration test method has been added to validate the structured output in chat, along with definitions for a new TemperatureUnit enum and QueryResponse class. These changes update schema definitions and add a practical test for the chat API's response formatting.

Changes

File Path Change Summary
src/libs/Ollama/openapi.yaml Updated ResponseFormat schema from a simple string enum to a oneOf construct that supports either a string type with enum or an object type with JSON schema.
src/tests/Ollama.IntegrationTests/Test...cs Added a new integration test StructuredOutputInChat, along with new enum TemperatureUnit and class QueryResponse to validate structured chat responses.

Sequence Diagram(s)

sequenceDiagram
    participant T as Test Framework
    participant CC as Chat Client
    participant S as Server/API

    T->>CC: Set response format with JSON schema
    T->>CC: Send query ("current temperature in Dubai")
    CC->>S: API request with structured payload
    S-->>CC: Return structured response (temperature, unit, location)
    CC-->>T: Deliver deserialized QueryResponse
    T->>T: Assert temperature and location values
Loading

Suggested reviewers

  • github-actions

Poem

I hop through code with glee,
New schemas and tests set free.
Structured chats make laughter bloom,
In API paths we find our room.
With every change, my heart goes “zoom”!
🐰💻 Hop on, let's zoom through the code!


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>, please review it.
    • 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 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 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 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. (Beta)
  • @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.

@CLAassistant
Copy link

CLAassistant commented Feb 3, 2025

CLA assistant check
All committers have signed the CLA.

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

🧹 Nitpick comments (3)
src/tests/Ollama.IntegrationTests/Test.StructuredOutputInChat.cs (3)

17-20: Make the system message more specific to weather queries.

The system message could be more specific to guide the model's behavior for weather-related queries.

-            systemMessage: "You are a helpful weather assistant."
+            systemMessage: "You are a weather assistant. Provide accurate temperature information in the requested format. Always respond with temperature in the specified unit and include the full location name."

22-39: Consider using a schema generation library or moving schema to a resource file.

The JSON schema is currently hardcoded as a string. Consider:

  1. Using NewtonSoft.Json.Schema for auto-generation from the QueryResponse class.
  2. Moving the schema to a resource file for better maintainability.

Example using NewtonSoft.Json.Schema:

using Newtonsoft.Json.Schema.Generation;

// Generate schema from QueryResponse class
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(QueryResponse));
chat.ResponseFormat = new ResponseFormat(schema);

58-70: Add XML documentation and validation attributes to types.

The types could benefit from:

  1. XML documentation for better IntelliSense support.
  2. Data validation attributes.
     [JsonConverter(typeof(JsonStringEnumConverter))]
+    /// <summary>
+    /// Represents the unit of temperature measurement.
+    /// </summary>
     public enum TemperatureUnit
     {
+        /// <summary>
+        /// Temperature in Celsius.
+        /// </summary>
         Celsius,
+        /// <summary>
+        /// Temperature in Fahrenheit.
+        /// </summary>
         Fahrenheit
     }

+    /// <summary>
+    /// Represents a response to a temperature query.
+    /// </summary>
     public class QueryResponse {
+        /// <summary>
+        /// Gets or sets the temperature value.
+        /// </summary>
+        [Range(-50, 60)]
         public int Temperature { get; set; }

+        /// <summary>
+        /// Gets or sets the temperature unit.
+        /// </summary>
+        [Required]
         public TemperatureUnit Unit { get; set; }

+        /// <summary>
+        /// Gets or sets the location name.
+        /// </summary>
+        [Required]
+        [MinLength(2)]
         public string Location { get; set; }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79e19b1 and a47c83a.

⛔ Files ignored due to path filters (16)
  • src/libs/Ollama/Generated/JsonConverters.ResponseFormat.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/JsonConverters.ResponseFormatEnum.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/JsonConverters.ResponseFormatEnumNullable.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/JsonSerializerContext.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/JsonSerializerContextTypes.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.ChatClient.GenerateChatCompletion.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.CompletionsClient.GenerateCompletion.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.IChatClient.GenerateChatCompletion.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.ICompletionsClient.GenerateCompletion.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.GenerateChatCompletionRequest.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.GenerateCompletionRequest.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.ResponseFormat.Json.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.ResponseFormat.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.ResponseFormatEnum.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.ResponseFormatEnum2.Json.g.cs is excluded by !**/generated/**
  • src/libs/Ollama/Generated/Ollama.Models.ResponseFormatEnum2.g.cs is excluded by !**/generated/**
📒 Files selected for processing (2)
  • src/libs/Ollama/openapi.yaml (1 hunks)
  • src/tests/Ollama.IntegrationTests/Test.StructuredOutputInChat.cs (1 hunks)
🔇 Additional comments (1)
src/libs/Ollama/openapi.yaml (1)

441-447: LGTM! Well-structured schema changes.

The ResponseFormat schema changes:

  1. Maintain backward compatibility with the 'json' string format.
  2. Add support for structured output through JSON schema objects.
  3. Include clear descriptions for both formats.

@DustinReagan DustinReagan mentioned this pull request Feb 3, 2025
@HavenDV HavenDV merged commit 70d226d into tryAGI:main Feb 3, 2025
3 of 4 checks passed
@HavenDV
Copy link
Contributor

HavenDV commented Feb 3, 2025

Thank you very much for taking the time to look into this issue and raise it and offer a solution.

Main outstanding issue is that the current generate.sh script as it stands will blow away the changes I made to the repos openapi.yaml file. IMO, the generate.sh script should target the repos version of the openapi.yaml file and not try to redownload it from the other source.

curl -o openapi.yaml https://raw.githubusercontent.com/davidmigloz/langchain_dart/main/packages/ollama_dart/oas/ollama-curated.yaml
dotnet run --project ../../helpers/FixOpenApiSpec openapi.yaml

Let me explain a bit what's going on - this is where the FixOpenApiSpec project is launched to make edits to the OpenAPI being loaded - and this is the place to make your suggested changes.

I fixed it in this commit - fd55bb8

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.

3 participants