Skip to content

Conversation

@EazyAl
Copy link
Contributor

@EazyAl EazyAl commented Aug 6, 2025

Pull Request

Adds first-class support for the experimental Chat Completions API
API reference: https://www.meilisearch.com/docs/reference/api/chats

Related issue

#1130

What does this PR do?

  • Implements the chat completions experimental features in Python SDK inspired by meilisearch-js PR #1988

New methods are:

  • create_chat_completion()
  • get_chat_workspaces()
  • get_chat_workspace_settings()
  • update_chat_workspace_settings()

Summary by CodeRabbit

  • New Features

    • Streaming chat completions for real-time responses.
    • Retrieve and update chat workspace settings with optional pagination.
    • POST requests can return streaming responses for large/continuous payloads.
  • Bug Fixes

    • Improved error handling for streaming, JSON parsing, and HTTP failures.
  • Tests

    • Added tests covering chat streaming, workspace retrieval/update, streaming error handling, and edge cases.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Walkthrough

Added HTTP streaming support via a new HttpRequests.post_stream method and four Client chat-related methods: create_chat_completion (streaming), get_chat_workspaces, get_chat_workspace_settings, and update_chat_workspace_settings. Added unit tests covering streaming, JSON errors, HTTP error propagation, and workspace endpoints.

Changes

Cohort / File(s) Change Summary
HTTP Streaming Support
meilisearch/_httprequests.py
Added post_stream to send POST requests with stream=True, return the raw requests.Response for streaming consumption, and raise appropriate timeout/connection/HTTP/schema errors.
Chat API Client Methods
meilisearch/client.py
Added create_chat_completion (streams and yields parsed JSON chunks until "[DONE]"), get_chat_workspaces, get_chat_workspace_settings, and update_chat_workspace_settings; added/updated imports for typing and error classes.
Chat Feature Unit Tests
tests/client/test_chat_completions.py
Added tests and MockStreamingResponse to validate streaming chat completions (multi-chunk, malformed JSON, HTTP error propagation), and GET/PATCH workspace endpoints.

Sequence Diagram(s)

Streaming Chat Completion Flow

sequenceDiagram
    participant User
    participant Client
    participant HttpRequests
    participant MeiliAPI

    rect rgba(200,230,255,0.4)
    User->>Client: create_chat_completion(workspace_uid, messages, stream=True)
    end

    Client->>HttpRequests: post_stream(path="/api/chats/{uid}/completions", body=...)
    HttpRequests->>MeiliAPI: POST /api/chats/{uid}/completions (stream=True)
    note right of MeiliAPI: Streams lines prefixed with "data:"
    MeiliAPI-->>HttpRequests: streaming lines (data: {...}\n, ..., data: "[DONE]\n")
    HttpRequests-->>Client: requests.Response (stream)
    loop each streamed line
        Client->>Client: read line, strip "data:", parse JSON (or raise)
        Client-->>User: yield parsed JSON chunk
    end
    Client->>HttpRequests: close() response
Loading

Retrieve / Update Chat Workspaces Flow

sequenceDiagram
    participant User
    participant Client
    participant HttpRequests
    participant MeiliAPI

    User->>Client: get_chat_workspaces(offset?, limit?)
    Client->>HttpRequests: get("/api/chats", params)
    HttpRequests->>MeiliAPI: GET /api/chats?offset=...&limit=...
    MeiliAPI-->>HttpRequests: JSON response
    HttpRequests-->>Client: parsed JSON
    Client-->>User: return workspaces

    User->>Client: update_chat_workspace_settings(uid, settings)
    Client->>HttpRequests: patch("/api/chats/{uid}/settings", body)
    HttpRequests->>MeiliAPI: PATCH /api/chats/{uid}/settings
    MeiliAPI-->>HttpRequests: JSON response
    HttpRequests-->>Client: parsed JSON
    Client-->>User: return updated settings
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

I hop on keys and chase the stream,
JSON petals in a dream.
Workspaces lined up neat and small—
I nibble bugs and test them all.
Rabbit code, I cheer the stream 🐇✨

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.

@EazyAl EazyAl marked this pull request as ready for review August 7, 2025 14:49
Copy link
Contributor

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

