CangjieMagic智能体框架优化实战

目录

引言

工作过程

优化方法

结束语


引言

最近在使用Cangjie Magic智能体框架时觉得它有点慢,在Cangjie Magic团队的midwinter1993帮助下尝试对其运行速度进行优化,现在分享一下经验。

工作过程

这里以官方的Health Monitor示例说明一下。先看一下官方的这个示例。

/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2025. All rights reserved.
 */
package magic.examples.health_monitor

import magic.dsl.*
import magic.prelude.*
import std.time.DateTime

@tool[description: "获取当前时间"]
func getCurrentTime(): String {
    return DateTime.now().toString()
}

@tool[description: "向用户发送短信通知",
      parameters: {
          msg: "发送短信的内容"
      }
]
func sendNotification(msg: String): String {
    println(">>>>>> ${msg} <<<<<")
    return "Done"
}

@agent[model: "deepseek:deepseek-chat",
       tools: [getCurrentTime, sendNotification]]
class CgmAgent {
    @prompt(
        """
        检测用户当前血糖是否正常。回答“正常”或是“异常”
        检查结果可以结合当前所处的时间综合判断
        如果异常,则向用户发送通知并告知可实施的建议
        仅使用已有工具
        """
    )
}

//================================================
@agent[model: "deepseek:deepseek-chat",
       tools: [sendNotification]]
class HeartBeatAgent {
    @prompt(
        """
        检测用户当前心跳是否正常。回答“正常”或是“异常”
        如果异常,则向用户发送通知并告知可实施的建议
        仅使用已有工具
        """
    )
}
//================================================
@agent[model: "deepseek:deepseek-chat"]
class MonitorAgent {
    @prompt(
        """
        根据接受到的监测数据,交由不同的检测模块进行检测
        """
    )
}

main() {
    let cgmAgent = CgmAgent()
    let heartBeatAgent = HeartBeatAgent()
    let monitorAgent =  MonitorAgent()
    let group = monitorAgent <= [cgmAgent, heartBeatAgent]

    let resp = group.chat(AgentRequest("当前血糖 189 mg/dL"))
    println(resp.content)
}

这段代码实现了一个健康监测系统,使用多个智能代理协同工作。 MonitorAgent是监控路由代理,负责将输入数据分发给合适的专业代理(血糖/心跳)。HeartBeatAgent(心跳监测代理)判断心跳是否异常,异常时发送建议。 CgmAgent(血糖监测代理)结合时间因素判断血糖是否异常,异常时发送建议。

这个程序在开发者云主机上运行,大概需要90秒完成全部工作。可以看一下日志(有节选):

