当前大模型虽能生成流畅文本,但无法主动调用外部系统、无法根据环境反馈调整策略,仅停留在“聊天”层面。AI Agent(代理) 通过引入推理(Reasoning) 与行动(Acting) 的闭环(即ReAct范式),使模型能够自主规划、调用工具、分析结果并迭代执行,最终完成复杂任务(如自动化运维、智能客服、数据分析)。
本文以云资源运维Agent为实战场景,基于腾讯云混元大模型(Hunyuan-Pro) 的Function Calling能力,结合云函数SCF与API网关,从零构建一个能听懂“检查CVM CPU负载,超阈值自动扩容”这类自然语言指令,并全自动执行整个链路的可运行系统。全程附有完整Node.js代码,可直接部署至腾讯云。
组件 | 选型 | 作用 |
|---|---|---|
推理引擎 | 腾讯混元大模型(hunyuan-pro) | 提供ReAct推理与结构化工具调用(Function Calling) |
工具层 | 腾讯云SDK(CVM + 监控) | 封装实例查询、CPU数据获取、扩缩容等云API |
记忆与状态 | 内存缓存(生产可换Redis) | 维持对话历史与中间结果 |
部署环境 | 腾讯云SCF(Node.js 18)+ API网关 | Serverless免运维,自动弹性,按量计费 |
Agent执行循环(ReAct核心):
while (目标未达成 && 步数<上限) {
1. 将用户目标 + 历史上下文 + 工具描述 构造成提示;
2. 调用混元API,获取推理文本和工具调用(含参数);
3. 若模型返回最终答案,则退出并返回;
4. 否则执行对应工具,获得结果,追加到历史,继续循环。
}在腾讯云控制台获取:
SecretId 与 SecretKey(用于调用混元API和云资源SDK)hunyuan-pro)本地项目初始化:
mkdir tencent-agent && cd tencent-agent
npm init -y
npm install axios tencentcloud-sdk-nodejs dotenv创建 .env 文件:
TENCENT_SECRET_ID=你的SecretId
TENCENT_SECRET_KEY=你的SecretKey
HUNYUAN_MODEL=hunyuan-pro
REGION=ap-guangzhou我们定义三个关键工具:查询实例列表、获取CPU平均利用率、模拟扩容。每个工具包含名称、描述、参数Schema、处理函数。
// tools/index.js
const tencentcloud = require('tencentcloud-sdk-nodejs');
const CvmClient = tencentcloud.cvm.v20170312.Client;
const MonitorClient = tencentcloud.monitor.v20180724.Client;
const clientConfig = {
credential: {
secretId: process.env.TENCENT_SECRET_ID,
secretKey: process.env.TENCENT_SECRET_KEY,
},
region: process.env.REGION,
profile: { httpProfile: { endpoint: 'cvm.tencentcloudapi.com' } },
};
const cvmClient = new CvmClient(clientConfig);
const monitorClient = new MonitorClient({
...clientConfig,
profile: { httpProfile: { endpoint: 'monitor.tencentcloudapi.com' } },
});
// 工具1:查询实例列表
async function describeInstances(params) {
const { InstanceIds } = params;
const resp = await cvmClient.DescribeInstances({ InstanceIds });
return resp.InstanceSet.map(i => ({
InstanceId: i.InstanceId,
InstanceName: i.InstanceName,
InstanceState: i.InstanceState,
CPU: i.CPU,
Memory: i.Memory
}));
}
// 工具2:获取CPU平均利用率
async function getCpuUsage(params) {
const { InstanceId, Period = 60, StartTime, EndTime } = params;
const resp = await monitorClient.GetMonitorData({
Namespace: 'QCE/CVM',
MetricName: 'CPUUsage',
Instances: [{ Dimensions: [{ Name: 'InstanceId', Value: InstanceId }] }],
Period,
StartTime,
EndTime,
});
const values = resp.DataPoints[0]?.Values || [];
const avg = values.reduce((a,b)=>a+b,0) / (values.length || 1);
return { InstanceId, avgCpu: avg };
}
// 工具3:模拟扩容(实际可调用ResizeInstanceDisks或RunInstances)
async function scaleUp(params) {
const { InstanceId, TargetCPU } = params;
// 这里简化演示,实际可触发CVM变配或新增实例
return {
action: 'scale_up',
instanceId: InstanceId,
targetCPU: TargetCPU,
message: `建议将实例${InstanceId}升级至目标CPU ${TargetCPU}核`
};
}
// 工具注册表(用于混元Function Calling)
const toolRegistry = {
describeInstances: {
description: '查询指定实例ID列表的详细信息',
parameters: {
type: 'object',
properties: {
InstanceIds: { type: 'array', items: { type: 'string' }, description: '实例ID数组' }
},
required: ['InstanceIds']
},
handler: describeInstances
},
getCpuUsage: {
description: '获取某个CVM实例在指定时间段的平均CPU使用率(百分比)',
parameters: {
type: 'object',
properties: {
InstanceId: { type: 'string' },
Period: { type: 'integer', default: 60 },
StartTime: { type: 'string' },
EndTime: { type: 'string' }
},
required: ['InstanceId']
},
handler: getCpuUsage
},
scaleUp: {
description: '对指定实例进行扩容操作,需给出目标CPU核数',
parameters: {
type: 'object',
properties: {
InstanceId: { type: 'string' },
TargetCPU: { type: 'integer' }
},
required: ['InstanceId', 'TargetCPU']
},
handler: scaleUp
}
};
module.exports = { toolRegistry };关键点:每次推理时,将工具列表的JSON Schema传给混元,并设置 ToolChoice: 'auto',让模型自主决定是否调用工具以及调用哪个工具。
// agent.js
const { toolRegistry } = require('./tools');
require('dotenv').config();
class CloudAgent {
constructor() {
this.history = [];
this.tools = toolRegistry;
this.model = process.env.HUNYUAN_MODEL;
// 初始化混元客户端(使用官方SDK)
const tencentcloud = require('tencentcloud-sdk-nodejs');
const HunyuanClient = tencentcloud.hunyuan.v20230901.Client;
this.client = new HunyuanClient({
credential: {
secretId: process.env.TENCENT_SECRET_ID,
secretKey: process.env.TENCENT_SECRET_KEY,
},
region: 'ap-guangzhou',
profile: { httpProfile: { endpoint: 'hunyuan.tencentcloudapi.com' } },
});
}
// 构造工具定义(符合混元Tools参数格式)
getToolDefinitions() {
return Object.entries(this.tools).map(([name, def]) => ({
Type: 'function',
Function: {
Name: name,
Description: def.description,
Parameters: JSON.stringify(def.parameters),
}
}));
}
// 执行工具调用
async executeToolCall(toolName, args) {
const tool = this.tools[toolName];
if (!tool) throw new Error(`Unknown tool: ${toolName}`);
return await tool.handler(args);
}
// 主循环
async run(userGoal, maxSteps = 5) {
this.history = [{ role: 'user', content: userGoal }];
let steps = 0;
let finalAnswer = '';
while (steps < maxSteps) {
steps++;
// 调用混元
const response = await this.client.ChatCompletions({
Model: this.model,
Messages: this.history,
Tools: this.getToolDefinitions(),
ToolChoice: 'auto',
});
const choice = response.Choices[0];
const message = choice.Message;
this.history.push({ role: 'assistant', content: message.Content || '' });
// 检查是否有工具调用
if (message.ToolCalls && message.ToolCalls.length > 0) {
for (const toolCall of message.ToolCalls) {
const { Name: toolName, Arguments: argsStr } = toolCall.Function;
const args = JSON.parse(argsStr);
console.log(`[Agent] 调用工具: ${toolName},参数:`, args);
const result = await this.executeToolCall(toolName, args);
// 工具结果以tool角色回填
this.history.push({
role: 'tool',
content: JSON.stringify(result),
tool_call_id: toolCall.Id,
});
}
continue;
}
// 无工具调用,视为最终答案
if (message.Content) {
finalAnswer = message.Content;
break;
}
break;
}
return finalAnswer || '任务执行完毕,但未返回明确结论。';
}
}
module.exports = CloudAgent;创建 index.js 快速验证:
const CloudAgent = require('./agent');
(async () => {
const agent = new CloudAgent();
const goal = `
查询实例 ins-abc123 和 ins-def456 的CPU使用率(过去10分钟),
如果任一实例的平均CPU超过80%,则对该实例执行扩容至4核。
`;
const result = await agent.run(goal);
console.log('最终结果:', result);
})();运行前确保 .env 正确。若实例ID不存在,工具会抛出错误,但Agent可根据错误信息重新规划(此为ReAct进阶能力,本文已实现基础循环)。
将Agent封装为Express应用,并通过 serverless-http 适配SCF。
// app.js
const express = require('express');
const serverless = require('serverless-http');
const CloudAgent = require('./agent');
const app = express();
app.use(express.json());
app.post('/agent', async (req, res) => {
const { goal } = req.body;
if (!goal) return res.status(400).json({ error: 'goal required' });
try {
const agent = new CloudAgent();
const answer = await agent.run(goal);
res.json({ success: true, answer });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
exports.main = serverless(app);创建 serverless.yml 配置文件:
app: ai-agent-demo
component: scf
name: cloud-agent
inputs:
name: cloud-agent
src: ./
runtime: Nodejs18.15
region: ap-guangzhou
handler: app.main
timeout: 300
events:
- http:
path: /agent
method: POST
apiGateway:
serviceName: agent-gw
environment:
variables:
TENCENT_SECRET_ID: ${env:TENCENT_SECRET_ID}
TENCENT_SECRET_KEY: ${env:TENCENT_SECRET_KEY}
HUNYUAN_MODEL: hunyuan-pro部署命令:
npm install -g serverless
serverless deploy --debug部署成功后,获得API网关URL,如 https://service-xxx.gz.apigw.tencentcs.com/agent。通过POST请求即可远程触发Agent:
curl -X POST https://service-xxx.gz.apigw.tencentcs.com/agent \
-H "Content-Type: application/json" \
-d '{"goal":"检查当前地域所有运行中实例的CPU,如果平均超过70%则记录实例ID"}'timeout至300秒,并考虑采用异步调用模式以应对长任务。本文完整展示了基于ReAct架构,利用腾讯云混元大模型Function Calling和Serverless基础设施,构建一个能自主调用云API完成复杂运维任务的AI Agent。整个过程从工具封装、推理循环到云端部署,全部代码可复制运行。该Agent不仅会“思考”,更能“行动”——它不再是简单的问答机器人,而是能够独立完成监控、分析、变更等自动化工作的数字员工。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。