🧹 Nitpick comments (3)
meilisearch/_httprequests.py (1)

5-5: Remove unused import.

The Iterator import is not used in this file and should be removed as flagged by static analysis.

-from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union
+from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple, Type, Union
meilisearch/client.py (1)

798-869: Excellent streaming chat completion implementation with minor exception chaining issue.

The create_chat_completion method is well-designed with proper parameter validation, streaming response handling, JSON parsing, and resource cleanup. The implementation correctly follows the Server-Sent Events (SSE) protocol pattern with "data: " prefixed lines and "[DONE]" completion signal.

However, there's a minor issue with exception chaining on line 866 as flagged by static analysis:

-                        raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}")
+                        raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}") from e

This preserves the original exception context for better debugging.

tests/client/test_chat_completions.py (1)

3-3: Remove unused imports.

Several imports are flagged as unused by static analysis and should be removed to keep the code clean:

-import json
 from unittest.mock import patch

 import pytest
 import requests

-import meilisearch
 from meilisearch.errors import MeilisearchApiError, MeilisearchCommunicationError
-from tests import BASE_URL, MASTER_KEY

The json, meilisearch, BASE_URL, and MASTER_KEY imports are not used in this test file.

Also applies to: 9-9, 11-11

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5293d9 and aac3eef.

📒 Files selected for processing (3)
  • meilisearch/_httprequests.py (2 hunks)
  • meilisearch/client.py (2 hunks)
  • tests/client/test_chat_completions.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
tests/client/test_chat_completions.py (3)
meilisearch/errors.py (2)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
tests/conftest.py (1)
  • client (15-16)
meilisearch/client.py (2)
  • create_chat_completion (798-868)
  • get_chat_workspaces (870-901)
meilisearch/client.py (3)
meilisearch/_httprequests.py (2)
  • post_stream (149-213)
  • get (95-96)
meilisearch/errors.py (3)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchError (17-25)
tests/client/test_chat_completions.py (2)
  • iter_lines (24-27)
  • close (29-31)
meilisearch/_httprequests.py (2)
tests/client/test_chat_completions.py (1)
  • raise_for_status (33-36)
meilisearch/errors.py (3)
  • MeilisearchTimeoutError (61-65)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchApiError (28-51)
🪛 Ruff (0.12.2)
tests/client/test_chat_completions.py

3-3: json imported but unused

Remove unused import: json

(F401)


9-9: meilisearch imported but unused

Remove unused import: meilisearch

(F401)


11-11: tests.BASE_URL imported but unused

Remove unused import

(F401)


11-11: tests.MASTER_KEY imported but unused

Remove unused import

(F401)

meilisearch/client.py

16-16: meilisearch.errors.MeilisearchApiError imported but unused

Remove unused import: meilisearch.errors.MeilisearchApiError

(F401)


866-866: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

meilisearch/_httprequests.py

5-5: typing.Iterator imported but unused

Remove unused import: typing.Iterator

(F401)

🔇 Additional comments (4)
meilisearch/_httprequests.py (1)

149-214: Streaming POST method is safely implemented

The post_stream method correctly handles body serialization, streaming, and error mapping. Since response is always assigned before raise_for_status() is called, the HTTPError handler cannot encounter an undefined response variable. No further changes needed—approving these updates.

meilisearch/client.py (2)

16-16: Import is correctly used.

The static analysis tool incorrectly flags MeilisearchApiError as unused. This import is actually used in the docstrings for exception documentation and the error handling logic relies on it being available. The import should remain.


870-902: Clean and straightforward workspace listing implementation.

The get_chat_workspaces method follows established patterns in the codebase for pagination handling and query string construction. The implementation is clean and correctly handles optional parameters.

tests/client/test_chat_completions.py (1)

14-140: Excellent comprehensive test coverage.

The test suite provides thorough coverage of the new chat completion functionality with well-designed test cases:

  • MockStreamingResponse: Well-implemented mock that accurately simulates the streaming response behavior
  • Happy path testing: Verifies correct streaming, JSON parsing, and response handling
  • Error conditions: Tests parameter validation, JSON decode errors, and HTTP error propagation
  • Edge cases: Covers both methods with and without optional parameters
  • Resource cleanup: Verifies proper response closure

