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.

userproxy.py 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from typing import Callable, List, Optional, Sequence, Union, Awaitable
  2. from inspect import iscoroutinefunction
  3. from autogen_agentchat.agents import BaseChatAgent
  4. from autogen_agentchat.base import Response
  5. from autogen_agentchat.messages import ChatMessage, TextMessage
  6. from autogen_core.base import CancellationToken
  7. import asyncio
  8. class UserProxyAgent(BaseChatAgent):
  9. """An agent that can represent a human user in a chat."""
  10. def __init__(
  11. self,
  12. name: str,
  13. description: Optional[str] = "a",
  14. input_func: Optional[Union[Callable[..., str],
  15. Callable[..., Awaitable[str]]]] = None
  16. ) -> None:
  17. super().__init__(name, description=description)
  18. self.input_func = input_func or input
  19. self._is_async = iscoroutinefunction(
  20. input_func) if input_func else False
  21. @property
  22. def produced_message_types(self) -> List[type[ChatMessage]]:
  23. return [TextMessage]
  24. async def _get_input(self, prompt: str) -> str:
  25. """Handle both sync and async input functions"""
  26. if self._is_async:
  27. return await self.input_func(prompt)
  28. else:
  29. return await asyncio.get_event_loop().run_in_executor(None, self.input_func, prompt)
  30. async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> Response:
  31. try:
  32. user_input = await self._get_input("Enter your response: ")
  33. return Response(chat_message=TextMessage(content=user_input, source=self.name))
  34. except Exception as e:
  35. # Consider logging the error here
  36. raise RuntimeError(f"Failed to get user input: {str(e)}") from e
  37. async def on_reset(self, cancellation_token: CancellationToken) -> None:
  38. pass