Skip to content

A programming framework for agentic AI

Cancellation for model client #90 (#240)

Eric Zhuc85da398a037
diff --git a/python/src/agnext/components/models/_model_client.py b/python/src/agnext/components/models/_model_client.py
index 06cb39de9..36696ae0b 100644
--- a/python/src/agnext/components/models/_model_client.py
+++ b/python/src/agnext/components/models/_model_client.py
@@ -11,6 +11,7 @@ from typing_extensions import (
Union,
)
+from ...core import CancellationToken
from ..tools import Tool, ToolSchema
from ._types import CreateResult, LLMMessage, RequestUsage
@@ -32,6 +33,7 @@ class ChatCompletionClient(Protocol):
# A value means to override the client default - often specified in the constructor
json_output: Optional[bool] = None,
extra_create_args: Mapping[str, Any] = {},
+ cancellation_token: Optional[CancellationToken] = None,
) -> CreateResult: ...
def create_stream(
@@ -42,6 +44,7 @@ class ChatCompletionClient(Protocol):
# A value means to override the client default - often specified in the constructor
json_output: Optional[bool] = None,
extra_create_args: Mapping[str, Any] = {},
+ cancellation_token: Optional[CancellationToken] = None,
) -> AsyncGenerator[Union[str, CreateResult], None]: ...
def actual_usage(self) -> RequestUsage: ...
diff --git a/python/src/agnext/components/models/_openai_client.py b/python/src/agnext/components/models/_openai_client.py
index f6f2597d4..de0cc9734 100644
--- a/python/src/agnext/components/models/_openai_client.py
+++ b/python/src/agnext/components/models/_openai_client.py
@@ -1,3 +1,4 @@
+import asyncio
import inspect
import json
import logging
@@ -36,6 +37,7 @@ from typing_extensions import Unpack
from ...application.logging import EVENT_LOGGER_NAME, TRACE_LOGGER_NAME
from ...application.logging.events import LLMCallEvent
+from ...core import CancellationToken
from .. import (
FunctionCall,
Image,
@@ -298,6 +300,7 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
tools: Sequence[Tool | ToolSchema] = [],
json_output: Optional[bool] = None,
extra_create_args: Mapping[str, Any] = {},
+ cancellation_token: Optional[CancellationToken] = None,
) -> CreateResult:
# Make sure all extra_create_args are valid
extra_create_args_keys = set(extra_create_args.keys())
@@ -336,14 +339,18 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
if len(tools) > 0:
converted_tools = convert_tools(tools)
- result = await self._client.chat.completions.create(
- messages=oai_messages,
- stream=False,
- tools=converted_tools,
- **create_args,
+ future = asyncio.ensure_future(
+ self._client.chat.completions.create(
+ messages=oai_messages, stream=False, tools=converted_tools, **create_args
+ )
)
else:
- result = await self._client.chat.completions.create(messages=oai_messages, stream=False, **create_args)
+ future = asyncio.ensure_future(
+ self._client.chat.completions.create(messages=oai_messages, stream=False, **create_args)
+ )
+ if cancellation_token is not None:
+ cancellation_token.link_future(future)
+ result = await future
if result.usage is not None:
logger.info(
@@ -362,7 +369,7 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
if self._resolved_model is not None:
if self._resolved_model != result.model:
warnings.warn(
- f"Resolved model mismatch: {self._resolved_model} != {result.model}. AutoGen model mapping may be incorrect.",
+ f"Resolved model mismatch: {self._resolved_model} != {result.model}. Model mapping may be incorrect.",
stacklevel=2,
)
@@ -404,6 +411,7 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
tools: Sequence[Tool | ToolSchema] = [],
json_output: Optional[bool] = None,
extra_create_args: Mapping[str, Any] = {},
+ cancellation_token: Optional[CancellationToken] = None,
) -> AsyncGenerator[Union[str, CreateResult], None]:
# Make sure all extra_create_args are valid
extra_create_args_keys = set(extra_create_args.keys())
@@ -436,11 +444,18 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
if len(tools) > 0:
converted_tools = convert_tools(tools)
- stream = await self._client.chat.completions.create(
- messages=oai_messages, stream=True, tools=converted_tools, **create_args
+ stream_future = asyncio.ensure_future(
+ self._client.chat.completions.create(
+ messages=oai_messages, stream=True, tools=converted_tools, **create_args
+ )
)
else:
- stream = await self._client.chat.completions.create(messages=oai_messages, stream=True, **create_args)
+ stream_future = asyncio.ensure_future(
+ self._client.chat.completions.create(messages=oai_messages, stream=True, **create_args)
+ )
+ if cancellation_token is not None:
+ cancellation_token.link_future(stream_future)
+ stream = await stream_future
stop_reason = None
maybe_model = None
@@ -448,33 +463,40 @@ class BaseOpenAIChatCompletionClient(ChatCompletionClient):
full_tool_calls: Dict[int, FunctionCall] = {}
completion_tokens = 0
- async for chunk in stream:
- choice = chunk.choices[0]
- stop_reason = choice.finish_reason
- maybe_model = chunk.model
- # First try get content
- if choice.delta.content is not None:
- content_deltas.append(choice.delta.content)
- if len(choice.delta.content) > 0:
- yield choice.delta.content
- continue
-
- # Otherwise, get tool calls
- if choice.delta.tool_calls is not None:
- for tool_call_chunk in choice.delta.tool_calls:
- idx = tool_call_chunk.index
- if idx not in full_tool_calls:
- # We ignore the type hint here because we want to fill in type when the delta provides it
- full_tool_calls[idx] = FunctionCall(id="", arguments="", name="")
-
- if tool_call_chunk.id is not None:
- full_tool_calls[idx].id += tool_call_chunk.id
-
- if tool_call_chunk.function is not None:
- if tool_call_chunk.function.name is not None:
- full_tool_calls[idx].name += tool_call_chunk.function.name
- if tool_call_chunk.function.arguments is not None:
- full_tool_calls[idx].arguments += tool_call_chunk.function.arguments
+ while True:
+ try:
+ chunk_future = asyncio.ensure_future(anext(stream))
+ if cancellation_token is not None:
+ cancellation_token.link_future(chunk_future)
+ chunk = await chunk_future
+ choice = chunk.choices[0]
+ stop_reason = choice.finish_reason
+ maybe_model = chunk.model
+ # First try get content
+ if choice.delta.content is not None:
+ content_deltas.append(choice.delta.content)
+ if len(choice.delta.content) > 0:
+ yield choice.delta.content
+ continue
+
+ # Otherwise, get tool calls
+ if choice.delta.tool_calls is not None:
+ for tool_call_chunk in choice.delta.tool_calls:
+ idx = tool_call_chunk.index
+ if idx not in full_tool_calls:
+ # We ignore the type hint here because we want to fill in type when the delta provides it
+ full_tool_calls[idx] = FunctionCall(id="", arguments="", name="")
+
+ if tool_call_chunk.id is not None:
+ full_tool_calls[idx].id += tool_call_chunk.id
+
+ if tool_call_chunk.function is not None:
+ if tool_call_chunk.function.name is not None:
+ full_tool_calls[idx].name += tool_call_chunk.function.name
+ if tool_call_chunk.function.arguments is not None:
+ full_tool_calls[idx].arguments += tool_call_chunk.function.arguments
+ except StopAsyncIteration:
+ break
model = maybe_model or create_args["model"]
model = model.replace("gpt-35", "gpt-3.5") # hack for Azure API
diff --git a/python/tests/test_model_client.py b/python/tests/test_model_client.py
index 18112d788..47f36ac13 100644
--- a/python/tests/test_model_client.py
+++ b/python/tests/test_model_client.py
@@ -1,10 +1,12 @@
-from typing import List
+import asyncio
+from typing import Any, AsyncGenerator, List
import pytest
from agnext.components import Image
from agnext.components.models import (
AssistantMessage,
AzureOpenAIChatCompletionClient,
+ CreateResult,
FunctionExecutionResult,
FunctionExecutionResultMessage,
LLMMessage,
@@ -12,9 +14,60 @@ from agnext.components.models import (
SystemMessage,
UserMessage,
)
+from agnext.components.models._model_info import resolve_model
from agnext.components.tools import FunctionTool
+from agnext.core import CancellationToken
+from openai.resources.chat.completions import AsyncCompletions
+from openai.types.chat.chat_completion import ChatCompletion, Choice
+from openai.types.chat.chat_completion_chunk import ChatCompletionChunk, ChoiceDelta
+from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice
+from openai.types.chat.chat_completion_message import ChatCompletionMessage
+from openai.types.completion_usage import CompletionUsage
+async def _mock_create_stream(*args: Any, **kwargs: Any) -> AsyncGenerator[ChatCompletionChunk, None]:
+ model = resolve_model(kwargs.get("model", "gpt-4o"))
+ chunks = ["Hello", " Another Hello", " Yet Another Hello"]
+ for chunk in chunks:
+ await asyncio.sleep(0.1)
+ yield ChatCompletionChunk(
+ id="id",
+ choices=[
+ ChunkChoice(
+ finish_reason="stop",
+ index=0,
+ delta=ChoiceDelta(
+ content=chunk,
+ role="assistant",
+ ),
+ )
+ ],
+ created=0,
+ model=model,
+ object="chat.completion.chunk",
+ )
+
+
+async def _mock_create(
+ *args: Any, **kwargs: Any
+) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
+ stream = kwargs.get("stream", False)
+ model = resolve_model(kwargs.get("model", "gpt-4o"))
+ if not stream:
+ await asyncio.sleep(0.1)
+ return ChatCompletion(
+ id="id",
+ choices=[
+ Choice(finish_reason="stop", index=0, message=ChatCompletionMessage(content="Hello", role="assistant"))
+ ],
+ created=0,
+ model=model,
+ object="chat.completion",
+ usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
+ )
+ else:
+ return _mock_create_stream(*args, **kwargs)
+
@pytest.mark.asyncio
async def test_openai_chat_completion_client() -> None:
client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
@@ -33,10 +86,60 @@ async def test_azure_openai_chat_completion_client() -> None:
assert client
+async def test_openai_chat_completion_client_create(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
+ client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
+ result = await client.create(messages=[UserMessage(content="Hello", source="user")])
+ assert result.content == "Hello"
+
+
+async def test_openai_chat_completion_client_create_stream(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
+ client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
+ chunks: List[str | CreateResult] = []
+ async for chunk in client.create_stream(messages=[UserMessage(content="Hello", source="user")]):
+ chunks.append(chunk)
+ assert chunks[0] == "Hello"
+ assert chunks[1] == " Another Hello"
+ assert chunks[2] == " Yet Another Hello"
+ assert isinstance(chunks[-1], CreateResult)
+ assert chunks[-1].content == "Hello Another Hello Yet Another Hello"
+
+
+async def test_openai_chat_completion_client_create_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
+ client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
+ cancellation_token = CancellationToken()
+ task = asyncio.create_task(
+ client.create(messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token)
+ )
+ cancellation_token.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_openai_chat_completion_client_create_stream_cancel(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(AsyncCompletions, "create", _mock_create)
+ client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
+ cancellation_token = CancellationToken()
+ stream = client.create_stream(
+ messages=[UserMessage(content="Hello", source="user")], cancellation_token=cancellation_token
+ )
+ assert await anext(stream)
+ cancellation_token.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in stream:
+ pass
+
+
@pytest.mark.asyncio
async def test_openai_chat_completion_client_count_tokens() -> None:
client = OpenAIChatCompletionClient(model="gpt-4o", api_key="api_key")
- messages : List[LLMMessage] = [
+ messages: List[LLMMessage] = [
SystemMessage(content="Hello"),
UserMessage(content="Hello", source="user"),
AssistantMessage(content="Hello", source="assistant"),