11import copy
2+ import inspect
23import mimetypes
34import os
45import uuid
@@ -166,15 +167,33 @@ async def generate(
166167 generation_kwargs .pop ("max_completion_tokens" , None )
167168
168169 try :
169- response = await self .client .chat .completions .create (
170- model = self .model ,
171- messages = messages ,
172- tools = (_convert_tool (tool ) for tool in tools ),
173- stream = self .stream ,
174- stream_options = {"include_usage" : True } if self .stream else omit ,
175- ** generation_kwargs ,
176- )
177- return KimiStreamedMessage (response )
170+ if self .stream :
171+ # ``with_raw_response`` eagerly reads the response body in the
172+ # OpenAI SDK. Use the normal streaming path so callers receive
173+ # the AsyncStream as soon as response headers arrive.
174+ parsed_response = await cast (Any , self .client .chat .completions .create )(
175+ model = self .model ,
176+ messages = messages ,
177+ tools = (_convert_tool (tool ) for tool in tools ),
178+ stream = True ,
179+ stream_options = {"include_usage" : True },
180+ ** generation_kwargs ,
181+ )
182+ trace_id = parsed_response .response .headers .get ("x-trace-id" )
183+ else :
184+ raw_response = await self .client .chat .completions .with_raw_response .create (
185+ model = self .model ,
186+ messages = messages ,
187+ tools = (_convert_tool (tool ) for tool in tools ),
188+ stream = False ,
189+ stream_options = omit ,
190+ ** generation_kwargs ,
191+ )
192+ trace_id = raw_response .headers .get ("x-trace-id" )
193+ parsed_response = raw_response .parse ()
194+ if inspect .isawaitable (parsed_response ):
195+ parsed_response = await parsed_response
196+ return KimiStreamedMessage (parsed_response , trace_id = trace_id )
178197 except (OpenAIError , httpx .HTTPError ) as e :
179198 raise convert_error (e ) from e
180199
@@ -372,13 +391,19 @@ def _convert_tool(tool: Tool) -> ChatCompletionToolParam:
372391class KimiStreamedMessage :
373392 """The streamed message of the Kimi chat provider."""
374393
375- def __init__ (self , response : ChatCompletion | AsyncStream [ChatCompletionChunk ]):
394+ def __init__ (
395+ self ,
396+ response : ChatCompletion | AsyncStream [ChatCompletionChunk ],
397+ * ,
398+ trace_id : str | None = None ,
399+ ):
376400 if isinstance (response , ChatCompletion ):
377401 self ._iter = self ._convert_non_stream_response (response )
378402 else :
379403 self ._iter = self ._convert_stream_response (response )
380404 self ._id : str | None = None
381405 self ._usage : CompletionUsage | None = None
406+ self ._trace_id = trace_id
382407
383408 def __aiter__ (self ) -> AsyncIterator [StreamedMessagePart ]:
384409 return self
@@ -390,6 +415,10 @@ async def __anext__(self) -> StreamedMessagePart:
390415 def id (self ) -> str | None :
391416 return self ._id
392417
418+ @property
419+ def trace_id (self ) -> str | None :
420+ return self ._trace_id
421+
393422 @property
394423 def usage (self ) -> TokenUsage | None :
395424 if self ._usage :
0 commit comments