The test structure follows established patterns and uses appropriate mocking strategies. The assertions are specific and verify both the HTTP calls and the returned data.

Copy link
Contributor

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

🧹 Nitpick comments (3)
meilisearch/_httprequests.py (1)

5-5: Remove unused import.

The Iterator type is imported but not used in this file. Based on the static analysis hint, this import should be removed.

-from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union
+from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple, Type, Union
meilisearch/client.py (1)

798-869: Solid streaming implementation with minor exception chaining issue.

The create_chat_completion method is well-implemented with proper SSE parsing, error handling, and resource cleanup. However, there's a minor issue with exception chaining.

Line 866 should use proper exception chaining:

                except json.JSONDecodeError as e:
-                    raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}")
+                    raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}") from e

This preserves the original exception context for better debugging.

tests/client/test_chat_completions.py (1)

3-3: Remove unused imports.

Several imports are not used in this test file:

  • json (line 3) - not used anywhere in the file
  • meilisearch (line 9) - the client fixture provides the client instance
  • BASE_URL and MASTER_KEY (line 11) - not used in these tests
-import json
 from unittest.mock import patch

 import pytest
 import requests

-import meilisearch
 from meilisearch.errors import MeilisearchApiError, MeilisearchCommunicationError
-from tests import BASE_URL, MASTER_KEY

Also applies to: 9-9, 11-11

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aac3eef and 5577004.

📒 Files selected for processing (3)
  • meilisearch/_httprequests.py (2 hunks)
  • meilisearch/client.py (2 hunks)
  • tests/client/test_chat_completions.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
meilisearch/_httprequests.py (2)
tests/client/test_chat_completions.py (1)
  • raise_for_status (33-36)
meilisearch/errors.py (3)
  • MeilisearchTimeoutError (61-65)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchApiError (28-51)
tests/client/test_chat_completions.py (4)
meilisearch/_httprequests.py (1)
  • patch (110-118)
meilisearch/errors.py (2)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
tests/conftest.py (1)
  • client (15-16)
meilisearch/client.py (3)
  • create_chat_completion (798-868)
  • get_chat_workspaces (870-901)
  • update_chat_workspace_settings (924-946)
🪛 Ruff (0.12.2)
meilisearch/client.py

16-16: meilisearch.errors.MeilisearchApiError imported but unused

Remove unused import: meilisearch.errors.MeilisearchApiError

(F401)


866-866: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

meilisearch/_httprequests.py

5-5: typing.Iterator imported but unused

Remove unused import: typing.Iterator

(F401)

tests/client/test_chat_completions.py

3-3: json imported but unused

Remove unused import: json

(F401)


9-9: meilisearch imported but unused

Remove unused import: meilisearch

(F401)


11-11: tests.BASE_URL imported but unused

Remove unused import

(F401)


11-11: tests.MASTER_KEY imported but unused

Remove unused import

(F401)

🔇 Additional comments (13)
meilisearch/_httprequests.py (1)

149-214: Good streaming implementation with one error handling issue.

The post_stream method follows established patterns and correctly implements streaming POST requests. However, there's an issue with the HTTPError exception handling.

In Line 203, the HTTPError exception handler references response which may not be defined if the exception occurs before the response assignment. This could cause a NameError:

        except requests.exceptions.HTTPError as err:
-            raise MeilisearchApiError(str(err), response) from err
+            # For HTTPError, we need to extract response from the exception
+            # since response might not be in scope if error occurs during assignment
+            http_response = getattr(err, 'response', None)
+            if http_response is not None:
+                raise MeilisearchApiError(str(err), http_response) from err
+            else:
+                raise MeilisearchCommunicationError(str(err)) from err

Likely an incorrect or invalid review comment.

meilisearch/client.py (5)

11-11: Iterator import is correctly used.

The Iterator type is used in the return type annotation of the create_chat_completion method (Line 804), so this import is necessary despite what static analysis suggests.


16-16: MeilisearchApiError import is correctly used.

The MeilisearchApiError is used in the docstring documentation (Line 826) and is part of the public API contract, so this import is necessary despite the static analysis hint.


870-902: LGTM!

The get_chat_workspaces method is cleanly implemented with proper optional parameter handling and clear query string construction.


903-922: LGTM!

