Skip to content

Commit 38687f3

Browse files
committed
improved formatting for integration workflow
1 parent 5577004 commit 38687f3

File tree

3 files changed

+51
-45
lines changed

3 files changed

+51
-45
lines changed

meilisearch/_httprequests.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import json
44
from functools import lru_cache
5-
from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union
5+
from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple, Type, Union
66

77
import requests
88

@@ -157,14 +157,14 @@ def post_stream(
157157
serializer: Optional[Type[json.JSONEncoder]] = None,
158158
) -> requests.Response:
159159
"""Send a POST request with streaming enabled.
160-
160+
161161
Returns the raw response object for streaming consumption.
162162
"""
163163
if content_type:
164164
self.headers["Content-Type"] = content_type
165165
try:
166166
request_path = self.config.url + "/" + path
167-
167+
168168
if isinstance(body, bytes):
169169
response = requests.post(
170170
request_path,
@@ -182,17 +182,17 @@ def post_stream(
182182
)
183183

184184
response = requests.post(
185-
request_path,
186-
timeout=self.config.timeout,
187-
headers=self.headers,
185+
request_path,
186+
timeout=self.config.timeout,
187+
headers=self.headers,
188188
data=data,
189189
stream=True,
190190
)
191-
191+
192192
# For streaming responses, we validate status but don't parse JSON
193193
if not response.ok:
194194
response.raise_for_status()
195-
195+
196196
return response
197197

198198
except requests.exceptions.Timeout as err:

meilisearch/client.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,23 @@
88
import hmac
99
import json
1010
import re
11-
from typing import Any, Dict, Iterator, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
11+
from typing import (
12+
Any,
13+
Dict,
14+
Iterator,
15+
List,
16+
Mapping,
17+
MutableMapping,
18+
Optional,
19+
Sequence,
20+
Tuple,
21+
Union,
22+
)
1223
from urllib import parse
1324

1425
from meilisearch._httprequests import HttpRequests
1526
from meilisearch.config import Config
16-
from meilisearch.errors import MeilisearchApiError, MeilisearchCommunicationError, MeilisearchError
27+
from meilisearch.errors import MeilisearchCommunicationError, MeilisearchError
1728
from meilisearch.index import Index
1829
from meilisearch.models.key import Key, KeysResults
1930
from meilisearch.models.task import Batch, BatchResults, Task, TaskInfo, TaskResults
@@ -839,31 +850,30 @@ def create_chat_completion(
839850
"messages": messages,
840851
"stream": True
841852
}
842-
853+
843854
# Construct the URL for the chat completions route.
844855
endpoint = f"chats/{workspace_uid}/chat/completions"
845-
856+
846857
# Initiate the HTTP POST request in streaming mode.
847858
response = self.http.post_stream(endpoint, body=payload)
848-
859+
849860
try:
850861
# Iterate over the streaming response lines
851862
for raw_line in response.iter_lines():
852863
if raw_line is None or raw_line == b'':
853-
continue
854-
864+
continue
865+
855866
line = raw_line.decode('utf-8')
856867
if line.startswith("data: "):
857-
data = line[len("data: "):]
868+
data = line[len("data: "):]
858869
if data.strip() == "[DONE]":
859-
break
860-
870+
break
871+
861872
try:
862873
chunk = json.loads(data)
863874
yield chunk
864875
except json.JSONDecodeError as e:
865-
866-
raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}")
876+
raise MeilisearchCommunicationError(f"Failed to parse chat chunk: {e}") from e
867877
finally:
868878
response.close()
869879

tests/client/test_chat_completions.py

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,31 @@
11
# pylint: disable=invalid-name
22

3-
import json
43
from unittest.mock import patch
54

65
import pytest
76
import requests
87

9-
import meilisearch
108
from meilisearch.errors import MeilisearchApiError, MeilisearchCommunicationError
11-
from tests import BASE_URL, MASTER_KEY
129

1310