2025/06/13 21:51:33.844094 INFO logger React executor runs MonitorAgent
2025/06/13 21:51:33.844681 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:51:33.844717 DEBUG logger header: Content-Type - application/json
2025/06/13 21:51:33.844726 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:51:33.844786 DEBUG logger body: {"messages":[{"role":"system","content":"# Task\nGiven instructions for an agent, summarize a description of the agent's functionality.\nIf the instructions include information about inputs and outputs, this should also be described in the functional description.\nThe output should be complete but also brief.\n\n# Agent Instruction\n        检测用户当前血糖是否正常。回答“正常”或是“异常”\n        检查结果可以结合当前所处的时间综合判断\n        如果异常,则向用户发送通知并告知可实施的建议\n        仅使用已有工具\n        \n\nNow, make the summary:\n"}],"model":"DeepSeek-R1","stream":false,"temperature":0.1}
2025/06/13 21:51:43.700829 DEBUG logger Raw http response: {"id":"chat-e0f2e548996e47ee9d2165094fe0f3ff","object":"chat.completion","created":1749822694,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\nThe agent checks if a user's current blood sugar level is normal (\"正常\") or abnormal (\"异常\"), incorporating time-based context for accuracy. If abnormal, it sends a notification with actionable recommendations. It operates strictly using predefined tools without external resources.","reasoning_content":"Okay, let's see. The user wants me to summarize the agent's functionality based on the given instructions. The main task is to detect if the user's current blood sugar is normal. The agent should respond with either \"正常\" (normal) or \"异常\" (abnormal). \n\nFirst, I need to mention the core function: checking blood sugar levels. The instructions say to consider the current time when making the determination, so I should note that time is a factor in the assessment.\n\nThen, if the result is abnormal, the agent sends a notification with actionable advice. That's important to include. Also, the agent only uses existing tools, so I should mention that it relies on predefined tools without external resources.\n\nI need to keep the summary brief but complete. Let me structure it step by step. Start with the primary function, mention time consideration, then the actions taken if abnormal, and note the tool usage. Avoid any extra details not in the instructions. Make sure to use concise terms and check for clarity.\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":110,"total_tokens":370,"completion_tokens":260},"prompt_logprobs":null}
200
2025/06/13 21:51:43.701056 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:51:43.701254 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:51:43.701274 DEBUG logger header: Content-Type - application/json
2025/06/13 21:51:43.701283 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:51:43.701313 DEBUG logger body: {"messages":[{"role":"system","content":"# Task\nGiven instructions for an agent, summarize a description of the agent's functionality.\nIf the instructions include information about inputs and outputs, this should also be described in the functional description.\nThe output should be complete but also brief.\n\n# Agent Instruction\n        检测用户当前心跳是否正常。回答“正常”或是“异常”\n        如果异常,则向用户发送通知并告知可实施的建议\n        仅使用已有工具\n        \n\nNow, make the summary:\n"}],"model":"DeepSeek-R1","stream":false,"temperature":0.1}
2025/06/13 21:51:52.216539 DEBUG logger Raw http response: {"id":"chat-a36a4a3725864131a0c06ff19354ffd0","object":"chat.completion","created":1749822704,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\nThe agent monitors a user's heartbeat to determine if it is normal (\"正常\") or abnormal (\"异常\"). If abnormal, it sends a notification to the user with actionable recommendations. It strictly uses predefined tools for assessment and response, without external inputs or outputs beyond the binary classification and follow-up guidance.","reasoning_content":"Okay, let's see. The user wants me to summarize the agent's functionality based on the given instructions. The main task is to detect if the user's current heartbeat is normal or not. The agent needs to respond with either \"正常\" or \"异常\". If it's abnormal, there's an additional step to send a notification to the user and provide actionable advice. Also, the agent should only use the tools it already has.\n\nFirst, I need to capture the primary function: monitoring heartbeat status. Then, the output is binary—normal or abnormal. When abnormal, two actions: notify and suggest. Also, mention that it relies on existing tools without adding new ones. Keep it concise but include all key points: purpose, input/output, actions taken if abnormal, and tool usage restriction.\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":99,"total_tokens":323,"completion_tokens":224},"prompt_logprobs":null}
200
2025/06/13 21:51:52.216644 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:51:52.216849 INFO logger MonitorAgent: ----- Build Agent Task -----
2025/06/13 21:51:52.216884 INFO logger MonitorAgent: Chat Message[ system ]: # Guidelines
Use the following format to accomplish user's request:
[Thought] think about what to do next to solve the question [/Thought]
[Action] use a tool, the action must be a json object wrapped by ```json and ```
    ```json
    {
        "name": string, name of the tool, it must refer to one of available tools
        "arguments": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters
    }
    ```
    For example,
    ```json
    {
        "name": "foo"
        "arguments": {
            "url": "http://example.com",
            "count": 3,
            "items": ["abc", "xyz"]
        }
    }
    ```
[/Action]
[Observation] the result of the action [/Observation]
... (Thought/Action/Observation may repeat N times to accomplish user's request)
[Answer] the final answer to the original input question [/Answer]

NEVER generate [Observation] yourself. This is an important requirement.

You must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]
Examples:
Output: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]
Output: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]

- If there are no available tools, generate final answer directly.

# Available Tools
[
 {
  "name": "CgmAgent",
  "description": "\n\nThe agent checks if a user's current blood sugar level is normal (\"正常\") or abnormal (\"异常\"), incorporating time-based context for accuracy. If abnormal, it sends a notification with actionable recommendations. It operates strictly using predefined tools without external resources.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "question": {
        "type": "string",
        "description": "The input question"
      }
    },
    "required": [
      "question"
    ]
  }
},
{
  "name": "HeartBeatAgent",
  "description": "\n\nThe agent monitors a user's heartbeat to determine if it is normal (\"正常\") or abnormal (\"异常\"). If abnormal, it sends a notification to the user with actionable recommendations. It strictly uses predefined tools for assessment and response, without external inputs or outputs beyond the binary classification and follow-up guidance.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "question": {
        "type": "string",
        "description": "The input question"
      }
    },
    "required": [
      "question"
    ]
  }
} 
]
---end of tools---

        根据接受到的监测数据,交由不同的检测模块进行检测