The get_chat_workspace_settings method is straightforward and correctly implemented.


924-947: LGTM!

The update_chat_workspace_settings method correctly uses the PATCH method for updating workspace settings.

tests/client/test_chat_completions.py (7)

14-37: Excellent mock implementation for streaming tests.

The MockStreamingResponse class properly simulates the requests.Response interface needed for testing streaming functionality, including proper error simulation and closure tracking.


39-67: Comprehensive test for streaming functionality.

This test thoroughly validates the streaming chat completion implementation, including HTTP call verification, chunk parsing, and proper resource cleanup.


69-75: LGTM!

This test correctly verifies that the method enforces streaming mode and raises the appropriate error when disabled.


77-89: LGTM!

This test properly validates error handling for malformed JSON in the streaming response, ensuring robust error reporting.


91-100: LGTM!

This test ensures that HTTP errors from the underlying post_stream method are properly propagated to the caller.


102-122: LGTM!

This test properly validates the get_chat_workspaces functionality with realistic mock data and correct HTTP call verification.


124-144: LGTM!

This test correctly validates the update_chat_workspace_settings functionality, ensuring proper PATCH request handling and response processing.

Copy link
Contributor

@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

🧹 Nitpick comments (3)
meilisearch/client.py (3)

855-855: Consider URL path validation for security.

The endpoint construction directly interpolates workspace_uid without validation, which could potentially allow path traversal if the UID contains malicious characters.

Consider adding basic validation or URL encoding:

-endpoint = f"chats/{workspace_uid}/chat/completions"
+# Basic validation to ensure workspace_uid doesn't contain path separators
+if "/" in workspace_uid or "\\" in workspace_uid:
+    raise ValueError("Invalid workspace_uid: must not contain path separators")
+endpoint = f"chats/{workspace_uid}/chat/completions"

Alternatively, use URL encoding if special characters are expected:

+from urllib.parse import quote
-endpoint = f"chats/{workspace_uid}/chat/completions"
+endpoint = f"chats/{quote(workspace_uid, safe='')}/chat/completions"

905-911: Consider using urllib.parse.urlencode for query string construction.

Manual query string construction works but using urllib.parse.urlencode would be more consistent with other methods in the codebase and handle edge cases better.

+from urllib import parse

def get_chat_workspaces(
    self,
    *,
    offset: Optional[int] = None,
    limit: Optional[int] = None,
) -> Dict[str, Any]:
    # ... docstring ...
-    q = []
-    if offset is not None:
-        q.append(f"offset={offset}")
-    if limit is not None:
-        q.append(f"limit={limit}")
-    path = "chats" + ("?" + "&".join(q) if q else "")
+    params = {}
+    if offset is not None:
+        params["offset"] = offset
+    if limit is not None:
+        params["limit"] = limit
+    path = "chats" + ("?" + parse.urlencode(params) if params else "")
    return self.http.get(path)

Note: The parse import is already available at the top of the file.


880-885: Consider adding input validation for pagination parameters.

The method should validate that offset and limit are non-negative when provided.

def get_chat_workspaces(
    self,
    *,
    offset: Optional[int] = None,
    limit: Optional[int] = None,
) -> Dict[str, Any]:
+    if offset is not None and offset < 0:
+        raise ValueError("offset must be non-negative")
+    if limit is not None and limit < 1:
+        raise ValueError("limit must be positive")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38687f3 and ca0b059.

📒 Files selected for processing (1)
  • meilisearch/client.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
meilisearch/client.py (3)
meilisearch/_httprequests.py (2)
  • post_stream (149-213)
  • get (95-96)
meilisearch/errors.py (3)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchError (17-25)
tests/client/test_chat_completions.py (2)
  • iter_lines (21-23)
  • close (25-27)
🪛 Ruff (0.12.2)
meilisearch/client.py

27-27: meilisearch.errors.MeilisearchApiError imported but unused

Remove unused import: meilisearch.errors.MeilisearchApiError

(F401)

🔇 Additional comments (2)
meilisearch/client.py (2)

844-846: LGTM!

The validation for streaming requirement is appropriate since non-streaming mode is not currently supported by the API.


27-27: MeilisearchApiError import is used and should be retained.

