AI回答采集系统需要稳定调用大模型API,获取结构化响应。本文以腾讯混元大模型为例,从认证、SDK集成、流式输出、结构化响应解析到错误处理,完整说明一个可复现的调用链路。适合需要批量调用模型API的开发者,前提是已开通腾讯混元服务并获取SecretId和SecretKey。
只调用一次模型接口并不复杂,但当采集任务需要连续调用数十个问题、处理流式输出、解析结构化字段、应对限流和超时时,工程细节就会暴露。本文只解决一个问题:如何让采集程序稳定调用腾讯混元,并正确获取模型回答。
npm install tencentcloud-sdk-nodejs-hunyuanexport TENCENT_SECRET_ID=your_secret_id
export TENCENT_SECRET_KEY=your_secret_key注意:密钥不要硬编码在代码中,生产环境应使用密钥管理服务或环境变量。
const { HunyuanClient } = require('tencentcloud-sdk-nodejs-hunyuan');
const 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',
},
},
});这段代码创建了一个混元客户端实例。region指定了服务地域,不同地域可能影响延迟和可用性。endpoint使用默认值即可。
采集系统需要逐字获取模型回答,以便实时处理或保存完整内容。使用流式接口:
const { ChatCompletionsRequest } = require('tencentcloud-sdk-nodejs-hunyuan').models;
async function streamChat(prompt) {
const params = {
Model: 'hunyuan-pro',
Messages: [{ Role: 'user', Content: prompt }],
Stream: true,
};
try {
const response = await client.ChatCompletions(params);
let fullContent = '';
for await (const chunk of response) {
if (chunk.Choices && chunk.Choices[0].Delta && chunk.Choices[0].Delta.Content) {
fullContent += chunk.Choices[0].Delta.Content;
process.stdout.write(chunk.Choices[0].Delta.Content); // 实时输出
}
}
return fullContent;
} catch (err) {
console.error('流式调用失败:', err);
throw err;
}
}Stream: true启用流式输出。response是一个异步迭代器,每个chunk包含增量内容。需要将增量拼接成完整回答。注意:流式响应中Choices[0].Delta.Content可能为空(如最后一个chunk),需要做空值判断。
采集系统通常需要模型以JSON格式返回结构化数据,例如品牌提及列表。使用函数调用或system prompt约束输出格式。
async function structuredChat(prompt, schema) {
const params = {
Model: 'hunyuan-pro',
Messages: [
{
Role: 'system',
Content: `请严格按照以下JSON Schema输出结果:${JSON.stringify(schema)}。只输出JSON,不要包含其他文字。`,
},
{ Role: 'user', Content: prompt },
],
Stream: false,
};
const response = await client.ChatCompletions(params);
const content = response.Choices[0].Message.Content;
try {
return JSON.parse(content);
} catch (e) {
console.error('JSON解析失败,原始内容:', content);
throw new Error('模型输出不是合法JSON');
}
}这里关闭流式输出(Stream: false),直接获取完整响应。通过system prompt约束输出格式,但模型仍可能输出非JSON内容,因此需要try-catch解析。如果解析失败,可以重试或记录原始内容供人工处理。
采集任务中,网络抖动、限流、超时是常见问题。需要实现指数退避重试:
async function callWithRetry(prompt, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await streamChat(prompt);
} catch (err) {
if (attempt === maxRetries) throw err;
const delay = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s
console.warn(`第${attempt}次调用失败,${delay}ms后重试:`, err.message);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}重试策略:最多重试3次,每次等待时间指数增长。注意:对于流式调用,重试需要重新发起请求,无法从断点续传。
正常情况下,调用streamChat(‘介绍一下腾讯云’)应当逐字输出回答,最终返回完整字符串。调用structuredChat应返回JSON对象。
验证步骤:
本文以腾讯混元为例,实现了AI回答采集中的模型调用链路,包括认证、SDK初始化、流式输出、结构化响应解析和错误重试。这套方案适用于需要批量、稳定调用模型API的采集系统。关键点在于:密钥安全、流式拼接、JSON解析容错和重试策略。实际使用时,还需根据业务需求调整超时、并发和成本控制参数。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。