|
| 1 | +from agentscope.message import Msg |
| 2 | +from loguru import logger |
| 3 | + |
| 4 | +from ajet import AjetTuner, Workflow, WorkflowOutput, WorkflowTask |
| 5 | + |
| 6 | + |
| 7 | +def extract_final_answer(result) -> str: |
| 8 | + """Extract the final answer from the agent's response.""" |
| 9 | + try: |
| 10 | + if ( |
| 11 | + hasattr(result, "metadata") |
| 12 | + and isinstance(result.metadata, dict) |
| 13 | + and "result" in result.metadata |
| 14 | + ): |
| 15 | + return result.metadata["result"] |
| 16 | + if hasattr(result, "content"): |
| 17 | + if isinstance(result.content, dict) and "result" in result.content: |
| 18 | + return result.content["result"] |
| 19 | + return str(result.content) |
| 20 | + return str(result) |
| 21 | + except Exception as e: |
| 22 | + logger.warning(f"Extract final answer error: {e}. Raw: {result}") |
| 23 | + return str(result) |
| 24 | + |
| 25 | + |
| 26 | +system_prompt = """ |
| 27 | +You are an agent specialized in solving math problems with tools. |
| 28 | +Please solve the math problem given to you. |
| 29 | +You can write and execute Python code to perform calculation or verify your answer. |
| 30 | +You should return your final answer within \\boxed{{}}. |
| 31 | +""" |
| 32 | + |
| 33 | + |
| 34 | +class ExampleMathLearn(Workflow): |
| 35 | + name: str = "math_agent_workflow" |
| 36 | + |
| 37 | + async def execute(self, workflow_task: WorkflowTask, tuner: AjetTuner) -> WorkflowOutput: |
| 38 | + from agentscope.agent import ReActAgent |
| 39 | + from agentscope.formatter import DashScopeChatFormatter |
| 40 | + from agentscope.memory import InMemoryMemory |
| 41 | + from agentscope.tool import Toolkit, execute_python_code |
| 42 | + |
| 43 | + query = workflow_task.task.main_query |
| 44 | + self.toolkit = Toolkit() |
| 45 | + self.toolkit.register_tool_function(execute_python_code) |
| 46 | + self.agent = ReActAgent( |
| 47 | + name="math_react_agent", |
| 48 | + sys_prompt=system_prompt, |
| 49 | + model=tuner.as_agentscope_model(), |
| 50 | + formatter=DashScopeChatFormatter(), |
| 51 | + toolkit=self.toolkit, |
| 52 | + memory=InMemoryMemory(), |
| 53 | + max_iters=2, |
| 54 | + ) |
| 55 | + self.agent.set_console_output_enabled(False) |
| 56 | + msg = Msg("user", query, role="user") |
| 57 | + result = await self.agent.reply(msg) |
| 58 | + final_answer = extract_final_answer(result) |
| 59 | + return WorkflowOutput(reward=None, metadata={"final_answer": final_answer}) |
0 commit comments