Search results show multiple references to MeilisearchApiError throughout meilisearch/client.py, so the import is required and must not be removed. No changes needed here.

Copy link
Contributor

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

♻️ Duplicate comments (2)
meilisearch/client.py (2)

844-855: Add validation for messages/model/stream for robustness (matches prior feedback)

Validate non-empty messages with required keys/types, non-empty model, and boolean stream to fail fast on bad inputs.

Apply this diff:

         if not stream:
             # The API currently only supports streaming responses:
             raise ValueError("Non-streaming chat completions are not supported. Use stream=True.")

         # Basic security validation (only what's needed)
         if not workspace_uid:
             raise ValueError("workspace_uid is required and cannot be empty")
         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")

+        # Validate input payload
+        if not isinstance(messages, list) or len(messages) == 0:
+            raise ValueError("messages must be a non-empty list")
+        for i, msg in enumerate(messages):
+            if not isinstance(msg, Mapping) or "role" not in msg or "content" not in msg:
+                raise ValueError(f"messages[{i}] must be a mapping with 'role' and 'content' keys")
+            if not isinstance(msg["role"], str) or not isinstance(msg["content"], str):
+                raise ValueError(f"messages[{i}]['role'] and ['content'] must be strings")
+        if not isinstance(model, str) or not model.strip():
+            raise ValueError("model name is required and cannot be empty")
+        if not isinstance(stream, bool):
+            raise TypeError("stream must be a boolean")
+
         payload = {"model": model, "messages": messages, "stream": True}

969-979: Type-check settings mapping in addition to non-empty

Runtime type check helps catch accidental non-mapping inputs before serialization.

Apply this diff:

         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")

-        if not settings:
-            raise ValueError("settings cannot be empty")
+        if not isinstance(settings, Mapping):
+            raise TypeError("settings must be a mapping/dict")
+        if not settings:
+            raise ValueError("settings cannot be empty")

         return self.http.patch(f"chats/{workspace_uid}/settings", body=settings)
🧹 Nitpick comments (4)
meilisearch/client.py (4)

27-27: Remove unused MeilisearchApiError import (Ruff F401 / Pylint W0611)

Static analysis flags this as unused. It’s only referenced in docstrings, so the import isn’t required.

Apply this diff:

-from meilisearch.errors import MeilisearchApiError, MeilisearchCommunicationError, MeilisearchError
+from meilisearch.errors import MeilisearchCommunicationError, MeilisearchError

868-880: Harden streaming decode path against UnicodeDecodeError

If the server emits invalid UTF-8, .decode() will raise and skip your nice JSON error handling. Catch and wrap as communication error.

Apply this diff:

-                line = raw_line.decode("utf-8")
+                try:
+                    line = raw_line.decode("utf-8")
+                except UnicodeDecodeError as e:
+                    raise MeilisearchCommunicationError(
+                        f"Failed to decode chat chunk as UTF-8: {e}"
+                    ) from e
                 if line.startswith("data: "):

909-915: Validate offset/limit types and bounds

Avoid sending invalid pagination params to the API by validating integers and ranges.

Apply this diff:

-        params = {}
-        if offset is not None:
-            params["offset"] = offset
-        if limit is not None:
-            params["limit"] = limit
+        params: Dict[str, Any] = {}
+        if offset is not None:
+            if not isinstance(offset, int) or offset < 0:
+                raise ValueError("offset must be a non-negative integer")
+            params["offset"] = offset
+        if limit is not None:
+            if not isinstance(limit, int) or limit <= 0:
+                raise ValueError("limit must be a positive integer")
+            params["limit"] = limit
         path = "chats" + ("?" + parse.urlencode(params) if params else "")
         return self.http.get(path)

857-858: Consider adding a config.paths entry for 'chats' for consistency

Most endpoints use self.config.paths.*; these hard-coded "chats" strings could be centralized similarly for consistency and easier future changes.

Also applies to: 914-915, 943-944, 978-979

📜 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 ca0b059 and 3b94b75.

📒 Files selected for processing (1)
  • meilisearch/client.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
meilisearch/client.py (3)
meilisearch/_httprequests.py (4)
  • HttpRequests (19-227)
  • post_stream (149-213)
  • get (95-96)
  • patch (110-118)
