You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_tool_use_assistant_agent.py 4.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import asyncio
  2. import json
  3. from typing import Any, AsyncGenerator, List
  4. import pytest
  5. from autogen_agentchat.agents import ToolUseAssistantAgent
  6. from autogen_agentchat.messages import (
  7. TextMessage,
  8. ToolCallMessage,
  9. ToolCallResultMessage,
  10. )
  11. from autogen_core.base import CancellationToken
  12. from autogen_core.components.models import FunctionExecutionResult, OpenAIChatCompletionClient
  13. from autogen_core.components.tools import FunctionTool
  14. from openai.resources.chat.completions import AsyncCompletions
  15. from openai.types.chat.chat_completion import ChatCompletion, Choice
  16. from openai.types.chat.chat_completion_chunk import ChatCompletionChunk
  17. from openai.types.chat.chat_completion_message import ChatCompletionMessage
  18. from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall, Function
  19. from openai.types.completion_usage import CompletionUsage
  20. class _MockChatCompletion:
  21. def __init__(self, chat_completions: List[ChatCompletion]) -> None:
  22. self._saved_chat_completions = chat_completions
  23. self._curr_index = 0
  24. async def mock_create(
  25. self, *args: Any, **kwargs: Any
  26. ) -> ChatCompletion | AsyncGenerator[ChatCompletionChunk, None]:
  27. await asyncio.sleep(0.1)
  28. completion = self._saved_chat_completions[self._curr_index]
  29. self._curr_index += 1
  30. return completion
  31. def _pass_function(input: str) -> str:
  32. return "pass"
  33. async def _fail_function(input: str) -> str:
  34. return "fail"
  35. async def _echo_function(input: str) -> str:
  36. return input
  37. @pytest.mark.asyncio
  38. async def test_round_robin_group_chat_with_tools(monkeypatch: pytest.MonkeyPatch) -> None:
  39. model = "gpt-4o-2024-05-13"
  40. chat_completions = [
  41. ChatCompletion(
  42. id="id1",
  43. choices=[
  44. Choice(
  45. finish_reason="tool_calls",
  46. index=0,
  47. message=ChatCompletionMessage(
  48. content=None,
  49. tool_calls=[
  50. ChatCompletionMessageToolCall(
  51. id="1",
  52. type="function",
  53. function=Function(
  54. name="pass",
  55. arguments=json.dumps({"input": "pass"}),
  56. ),
  57. )
  58. ],
  59. role="assistant",
  60. ),
  61. )
  62. ],
  63. created=0,
  64. model=model,
  65. object="chat.completion",
  66. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  67. ),
  68. ChatCompletion(
  69. id="id2",
  70. choices=[
  71. Choice(finish_reason="stop", index=0, message=ChatCompletionMessage(content="Hello", role="assistant"))
  72. ],
  73. created=0,
  74. model=model,
  75. object="chat.completion",
  76. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  77. ),
  78. ChatCompletion(
  79. id="id2",
  80. choices=[
  81. Choice(
  82. finish_reason="stop", index=0, message=ChatCompletionMessage(content="TERMINATE", role="assistant")
  83. )
  84. ],
  85. created=0,
  86. model=model,
  87. object="chat.completion",
  88. usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
  89. ),
  90. ]
  91. mock = _MockChatCompletion(chat_completions)
  92. monkeypatch.setattr(AsyncCompletions, "create", mock.mock_create)
  93. tool_use_agent = ToolUseAssistantAgent(
  94. "tool_use_agent",
  95. model_client=OpenAIChatCompletionClient(model=model, api_key=""),
  96. registered_tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],
  97. )
  98. response = await tool_use_agent.on_messages(
  99. messages=[TextMessage(content="Test", source="user")], cancellation_token=CancellationToken()
  100. )
  101. assert isinstance(response, ToolCallMessage)
  102. tool_call_results = [FunctionExecutionResult(content="", call_id=call.id) for call in response.content]
  103. response = await tool_use_agent.on_messages(
  104. messages=[ToolCallResultMessage(content=tool_call_results, source="test")],
  105. cancellation_token=CancellationToken(),
  106. )
  107. assert isinstance(response, TextMessage)