2025/06/13 21:51:52.216908 INFO logger MonitorAgent: Chat Message[ user ]: 当前血糖 189 mg/dL
2025/06/13 21:51:52.216917 INFO logger MonitorAgent: ----- End of Build Agent Task -----
2025/06/13 21:51:52.216929 INFO logger MonitorAgent: Step #0
2025/06/13 21:51:52.216980 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:51:52.216992 DEBUG logger header: Content-Type - application/json
2025/06/13 21:51:52.217004 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:51:52.217059 DEBUG logger body: {"messages":[{"role":"system","content":"# Guidelines\nUse the following format to accomplish user's request:\n[Thought] think about what to do next to solve the question [/Thought]\n[Action] use a tool, the action must be a json object wrapped by ```json and ```\n    ```json\n    {\n        \"name\": string, name of the tool, it must refer to one of available tools\n        \"arguments\": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters\n    }\n    ```\n    For example,\n    ```json\n    {\n        \"name\": \"foo\"\n        \"arguments\": {\n            \"url\": \"http://example.com\",\n            \"count\": 3,\n            \"items\": [\"abc\", \"xyz\"]\n        }\n    }\n    ```\n[/Action]\n[Observation] the result of the action [/Observation]\n... (Thought/Action/Observation may repeat N times to accomplish user's request)\n[Answer] the final answer to the original input question [/Answer]\n\nNEVER generate [Observation] yourself. This is an important requirement.\n\nYou must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]\nExamples:\nOutput: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]\nOutput: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]\n\n- If there are no available tools, generate final answer directly.\n\n# Available Tools\n[\n {\n  \"name\": \"CgmAgent\",\n  \"description\": \"\\n\\nThe agent checks if a user's current blood sugar level is normal (\\\"正常\\\") or abnormal (\\\"异常\\\"), incorporating time-based context for accuracy. If abnormal, it sends a notification with actionable recommendations. It operates strictly using predefined tools without external resources.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"question\": {\n        \"type\": \"string\",\n        \"description\": \"The input question\"\n      }\n    },\n    \"required\": [\n      \"question\"\n    ]\n  }\n},\n{\n  \"name\": \"HeartBeatAgent\",\n  \"description\": \"\\n\\nThe agent monitors a user's heartbeat to determine if it is normal (\\\"正常\\\") or abnormal (\\\"异常\\\"). If abnormal, it sends a notification to the user with actionable recommendations. It strictly uses predefined tools for assessment and response, without external inputs or outputs beyond the binary classification and follow-up guidance.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"question\": {\n        \"type\": \"string\",\n        \"description\": \"The input question\"\n      }\n    },\n    \"required\": [\n      \"question\"\n    ]\n  }\n} \n]\n---end of tools---\n\n        根据接受到的监测数据,交由不同的检测模块进行检测"},{"role":"user","content":"当前血糖 189 mg/dL"},{"role":"system","content":"Decide what to do next. Output a pair of [Thought] and [Action], a pair of [Thought] and [Answer], or a single [Answer]"}],"model":"DeepSeek-R1","stream":false,"stop":["[Observation]"],"temperature":0.1}
2025/06/13 21:52:00.264515 DEBUG logger Raw http response: {"id":"chat-7a18623061024f7fb1303e9d1e89333c","object":"chat.completion","created":1749822712,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n[Thought] 需要调用CgmAgent来评估当前血糖值是否正常[/Thought]\n[Action]\n```json\n{\n    \"name\": \"CgmAgent\",\n    \"arguments\": {\n        \"question\": \"当前血糖 189 mg/dL\"\n    }\n}\n```\n[/Action]","reasoning_content":"好的,我现在需要处理用户的血糖数据,当前血糖值是189 mg/dL。首先,我得确定这个数值是否在正常范围内。正常血糖范围通常空腹是70-100 mg/dL,餐后两小时不超过140 mg/dL。用户提供的189明显高于正常餐后水平,可能属于异常。接下来,我应该使用CgmAgent工具来确认这个判断。根据工具描述,CgmAgent会结合时间因素,比如是否在餐后,来判断是否正常。如果确认异常,工具会发送通知并提供建议。因此,我需要调用CgmAgent,将问题参数设置为用户的当前血糖值,等待结果后再决定是否需要进一步处理或直接给出答案。\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":656,"total_tokens":856,"completion_tokens":200},"prompt_logprobs":null}
200
2025/06/13 21:52:00.264624 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:52:00.264733 INFO logger MonitorAgent: Chat Message[ assistant ]: [Thought] 需要调用CgmAgent来评估当前血糖值是否正常 [/Thought]
2025/06/13 21:52:00.264751 INFO logger MonitorAgent: Chat Message[ assistant ]: [Action] ```json
{
    "name": "CgmAgent",
    "arguments": {
        "question": "当前血糖 189 mg/dL"
    }
}
``` [/Action]
2025/06/13 21:52:00.264805 INFO logger React executor runs CgmAgent
2025/06/13 21:52:00.264976 INFO logger CgmAgent: ----- Build Agent Task -----
2025/06/13 21:52:00.264998 INFO logger CgmAgent: Chat Message[ system ]: # Guidelines
Use the following format to accomplish user's request:
[Thought] think about what to do next to solve the question [/Thought]
[Action] use a tool, the action must be a json object wrapped by ```json and ```
    ```json
    {
        "name": string, name of the tool, it must refer to one of available tools
        "arguments": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters
    }
    ```
    For example,
    ```json
    {
        "name": "foo"
        "arguments": {
            "url": "http://example.com",
            "count": 3,
            "items": ["abc", "xyz"]
        }
    }
    ```
[/Action]
[Observation] the result of the action [/Observation]
... (Thought/Action/Observation may repeat N times to accomplish user's request)
[Answer] the final answer to the original input question [/Answer]

NEVER generate [Observation] yourself. This is an important requirement.

You must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]
Examples:
Output: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]
Output: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]