meilisearch/errors.py (3)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchError (17-25)
tests/client/test_chat_completions.py (2)
  • iter_lines (21-23)
  • close (25-27)
🪛 Ruff (0.12.2)
meilisearch/client.py

27-27: meilisearch.errors.MeilisearchApiError imported but unused

Remove unused import: meilisearch.errors.MeilisearchApiError

(F401)

🪛 GitHub Actions: Tests
meilisearch/client.py

[warning] 27-27: Pylint warning: Unused import 'MeilisearchApiError' from meilisearch.errors (W0611).

🔇 Additional comments (3)
meilisearch/client.py (3)

11-22: Typing imports update looks good

Brings in Iterator for the streaming method; all imported symbols appear used. No concerns.


937-944: LGTM: consistent workspace_uid validation and path usage

Validation mirrors create_chat_completion and prevents path traversal. Implementation is clean.


813-826: No change required: model parameter is mandatory
According to the official Meilisearch Chat Completions API docs, the model field is marked as Required in every request and cannot be omitted in favor of a workspace default. The existing signature (model: str = "gpt-3.5-turbo") is correct and should remain unchanged.

Likely an incorrect or invalid review comment.

Copy link
Contributor

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

🧹 Nitpick comments (7)
meilisearch/client.py (7)

27-31: Fix lints: remove unused MeilisearchApiError import

MeilisearchApiError isn’t used in this file (only referenced in docstrings). This triggers Ruff F401 and Pylint W0611. Drop the unused import and the trailing per-line disable (it currently doesn’t suppress the warning on the multiline import anyway).

Apply:

-from meilisearch.errors import (
-    MeilisearchApiError,
-    MeilisearchCommunicationError,
-    MeilisearchError,
-)  # pylint: disable=unused-import
+from meilisearch.errors import (
+    MeilisearchCommunicationError,
+    MeilisearchError,
+)

848-857: Strengthen input validation for messages/model/stream

You already validate workspace_uid. Extend validation to catch common user errors earlier and avoid sending malformed payloads.

Apply:

         # Basic security validation (only what's needed)
         if not workspace_uid:
             raise ValueError("workspace_uid is required and cannot be empty")
         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")
 
+        # Validate messages
+        if not isinstance(messages, list) or not messages:
+            raise ValueError("messages must be a non-empty list of dicts with 'role' and 'content'")
+        for i, m in enumerate(messages):
+            if not isinstance(m, Mapping) or "role" not in m or "content" not in m:
+                raise ValueError(f"messages[{i}] must be a mapping with 'role' and 'content' keys")
+
+        # Validate model
+        if not isinstance(model, str) or not model.strip():
+            raise ValueError("model name is required and cannot be empty")
+
+        # Validate stream flag type
+        if not isinstance(stream, bool):
+            raise ValueError("stream must be a boolean")

861-862: URL-encode the workspace_uid when building the path

Even with slash/backslash checks, encoding the path segment is safer and avoids surprises with special characters like spaces, “?”, or “%”.

Apply:

-        endpoint = f"chats/{workspace_uid}/chat/completions"
+        encoded_uid = parse.quote(workspace_uid, safe="")
+        endpoint = f"chats/{encoded_uid}/chat/completions"

867-874: Leverage decode_unicode in iter_lines to simplify decoding

requests.Response.iter_lines can decode for you. This reduces branching and byte/string juggling.

Apply:

-            # Iterate over the streaming response lines
-            for raw_line in response.iter_lines():
-                if raw_line is None or raw_line == b"":
-                    continue
-
-                line = raw_line.decode("utf-8")
+            # Iterate over the streaming response lines
+            for line in response.iter_lines(decode_unicode=True):
+                if not line:
+                    continue

888-920: Optional: validate pagination inputs (offset/limit)

Guardrails on pagination parameters avoid server-side 400s and make misuse fail fast.

Apply:

         params = {}
-        if offset is not None:
+        if offset is not None:
+            if not isinstance(offset, int) or offset < 0:
+                raise ValueError("offset must be a non-negative integer")
             params["offset"] = offset
-        if limit is not None:
+        if limit is not None:
+            if not isinstance(limit, int) or limit <= 0:
+                raise ValueError("limit must be a positive integer")
             params["limit"] = limit
         path = "chats" + ("?" + parse.urlencode(params) if params else "")
         return self.http.get(path)