1411
class MockStreamingResponse:
1512
"""Mock response object for testing streaming functionality."""
16-
13+
1714
def __init__(self, lines, ok=True, status_code=200, text=""):
1815
self.lines = lines
1916
self.ok = ok
2017
self.status_code = status_code
2118
self.text = text
2219
self._closed = False
23-
20+
2421
def iter_lines(self):
2522
"""Simulate iter_lines() method of requests.Response."""
26-
for line in self.lines:
27-
yield line
28-
23+
yield from self.lines
24+
2925
def close(self):
3026
"""Simulate close() method of requests.Response."""
3127
self._closed = True
32-
28+
3329
def raise_for_status(self):
3430
"""Simulate raise_for_status() method of requests.Response."""
3531
if not self.ok:
@@ -44,11 +40,11 @@ def test_create_chat_completion_basic_stream(client):
4440
b'data: [DONE]'
4541
]
4642
mock_resp = MockStreamingResponse(dummy_lines)
47-
43+
4844
with patch.object(client.http, 'post_stream', return_value=mock_resp) as mock_post:
4945
messages = [{"role": "user", "content": "Hi"}]
5046
chunks = list(client.create_chat_completion("my-assistant", messages=messages))
51-
47+
5248
# Verify the HTTP call was made correctly
5349
mock_post.assert_called_once_with(
5450
"chats/my-assistant/chat/completions",
@@ -58,18 +54,18 @@ def test_create_chat_completion_basic_stream(client):
5854
"stream": True
5955
}
6056
)
61-
57+
6258
# Verify the chunks are parsed correctly
6359
assert len(chunks) == 2
6460
assert chunks[0]["choices"][0]["delta"]["content"] == "Hello"
6561
assert chunks[1]["choices"][0]["delta"]["content"] == " world"
66-
assert mock_resp._closed
62+
assert mock_resp._closed # pylint: disable=protected-access
6763

6864

6965
def test_create_chat_completion_stream_false_raises_error(client):
7066
"""Test that stream=False raises ValueError."""
7167
messages = [{"role": "user", "content": "Test"}]
72-
68+
7369
with pytest.raises(ValueError, match="Non-streaming chat completions are not supported"):
7470
list(client.create_chat_completion("my-assistant", messages=messages, stream=False))
7571

@@ -80,10 +76,10 @@ def test_create_chat_completion_json_decode_error(client):
8076
b'data: {"invalid": json}', # Malformed JSON
8177
]
8278
mock_resp = MockStreamingResponse(dummy_lines)
83-
79+
8480
with patch.object(client.http, 'post_stream', return_value=mock_resp):
8581
messages = [{"role": "user", "content": "Test"}]
86-
82+
8783
with pytest.raises(MeilisearchCommunicationError, match="Failed to parse chat chunk"):
8884
list(client.create_chat_completion("my-assistant", messages=messages))
8985

@@ -94,7 +90,7 @@ def test_create_chat_completion_http_error_propagated(client):
9490
error_response = MockStreamingResponse([], ok=False, status_code=400, text='{"message": "API Error"}')
9591
mock_post.side_effect = MeilisearchApiError("API Error", error_response)
9692
messages = [{"role": "user", "content": "Test"}]
97-
93+
9894
with pytest.raises(MeilisearchApiError, match="API Error"):
9995
list(client.create_chat_completion("my-assistant", messages=messages))
10096

@@ -110,13 +106,13 @@ def test_get_chat_workspaces(client):
110106
"limit": 20,
111107
"total": 2
112108
}
113-
109+
114110
with patch.object(client.http, 'get', return_value=mock_response) as mock_get:
115111
result = client.get_chat_workspaces()
116-
112+
117113
# Verify the HTTP call was made correctly
118114
mock_get.assert_called_once_with("chats")
119-
115+
120116
# Verify the response is returned as-is
121117
assert result == mock_response
122118

@@ -128,17 +124,17 @@ def test_update_chat_workspace_settings(client):
128124
"temperature": 0.8,
129125
"max_tokens": 1500
130126
}
131-
127+
132128
settings_update = {
133129
"temperature": 0.8,
134130
"max_tokens": 1500
135131
}
136-
132+
137133
with patch.object(client.http, 'patch', return_value=mock_response) as mock_patch:
138134
result = client.update_chat_workspace_settings("my-workspace", settings_update)
139-
135+
140136
# Verify the HTTP call was made correctly
141137
mock_patch.assert_called_once_with("chats/my-workspace/settings", body=settings_update)
142-
138+
143139
# Verify the response is returned as-is
144-
assert result == mock_response
140+
assert result == mock_response

0 commit comments

Comments
 (0)