Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(ollama): close the delegated provider stream (#3906)
Wang guanyu3a9f788d8cd8
diff --git a/src/agentscope/model/_ollama/_model.py b/src/agentscope/model/_ollama/_model.pyindex 4cd2413e5..5752ae44a 100644--- a/src/agentscope/model/_ollama/_model.py+++ b/src/agentscope/model/_ollama/_model.py@@ -1,5 +1,6 @@# -*- coding: utf-8 -*-"""The Ollama chat model implementation."""+import inspectimport jsonfrom datetime import datetimefrom typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type@@ -256,49 +257,60 @@ class OllamaChatModel(ChatModelBase):text_id: str = _generate_id()thinking_id: str = _generate_id()- async for chunk in response:- delta_res = ChatResponse(- content=[],- is_last=False,- id=response_id,- )-- msg = chunk.message-- # Thinking- if getattr(msg, "thinking", None):- delta_res.append_thinking(- block_id=thinking_id,- thinking=msg.thinking,+ try:+ async for chunk in response:+ delta_res = ChatResponse(+ content=[],+ is_last=False,+ id=response_id,)- # Text- if msg.content:- delta_res.append_text(- block_id=text_id,- text=msg.content,- )-- # Tool call. The ollama client drops the server's call id, and- # one built from the position repeats in the next round- for tool_call in msg.tool_calls or []:- delta_res.append_tool_call(- block_id=_generate_id(),- name=tool_call.function.name,- input=json.dumps(- tool_call.function.arguments,- ensure_ascii=False,- ),+ msg = chunk.message++ # Thinking+ if getattr(msg, "thinking", None):+ delta_res.append_thinking(+ block_id=thinking_id,+ thinking=msg.thinking,+ )++ # Text+ if msg.content:+ delta_res.append_text(+ block_id=text_id,+ text=msg.content,+ )++ # The client drops the server's call id; positions repeat+ # in the next round, so allocate a fresh id per call.+ for tool_call in msg.tool_calls or []:+ delta_res.append_tool_call(+ block_id=_generate_id(),+ name=tool_call.function.name,+ input=json.dumps(+ tool_call.function.arguments,+ ensure_ascii=False,+ ),+ )++ current_time = (+ datetime.now() - start_datetime+ ).total_seconds()+ delta_res.usage = ChatUsage(+ input_tokens=getattr(chunk, "prompt_eval_count", 0) or 0,+ output_tokens=getattr(chunk, "eval_count", 0) or 0,+ time=current_time,)- current_time = (datetime.now() - start_datetime).total_seconds()- delta_res.usage = ChatUsage(- input_tokens=getattr(chunk, "prompt_eval_count", 0) or 0,- output_tokens=getattr(chunk, "eval_count", 0) or 0,- time=current_time,- )-- yield delta_res+ yield delta_res+ finally:+ # Closing the parser does not implicitly close its delegated+ # SDK generator. Await its response cleanup before returning.+ aclose = getattr(response, "aclose", None)+ if aclose is not None:+ result = aclose()+ if inspect.isawaitable(result):+ await resultasync def _parse_completion_response(self,