941-947: URL-encode workspace_uid for settings GET path

Consistent with chat completions, encode the UID to avoid malformed URLs on special characters.

Apply:

-        return self.http.get(f"chats/{workspace_uid}/settings")
+        encoded_uid = parse.quote(workspace_uid, safe="")
+        return self.http.get(f"chats/{encoded_uid}/settings")

973-983: URL-encode workspace_uid for settings PATCH path

Same rationale as above; improves robustness.

Apply:

-        return self.http.patch(f"chats/{workspace_uid}/settings", body=settings)
+        encoded_uid = parse.quote(workspace_uid, safe="")
+        return self.http.patch(f"chats/{encoded_uid}/settings", body=settings)
📜 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 3b94b75 and dd4626a.

📒 Files selected for processing (2)
  • meilisearch/client.py (2 hunks)
  • tests/client/test_chat_completions.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/client/test_chat_completions.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
meilisearch/client.py (3)
meilisearch/_httprequests.py (4)
  • HttpRequests (19-227)
  • post_stream (149-213)
  • get (95-96)
  • patch (110-118)
meilisearch/errors.py (3)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchError (17-25)
tests/client/test_chat_completions.py (2)
  • iter_lines (21-23)
  • close (25-27)
🪛 Ruff (0.12.2)
meilisearch/client.py

28-28: meilisearch.errors.MeilisearchApiError imported but unused

Remove unused import: meilisearch.errors.MeilisearchApiError

(F401)

🪛 GitHub Actions: Tests
meilisearch/client.py

[warning] 27-27: Pylint: Unused import 'MeilisearchApiError' from meilisearch.errors (W0611).

🔇 Additional comments (1)
meilisearch/client.py (1)

11-22: LGTM: typing imports (including Iterator) are appropriate

The additions are consistent with the new streaming API surface.

@Strift Strift self-requested a review August 19, 2025 12:42
Copy link
Contributor

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

♻️ Duplicate comments (1)
meilisearch/client.py (1)

