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.

coder_executor.py 9.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. """
  2. This example shows how to use publish-subscribe to implement
  3. a simple interaction between a coder and an executor agent.
  4. 1. The coder agent receives a task message, generates a code block,
  5. and publishes a code execution
  6. task message.
  7. 2. The executor agent receives the code execution task message,
  8. executes the code block, and publishes a code execution task result message.
  9. 3. The coder agent receives the code execution task result message, depending
  10. on the result: if the task is completed, it publishes a task completion message;
  11. otherwise, it generates a new code block and publishes a code execution task message.
  12. 4. The process continues until the coder agent publishes a task completion message.
  13. """
  14. import asyncio
  15. import os
  16. import re
  17. import sys
  18. import uuid
  19. from dataclasses import dataclass
  20. from typing import Dict, List
  21. from agnext.application import SingleThreadedAgentRuntime
  22. from agnext.components import DefaultTopicId, RoutedAgent, message_handler
  23. from agnext.components._type_subscription import TypeSubscription
  24. from agnext.components.code_executor import CodeBlock, CodeExecutor, LocalCommandLineCodeExecutor
  25. from agnext.components.models import (
  26. AssistantMessage,
  27. ChatCompletionClient,
  28. LLMMessage,
  29. SystemMessage,
  30. UserMessage,
  31. )
  32. from agnext.core import TopicId
  33. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
  34. from agnext.core import MessageContext
  35. from common.utils import get_chat_completion_client_from_envs
  36. @dataclass
  37. class TaskMessage:
  38. content: str
  39. @dataclass
  40. class TaskCompletion:
  41. content: str
  42. @dataclass
  43. class CodeExecutionTask:
  44. session_id: str
  45. content: str
  46. @dataclass
  47. class CodeExecutionTaskResult:
  48. session_id: str
  49. output: str
  50. exit_code: int
  51. class Coder(RoutedAgent):
  52. """An agent that writes code."""
  53. def __init__(
  54. self,
  55. model_client: ChatCompletionClient,
  56. ) -> None:
  57. super().__init__(description="A Python coder assistant.")
  58. self._model_client = model_client
  59. self._system_messages = [
  60. SystemMessage(
  61. """You are a helpful AI assistant.
  62. Solve tasks using your coding and language skills.
  63. In the following cases, suggest python code (in a python coding block) or shell script (in a sh coding block) for the user to execute.
  64. 1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself.
  65. 2. When you need to perform some task with code, use the code to perform the task and output the result. Finish the task smartly.
  66. Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.
  67. When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.
  68. If you want the user to save the code in a file before executing it, put # filename: <filename> inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.
  69. If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.
  70. When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.
  71. Reply "TERMINATE" in the end when everything is done."""
  72. )
  73. ]
  74. # A dictionary to store the messages for each task session.
  75. self._session_memory: Dict[str, List[LLMMessage]] = {}
  76. @message_handler
  77. async def handle_task(self, message: TaskMessage, ctx: MessageContext) -> None:
  78. # Create a new session.
  79. session_id = str(uuid.uuid4())
  80. self._session_memory.setdefault(session_id, []).append(UserMessage(content=message.content, source="user"))
  81. # Make an inference to the model.
  82. response = await self._model_client.create(self._system_messages + self._session_memory[session_id])
  83. assert isinstance(response.content, str)
  84. self._session_memory[session_id].append(
  85. AssistantMessage(content=response.content, source=self.metadata["type"])
  86. )
  87. # Publish the code execution task.
  88. await self.publish_message(
  89. CodeExecutionTask(content=response.content, session_id=session_id),
  90. cancellation_token=ctx.cancellation_token,
  91. topic_id=DefaultTopicId(),
  92. )
  93. @message_handler
  94. async def handle_code_execution_result(self, message: CodeExecutionTaskResult, ctx: MessageContext) -> None:
  95. # Store the code execution output.
  96. self._session_memory[message.session_id].append(UserMessage(content=message.output, source="user"))
  97. # Make an inference to the model -- reflection on the code execution output happens here.
  98. response = await self._model_client.create(self._system_messages + self._session_memory[message.session_id])
  99. assert isinstance(response.content, str)
  100. self._session_memory[message.session_id].append(
  101. AssistantMessage(content=response.content, source=self.metadata["type"])
  102. )
  103. if "TERMINATE" in response.content:
  104. # If the task is completed, publish a message with the completion content.
  105. await self.publish_message(
  106. TaskCompletion(content=response.content),
  107. cancellation_token=ctx.cancellation_token,
  108. topic_id=DefaultTopicId(),
  109. )
  110. print("--------------------")
  111. print("Task completed:")
  112. print(response.content)
  113. return
  114. # Publish the code execution task.
  115. await self.publish_message(
  116. CodeExecutionTask(content=response.content, session_id=message.session_id),
  117. cancellation_token=ctx.cancellation_token,
  118. topic_id=DefaultTopicId(),
  119. )
  120. class Executor(RoutedAgent):
  121. """An agent that executes code."""
  122. def __init__(self, executor: CodeExecutor) -> None:
  123. super().__init__(description="A code executor agent.")
  124. self._executor = executor
  125. @message_handler
  126. async def handle_code_execution(self, message: CodeExecutionTask, ctx: MessageContext) -> None:
  127. # Extract the code block from the message.
  128. code_blocks = self._extract_code_blocks(message.content)
  129. if not code_blocks:
  130. # If no code block is found, publish a message with an error.
  131. await self.publish_message(
  132. CodeExecutionTaskResult(
  133. output="Error: no Markdown code block found.", exit_code=1, session_id=message.session_id
  134. ),
  135. cancellation_token=ctx.cancellation_token,
  136. topic_id=DefaultTopicId(),
  137. )
  138. return
  139. # Execute code blocks.
  140. result = await self._executor.execute_code_blocks(
  141. code_blocks=code_blocks, cancellation_token=ctx.cancellation_token
  142. )
  143. # Publish the code execution result.
  144. await self.publish_message(
  145. CodeExecutionTaskResult(output=result.output, exit_code=result.exit_code, session_id=message.session_id),
  146. cancellation_token=ctx.cancellation_token,
  147. topic_id=DefaultTopicId(),
  148. )
  149. def _extract_code_blocks(self, markdown_text: str) -> List[CodeBlock]:
  150. pattern = re.compile(r"```(?:\s*([\w\+\-]+))?\n([\s\S]*?)```")
  151. matches = pattern.findall(markdown_text)
  152. code_blocks: List[CodeBlock] = []
  153. for match in matches:
  154. language = match[0].strip() if match[0] else ""
  155. code_content = match[1]
  156. code_blocks.append(CodeBlock(code=code_content, language=language))
  157. return code_blocks
  158. async def main(task: str, temp_dir: str) -> None:
  159. # Create the runtime with the termination handler.
  160. runtime = SingleThreadedAgentRuntime()
  161. # Register the agents.
  162. await runtime.register(
  163. "coder", lambda: Coder(model_client=get_chat_completion_client_from_envs(model="gpt-4-turbo"))
  164. )
  165. await runtime.register("executor", lambda: Executor(executor=LocalCommandLineCodeExecutor(work_dir=temp_dir)))
  166. await runtime.add_subscription(TypeSubscription("default", "coder"))
  167. await runtime.add_subscription(TypeSubscription("default", "executor"))
  168. runtime.start()
  169. # Publish the task message.
  170. await runtime.publish_message(TaskMessage(content=task), topic_id=TopicId("default", "default"))
  171. await runtime.stop_when_idle()
  172. if __name__ == "__main__":
  173. import logging
  174. from datetime import datetime
  175. logging.basicConfig(level=logging.WARNING)
  176. logging.getLogger("agnext").setLevel(logging.DEBUG)
  177. task = f"Today is {datetime.today()}, create a plot of NVDA and TSLA stock prices YTD using yfinance."
  178. asyncio.run(main(task, "."))