- If there are no available tools, generate final answer directly.

# Available Tools
[
 {
  "name": "getCurrentTime",
  "description": "获取当前时间",
  "inputSchema": {
    "type": "object",
    "properties": {},
    "required": []
  }
},
{
  "name": "sendNotification",
  "description": "向用户发送短信通知",
  "inputSchema": {
    "type": "object",
    "properties": {
      "msg": {
        "type": "string",
        "description": "发送短信的内容"
      }
    },
    "required": [
      "msg"
    ]
  }
} 
]
---end of tools---

        检测用户当前血糖是否正常。回答“正常”或是“异常”
        检查结果可以结合当前所处的时间综合判断
        如果异常,则向用户发送通知并告知可实施的建议
        仅使用已有工具
2025/06/13 21:52:00.265016 INFO logger CgmAgent: Chat Message[ user ]: 当前血糖 189 mg/dL
2025/06/13 21:52:00.265024 INFO logger CgmAgent: ----- End of Build Agent Task -----
2025/06/13 21:52:00.265048 INFO logger CgmAgent: Step #0
2025/06/13 21:52:00.265086 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:52:00.265099 DEBUG logger header: Content-Type - application/json
2025/06/13 21:52:00.265108 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:52:00.265150 DEBUG logger body: {"messages":[{"role":"system","content":"# Guidelines\nUse the following format to accomplish user's request:\n[Thought] think about what to do next to solve the question [/Thought]\n[Action] use a tool, the action must be a json object wrapped by ```json and ```\n    ```json\n    {\n        \"name\": string, name of the tool, it must refer to one of available tools\n        \"arguments\": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters\n    }\n    ```\n    For example,\n    ```json\n    {\n        \"name\": \"foo\"\n        \"arguments\": {\n            \"url\": \"http://example.com\",\n            \"count\": 3,\n            \"items\": [\"abc\", \"xyz\"]\n        }\n    }\n    ```\n[/Action]\n[Observation] the result of the action [/Observation]\n... (Thought/Action/Observation may repeat N times to accomplish user's request)\n[Answer] the final answer to the original input question [/Answer]\n\nNEVER generate [Observation] yourself. This is an important requirement.\n\nYou must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]\nExamples:\nOutput: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]\nOutput: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]\n\n- If there are no available tools, generate final answer directly.\n\n# Available Tools\n[\n {\n  \"name\": \"getCurrentTime\",\n  \"description\": \"获取当前时间\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {},\n    \"required\": []\n  }\n},\n{\n  \"name\": \"sendNotification\",\n  \"description\": \"向用户发送短信通知\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"msg\": {\n        \"type\": \"string\",\n        \"description\": \"发送短信的内容\"\n      }\n    },\n    \"required\": [\n      \"msg\"\n    ]\n  }\n} \n]\n---end of tools---\n\n        检测用户当前血糖是否正常。回答“正常”或是“异常”\n        检查结果可以结合当前所处的时间综合判断\n        如果异常,则向用户发送通知并告知可实施的建议\n        仅使用已有工具"},{"role":"user","content":"当前血糖 189 mg/dL"},{"role":"system","content":"Decide what to do next. Output a pair of [Thought] and [Action], a pair of [Thought] and [Answer], or a single [Answer]"}],"model":"DeepSeek-R1","stream":false,"stop":["[Observation]"],"temperature":0.1}
2025/06/13 21:52:07.390297 DEBUG logger Raw http response: {"id":"chat-b9d878cd1ed94c0581047ef01fb26d67","object":"chat.completion","created":1749822720,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n[Thought] 需要获取当前时间来判断血糖值是否异常 [/Thought]\n[Action]\n```json\n{\n    \"name\": \"getCurrentTime\",\n    \"arguments\": {}\n}\n```\n[/Action]\n","reasoning_content":"好的,用户当前的血糖值是189 mg/dL。首先,我需要确定这个数值是否正常。通常,正常空腹血糖范围是70-100 mg/dL,餐后两小时血糖应低于140 mg/dL。现在用户没有说明是空腹还是餐后,但189明显偏高。接下来,我需要检查当前时间,如果是餐后可能稍高,但189还是过高。使用getCurrentTime工具获取时间。假设现在是下午3点,可能属于随机血糖,超过200才考虑糖尿病,但189接近异常。可能需要发送通知建议用户监测或就医。根据指南,如果异常则发送通知。所以这里判断为异常,发送建议。\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":"[Observation]"}],"usage":{"prompt_tokens":550,"total_tokens":732,"completion_tokens":182},"prompt_logprobs":null}
200
2025/06/13 21:52:07.390406 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:52:07.390455 INFO logger CgmAgent: Chat Message[ assistant ]: [Thought] 需要获取当前时间来判断血糖值是否异常 [/Thought]
2025/06/13 21:52:07.390468 INFO logger CgmAgent: Chat Message[ assistant ]: [Action] ```json
{
    "name": "getCurrentTime",
    "arguments": {}
}
``` [/Action]
2025/06/13 21:52:07.390543 INFO logger CgmAgent: Chat Message[ assistant ]: [Observation] 2025-06-13T21:52:07.390506974+08:00 [/Observation]
2025/06/13 21:52:07.390556 INFO logger CgmAgent: Step #1
2025/06/13 21:52:07.390601 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:52:07.390615 DEBUG logger header: Content-Type - application/json
2025/06/13 21:52:07.390624 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:52:07.390688 DEBUG logger body: {"messages":[{"role":"system","content":"# Guidelines\nUse the following format to accomplish user's request:\n[Thought] think about what to do next to solve the question [/Thought]\n[Action] use a tool, the action must be a json object wrapped by ```json and ```\n    ```json\n    {\n        \"name\": string, name of the tool, it must refer to one of available tools\n        \"arguments\": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters\n    }\n    ```\n    For example,\n    ```json\n    {\n        \"name\": \"foo\"\n        \"arguments\": {\n            \"url\": \"http://example.com\",\n            \"count\": 3,\n            \"items\": [\"abc\", \"xyz\"]\n        }\n    }\n    ```\n[/Action]\n[Observation] the result of the action [/Observation]\n... (Thought/Action/Observation may repeat N times to accomplish user's request)\n[Answer] the final answer to the original input question [/Answer]\n\nNEVER generate [Observation] yourself. This is an important requirement.\n\nYou must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]\nExamples:\nOutput: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]\nOutput: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]\n\n- If there are no available tools, generate final answer directly.\n\n# Available Tools\n[\n {\n  \"name\": \"getCurrentTime\",\n  \"description\": \"获取当前时间\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {},\n    \"required\": []\n  }\n},\n{\n  \"name\": \"sendNotification\",\n  \"description\": \"向用户发送短信通知\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"msg\": {\n        \"type\": \"string\",\n        \"description\": \"发送短信的内容\"\n      }\n    },\n    \"required\": [\n      \"msg\"\n    ]\n  }\n} \n]\n---end of tools---\n\n        检测用户当前血糖是否正常。回答“正常”或是“异常”\n        检查结果可以结合当前所处的时间综合判断\n        如果异常,则向用户发送通知并告知可实施的建议\n        仅使用已有工具"},{"role":"user","content":"当前血糖 189 mg/dL"},{"role":"assistant","content":"[Thought] 需要获取当前时间来判断血糖值是否异常 [/Thought]"},{"role":"assistant","content":"[Action] ```json\n{\n    \"name\": \"getCurrentTime\",\n    \"arguments\": {}\n}\n``` [/Action]"},{"role":"assistant","content":"[Observation] 2025-06-13T21:52:07.390506974+08:00 [/Observation]"},{"role":"system","content":"Decide what to do next. Output a pair of [Thought] and [Action], a pair of [Thought] and [Answer], or a single [Answer]"}],"model":"DeepSeek-R1","stream":false,"stop":["[Observation]"],"temperature":0.1}
2025/06/13 21:52:22.317881 DEBUG logger Raw http response: {"id":"chat-a0456430fc204af5854603e28b82ce9c","object":"chat.completion","created":1749822727,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n[Thought] 当前时间为21:52,根据医学标准,正常餐后2小时血糖应低于140mg/dL。检测值189mg/dL明显高于正常范围 [/Thought]\n[Action] ```json\n{\n    \"name\": \"sendNotification\",\n    \"arguments\": {\n        \"msg\": \"您的当前血糖值为189mg/dL(检测时间21:52),血糖水平异常偏高。建议立即进行15分钟轻度运动,饮用清水,若30分钟后未下降请及时就医\"\n    }\n}\n``` [/Action]\n","reasoning_content":"好的,我现在需要处理用户的血糖检测请求。用户提供的血糖值是189 mg/dL,我需要判断这是否正常。首先,根据医学标准,正常空腹血糖通常在70-130 mg/dL之间,餐后两小时血糖应低于180 mg/dL。用户当前的时间是2025年6月13日晚上9点52分,接近晚上10点,这个时间点通常是晚餐后的几小时,可能属于餐后阶段。\n\n接下来,我需要确定用户是否在餐后两小时内。如果当前时间接近晚餐时间,比如晚餐是在晚上7点左右,那么两小时后也就是9点左右,这时候血糖值189 mg/dL可能略高于正常范围。但如果是餐后超过两小时,血糖值仍然在189,这可能表明血糖控制不佳,属于异常情况。\n\n由于用户没有明确说明测量时间是否在餐后,我需要根据常规情况推断。通常,晚上9点多可能已经过了晚餐后的两小时,因此189 mg/dL可能偏高。这时候应该发送通知提醒用户,并给出建议,比如建议用户适当运动、控制饮食,或者咨询医生。\n\n接下来,我需要使用sendNotification工具发送短信通知。短信内容需要包含当前血糖值、判断结果以及建议措施。例如:“您的当前血糖值为189 mg/dL,检测时间为21:52,血糖水平偏高。建议适当运动,控制饮食,并咨询医生。”\n\n最后,综合所有信息,判断用户血糖异常,并发送通知。因此,最终答案应为“异常”。\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":"[Observation]"}],"usage":{"prompt_tokens":625,"total_tokens":1039,"completion_tokens":414},"prompt_logprobs":null}
200
2025/06/13 21:52:22.318014 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:52:22.318073 INFO logger CgmAgent: Chat Message[ assistant ]: [Thought] 当前时间为21:52,根据医学标准,正常餐后2小时血糖应低于140mg/dL。检测值189mg/dL明显高于正常范围 [/Thought]
2025/06/13 21:52:22.318087 INFO logger CgmAgent: Chat Message[ assistant ]: [Action] ```json
{
    "name": "sendNotification",
    "arguments": {
        "msg": "您的当前血糖值为189mg/dL(检测时间21:52),血糖水平异常偏高。建议立即进行15分钟轻度运动,饮用清水,若30分钟后未下降请及时就医"
    }
}
``` [/Action]
2025/06/13 21:52:22.318183 INFO logger CgmAgent: Chat Message[ assistant ]: [Observation] Done [/Observation]
2025/06/13 21:52:22.318201 INFO logger CgmAgent: Step #2
2025/06/13 21:52:22.318251 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:52:22.318266 DEBUG logger header: Content-Type - application/json
2025/06/13 21:52:22.318271 DEBUG logger header: Authorization - Bearer
2025/06/13 21:52:22.318340 DEBUG logger body: {"messages":[{"role":"system","content":"# Guidelines\nUse the following format to accomplish user's request:\n[Thought] think about what to do next to solve the question [/Thought]\n[Action] use a tool, the action must be a json object wrapped by ```json and ```\n    ```json\n    {\n        \"name\": string, name of the tool, it must refer to one of available tools\n        \"arguments\": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters\n    }\n    ```\n    For example,\n    ```json\n    {\n        \"name\": \"foo\"\n        \"arguments\": {\n            \"url\": \"http://example.com\",\n            \"count\": 3,\n            \"items\": [\"abc\", \"xyz\"]\n        }\n    }\n    ```\n[/Action]\n[Observation] the result of the action [/Observation]\n... (Thought/Action/Observation may repeat N times to accomplish user's request)\n[Answer] the final answer to the original input question [/Answer]\n\nNEVER generate [Observation] yourself. This is an important requirement.\n\nYou must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]\nExamples:\nOutput: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]\nOutput: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]\n\n- If there are no available tools, generate final answer directly.\n\n# Available Tools\n[\n {\n  \"name\": \"getCurrentTime\",\n  \"description\": \"获取当前时间\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {},\n    \"required\": []\n  }\n},\n{\n  \"name\": \"sendNotification\",\n  \"description\": \"向用户发送短信通知\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"msg\": {\n        \"type\": \"string\",\n        \"description\": \"发送短信的内容\"\n      }\n    },\n    \"required\": [\n      \"msg\"\n    ]\n  }\n} \n]\n---end of tools---\n\n        检测用户当前血糖是否正常。回答“正常”或是“异常”\n        检查结果可以结合当前所处的时间综合判断\n        如果异常,则向用户发送通知并告知可实施的建议\n        仅使用已有工具"},{"role":"user","content":"当前血糖 189 mg/dL"},{"role":"assistant","content":"[Thought] 需要获取当前时间来判断血糖值是否异常 [/Thought]"},{"role":"assistant","content":"[Action] ```json\n{\n    \"name\": \"getCurrentTime\",\n    \"arguments\": {}\n}\n``` [/Action]"},{"role":"assistant","content":"[Observation] 2025-06-13T21:52:07.390506974+08:00 [/Observation]"},{"role":"assistant","content":"[Thought] 当前时间为21:52,根据医学标准,正常餐后2小时血糖应低于140mg/dL。检测值189mg/dL明显高于正常范围 [/Thought]"},{"role":"assistant","content":"[Action] ```json\n{\n    \"name\": \"sendNotification\",\n    \"arguments\": {\n        \"msg\": \"您的当前血糖值为189mg/dL(检测时间21:52),血糖水平异常偏高。建议立即进行15分钟轻度运动,饮用清水,若30分钟后未下降请及时就医\"\n    }\n}\n``` [/Action]"},{"role":"assistant","content":"[Observation] Done [/Observation]"},{"role":"system","content":"Decide what to do next. Output a pair of [Thought] and [Action], a pair of [Thought] and [Answer], or a single [Answer]"}],"model":"DeepSeek-R1","stream":false,"stop":["[Observation]"],"temperature":0.1}
2025/06/13 21:52:45.264136 DEBUG logger Raw http response: {"id":"chat-b2be51d4fb724bd6a9f7bab0f2afed49","object":"chat.completion","created":1749822743,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n[Answer] 异常 [/Answer]","reasoning_content":"好的,我现在需要处理用户的血糖检测请求。用户提供的血糖值是189 mg/dL,我需要判断是否正常。首先,根据医学知识,正常空腹血糖应该在70-100 mg/dL之间,而餐后两小时血糖应低于140 mg/dL。但用户没有说明是空腹还是餐后,这时候可能需要结合当前时间来判断。\n\n接下来,我需要使用可用的工具来获取当前时间。用户提到要结合当前时间综合判断,所以第一步是调用getCurrentTime工具。假设当前时间是晚上9点多,这可能意味着用户是在晚餐后测量的,这时候餐后两小时的血糖值如果超过140就属于异常。\n\n然后,根据返回的时间,比如21:52,这时候如果用户是在晚餐后两小时测量的,那么189 mg/dL明显高于正常范围,属于异常。这时候需要发送通知,告知用户血糖异常并提供建议。建议可能包括轻度运动、补充水分,如果情况没有改善应及时就医。\n\n需要注意的是,用户可能没有说明测量时间,所以必须依赖当前时间来推断。另外,发送通知的内容需要明确血糖值、检测时间以及具体的建议,确保用户清楚情况并知道如何应对。同时,要确保使用正确的工具参数,比如sendNotification中的msg内容要准确无误。\n\n最后,确保整个流程符合用户的要求,仅使用已有的工具,并且最终回答“异常”或“正常”。根据分析,用户的情况属于异常,因此最终答案是“异常”,并发送相应的通知。\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":747,"total_tokens":1051,"completion_tokens":304},"prompt_logprobs":null}
200
2025/06/13 21:52:45.264233 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:52:45.264274 INFO logger CgmAgent: Chat Message[ assistant ]: [Answer] 异常 [/Answer]
2025/06/13 21:52:45.264309 INFO logger MonitorAgent: Chat Message[ assistant ]: [Observation] 异常 [/Observation]
2025/06/13 21:52:45.264318 INFO logger MonitorAgent: Step #1
2025/06/13 21:52:45.264354 DEBUG logger http POST: https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/8a062fd4-7367-4ab4-a936-5eeb8fb821c4/v1//chat/completions
2025/06/13 21:52:45.264369 DEBUG logger header: Content-Type - application/json
2025/06/13 21:52:45.264374 DEBUG logger header: Authorization - Bearer 
2025/06/13 21:52:45.264422 DEBUG logger body: {"messages":[{"role":"system","content":"# Guidelines\nUse the following format to accomplish user's request:\n[Thought] think about what to do next to solve the question [/Thought]\n[Action] use a tool, the action must be a json object wrapped by ```json and ```\n    ```json\n    {\n        \"name\": string, name of the tool, it must refer to one of available tools\n        \"arguments\": { [key: string]: unknown }, arguments for the tool, each argument must be a valid json value required by the tool; it can be omitted, if the tool does not accept parameters\n    }\n    ```\n    For example,\n    ```json\n    {\n        \"name\": \"foo\"\n        \"arguments\": {\n            \"url\": \"http://example.com\",\n            \"count\": 3,\n            \"items\": [\"abc\", \"xyz\"]\n        }\n    }\n    ```\n[/Action]\n[Observation] the result of the action [/Observation]\n... (Thought/Action/Observation may repeat N times to accomplish user's request)\n[Answer] the final answer to the original input question [/Answer]\n\nNEVER generate [Observation] yourself. This is an important requirement.\n\nYou must generate either a pair of [Thought] and [Action] or a pair of [Thought] and [Answer]\nExamples:\nOutput: [Thought] I need to search the web to get related knowledge [/Thought] [Action] ... [/Action]\nOutput: [Thought] I know the final answer now [/Thought] [Answer] ... [/Answer]\n\n- If there are no available tools, generate final answer directly.\n\n# Available Tools\n[\n {\n  \"name\": \"CgmAgent\",\n  \"description\": \"\\n\\nThe agent checks if a user's current blood sugar level is normal (\\\"正常\\\") or abnormal (\\\"异常\\\"), incorporating time-based context for accuracy. If abnormal, it sends a notification with actionable recommendations. It operates strictly using predefined tools without external resources.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"question\": {\n        \"type\": \"string\",\n        \"description\": \"The input question\"\n      }\n    },\n    \"required\": [\n      \"question\"\n    ]\n  }\n},\n{\n  \"name\": \"HeartBeatAgent\",\n  \"description\": \"\\n\\nThe agent monitors a user's heartbeat to determine if it is normal (\\\"正常\\\") or abnormal (\\\"异常\\\"). If abnormal, it sends a notification to the user with actionable recommendations. It strictly uses predefined tools for assessment and response, without external inputs or outputs beyond the binary classification and follow-up guidance.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"question\": {\n        \"type\": \"string\",\n        \"description\": \"The input question\"\n      }\n    },\n    \"required\": [\n      \"question\"\n    ]\n  }\n} \n]\n---end of tools---\n\n        根据接受到的监测数据,交由不同的检测模块进行检测"},{"role":"user","content":"当前血糖 189 mg/dL"},{"role":"assistant","content":"[Thought] 需要调用CgmAgent来评估当前血糖值是否正常 [/Thought]"},{"role":"assistant","content":"[Action] ```json\n{\n    \"name\": \"CgmAgent\",\n    \"arguments\": {\n        \"question\": \"当前血糖 189 mg/dL\"\n    }\n}\n``` [/Action]"},{"role":"assistant","content":"[Observation] 异常 [/Observation]"},{"role":"system","content":"Decide what to do next. Output a pair of [Thought] and [Action], a pair of [Thought] and [Answer], or a single [Answer]"}],"model":"DeepSeek-R1","stream":false,"stop":["[Observation]"],"temperature":0.1}
2025/06/13 21:53:04.010654 DEBUG logger Raw http response: {"id":"chat-c8187170c9ab4ae687c03f6faab8521b","object":"chat.completion","created":1749822765,"model":"DeepSeek-R1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n[Answer] 您的血糖值为189 mg/dL,属于异常范围(正常空腹血糖应低于100 mg/dL,餐后2小时应低于140 mg/dL)。建议:1. 立即停止摄入含糖食物 2. 进行15分钟轻度运动(如散步) 3. 1小时后复测血糖 4. 若持续高于180 mg/dL请及时就医。请注意观察是否有口渴、多尿或乏力等糖尿病症状。[/Answer]","reasoning_content":"好的,用户提供的血糖值是189 mg/dL,我需要使用CgmAgent来评估这个数值是否正常。根据医学标准,正常空腹血糖通常在70-99 mg/dL之间,餐后两小时血糖应低于140 mg/dL。189明显高于正常范围,尤其是在空腹情况下可能属于高血糖。如果这是餐后数值,可能仍然偏高。因此,CgmAgent返回“异常”是合理的。接下来需要根据结果提供建议,比如建议用户控制饮食,避免高糖食物,适量运动,必要时咨询医生调整药物剂量。同时提醒监测血糖变化,如有持续升高或出现症状应及时就医。确保回答清晰且具有可操作性,帮助用户理解当前状况并采取正确措施。\n","tool_calls":[]},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":729,"total_tokens":975,"completion_tokens":246},"prompt_logprobs":null}
200
2025/06/13 21:53:04.010758 DEBUG logger #Response-Message: 1; #Assistant-Message: 1
2025/06/13 21:53:04.010790 INFO logger MonitorAgent: Chat Message[ assistant ]: [Answer] 您的血糖值为189 mg/dL,属于异常范围(正常空腹血糖应低于100 mg/dL,餐后2小时应低于140 mg/dL)。建议:1. 立即停止摄入含糖食物 2. 进行15分钟轻度运动(如散步) 3. 1小时后复测血糖 4. 若持续高于180 mg/dL请及时就医。请注意观察是否有口渴、多尿或乏力等糖尿病症状。 [/Answer]

 这个流程在----- Build Agent Task -----前先进行了两次DeepSeek对话,主要是分析血压和心跳两个代理的作用,然后才开始智能体的流程。官方这个示例在开发者云主机上运行大概需要90s。

优化方法

 Cangjie Magic团队的midwinter1993提示我要省掉前面的两次DeepSeek对话,可以在代理那里加上描述,这样 Cangjie Magic就不会再询问代理的功能,而是直接将描述作为代理的功能开始后面的流程。

@agent[model: "deepseek:DeepSeek-R1", description: "检测用户当前血糖是否正常,返回“正常”或是“异常”。",
       tools: [getCurrentTime, sendNotification]]
class CgmAgent {
    @prompt(
        """
        检测用户当前血糖是否正常。回答“正常”或是“异常”
        检查结果可以结合当前所处的时间综合判断
        如果异常,则向用户发送通知并告知可实施的建议
        仅使用已有工具
        """
    )
}

//================================================
@agent[model: "deepseek:DeepSeek-R1",
       tools: [sendNotification], description: "检测用户当前心跳是否正常,返回“正常”或是“异常”。"]
class HeartBeatAgent {
    @prompt(
        """
        检测用户当前心跳是否正常。回答“正常”或是“异常”
        如果异常,则向用户发送通知并告知可实施的建议
        仅使用已有工具
        """
    )
}

经过这样的处理,果然程序速度加快。优化后的程序在同样的机器上运行为46s。

结束语

Cangjie Magic框架仍有诸多值得挖掘,期待持续关注该领域的动态发展。若有任何疑问或反馈,欢迎深入交流探讨。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神一样的老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值