851-866: Strengthen input validation and safely encode workspace_uid in path

  • Add minimal validation for model and messages for better DX and earlier failures.
  • Quote workspace_uid to prevent path confusion with reserved characters (e.g., ?, #, %), not just slashes.
         if not stream:
             # The API currently only supports streaming responses:
             raise ValueError("Non-streaming chat completions are not supported. Use stream=True.")

         # Basic security validation (only what's needed)
         if not workspace_uid:
             raise ValueError("workspace_uid is required and cannot be empty")
         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")
 
+        # Basic payload validation
+        if not isinstance(model, str) or not model.strip():
+            raise ValueError("model is required and cannot be empty")
+        if not messages or not isinstance(messages, Sequence):
+            raise ValueError("messages must be a non-empty sequence")
+
+        # Optionally validate minimal schema of each message
+        for i, m in enumerate(messages):
+            if not isinstance(m, Mapping):
+                raise ValueError(f"messages[{i}] must be a mapping")
+            if "role" not in m or "content" not in m:
+                raise ValueError(f"messages[{i}] must contain 'role' and 'content'")
+            if not isinstance(m["role"], str) or not isinstance(m["content"], str):
+                raise ValueError(f"messages[{i}]['role'|'content'] must be strings")
+
         payload = {"model": model, "messages": messages, "stream": True}
 
         # Construct the URL for the chat completions route.
-        endpoint = f"chats/{workspace_uid}/chat/completions"
+        sanitized_uid = parse.quote(workspace_uid, safe="")
+        endpoint = f"chats/{sanitized_uid}/chat/completions"
 
         # Initiate the HTTP POST request in streaming mode.
         response = self.http.post_stream(endpoint, body=payload)

If you prefer to avoid repeating validation/quoting across methods, consider a small helper:

# Place inside Client (e.g., near other @staticmethods)
@staticmethod
def _sanitize_workspace_uid(uid: str) -> str:
    if not uid:
        raise ValueError("workspace_uid is required and cannot be empty")
    if "/" in uid or "\\" in uid:
        raise ValueError("Invalid workspace_uid: must not contain path separators")
    return parse.quote(uid, safe="")
🧹 Nitpick comments (6)
meilisearch/client.py (6)

27-31: Nit: Drop the noqa; aliasing approach is fine

  • The class-level alias for MeilisearchApiError is acceptable for docstring references.
  • The import is actually used (via the alias and direct references), so the inline # noqa: F401 is likely unnecessary.

Apply this tiny cleanup:

-from meilisearch.errors import (  # noqa: F401
+from meilisearch.errors import (
     MeilisearchApiError,
     MeilisearchCommunicationError,
     MeilisearchError,
 )

Also applies to: 46-48


816-822: Broaden messages type for forward-compatibility

Consider allowing additional keys and collection types to match evolving chat payloads without forcing casts for users.

-        messages: List[Dict[str, str]],
+        messages: Sequence[Mapping[str, Any]],

881-887: Include a small data preview on JSON parse errors for faster debugging

Augment the error message with a short preview of the problematic payload.

-                    except json.JSONDecodeError as e:
-                        raise MeilisearchCommunicationError(
-                            f"Failed to parse chat chunk: {e}"
-                        ) from e
+                    except json.JSONDecodeError as e:
+                        raw_preview = data[:200]
+                        raise MeilisearchCommunicationError(
+                            f"Failed to parse chat chunk: {e}. data preview='{raw_preview}'"
+                        ) from e

916-922: Validate offset/limit to catch bad inputs early

Guard against negative or invalid values before building the request.

-        params = {}
+        params = {}
+        if offset is not None and (not isinstance(offset, int) or offset < 0):
+            raise ValueError("offset must be a non-negative integer")
+        if limit is not None and (not isinstance(limit, int) or limit <= 0):
+            raise ValueError("limit must be a positive integer")
         if offset is not None:
             params["offset"] = offset
         if limit is not None:
             params["limit"] = limit
         path = "chats" + ("?" + parse.urlencode(params) if params else "")
         return self.http.get(path)

944-951: URL-encode workspace_uid to avoid path issues

Safely encode the UID to avoid accidental query/fragment injection or path corruption.

         # Basic security validation (only what's needed)
         if not workspace_uid:
             raise ValueError("workspace_uid is required and cannot be empty")
         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")
 
-        return self.http.get(f"chats/{workspace_uid}/settings")
+        sanitized_uid = parse.quote(workspace_uid, safe="")
+        return self.http.get(f"chats/{sanitized_uid}/settings")

976-985: Same hardening here: URL-encode workspace_uid before building the path

         # Basic security validation (only what's needed)
         if not workspace_uid:
             raise ValueError("workspace_uid is required and cannot be empty")
         if "/" in workspace_uid or "\\" in workspace_uid:
             raise ValueError("Invalid workspace_uid: must not contain path separators")
 
+        sanitized_uid = parse.quote(workspace_uid, safe="")
         if not settings:
             raise ValueError("settings cannot be empty")
 
-        return self.http.patch(f"chats/{workspace_uid}/settings", body=settings)
+        return self.http.patch(f"chats/{sanitized_uid}/settings", body=settings)
📜 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 dd4626a and 6ce0850.

📒 Files selected for processing (1)
  • meilisearch/client.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
meilisearch/client.py (3)
meilisearch/_httprequests.py (4)
  • HttpRequests (19-227)
  • post_stream (149-213)
  • get (95-96)
  • patch (110-118)
meilisearch/errors.py (3)
  • MeilisearchApiError (28-51)
  • MeilisearchCommunicationError (54-58)
  • MeilisearchError (17-25)
tests/client/test_chat_completions.py (2)
  • iter_lines (21-23)
  • close (25-27)
🔇 Additional comments (1)
meilisearch/client.py (1)

11-22: Typing imports look appropriate for streaming and new endpoints

Adding Iterator, Mapping, MutableMapping, Optional, Sequence, etc., aligns with the new APIs’ signatures and usage.

@curquiza curquiza added the enhancement New feature or request label Aug 19, 2025
Copy link
Contributor

@Strift Strift left a comment

Choose a reason for hiding this comment

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

LGTM

@Strift Strift added this pull request to the merge queue Aug 20, 2025
Merged via the queue into meilisearch:main with commit 07e6ab7 Aug 20, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants