在构建AI回答采集系统时,核心任务之一是稳定调用大模型接口,获取模型对特定问题的回答。只调用一次接口并不复杂,但采集系统需要处理批量问题、不同模型、认证、超时、重试、流式输出和结构化解析。本文以腾讯混元大模型为例,介绍如何将模型调用工程化地集成到采集任务中。
采集系统与模型调用的关系如下:
密钥管理:SecretId和SecretKey通过环境变量读取,不硬编码在代码中。
import os
from tencentcloud.common import credential
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
secret_id = os.environ.get("TENCENT_SECRET_ID")
secret_key = os.environ.get("TENCENT_SECRET_KEY")
cred = credential.Credential(secret_id, secret_key)def call_hunyuan_sync(question: str, model: str = "hunyuan-pro") -> str:
client = hunyuan_client.HunyuanClient(cred, "ap-guangzhou")
req = models.ChatCompletionsRequest()
req.Model = model
req.Messages = [
{"Role": "user", "Content": question}
]
try:
resp = client.ChatCompletions(req)
return resp.Choices[0].Message.Content
except Exception as e:
logging.error(f"调用失败: {e}")
raise这段代码做了最基础的调用:创建客户端、构造请求、发送并返回回答内容。注意地域参数ap-guangzhou,实际使用时需根据账号开通的地域调整。
采集系统可能需要实时获取回答片段,或减少等待时间。混元SDK支持流式输出:
def call_hunyuan_stream(question: str, model: str = "hunyuan-pro") -> str:
client = hunyuan_client.HunyuanClient(cred, "ap-guangzhou")
req = models.ChatCompletionsRequest()
req.Model = model
req.Messages = [{"Role": "user", "Content": question}]
req.Stream = True
full_content = ""
try:
resp = client.ChatCompletions(req)
for event in resp:
if event.Choices:
delta = event.Choices[0].Delta
if delta and delta.Content:
full_content += delta.Content
return full_content
except Exception as e:
logging.error(f"流式调用失败: {e}")
raise流式模式下,SDK返回一个迭代器,每个event包含增量内容。需要自行拼接完整回答。注意:流式模式下,最终回答可能包含多个event,最后一个event的Choices[0].FinishReason为"stop"。
采集系统有时需要模型返回结构化数据,例如提取品牌名称、推荐理由等。混元支持通过response_format指定JSON输出:
def call_hunyuan_json(question: str, schema: dict, model: str = "hunyuan-pro") -> dict:
client = hunyuan_client.HunyuanClient(cred, "ap-guangzhou")
req = models.ChatCompletionsRequest()
req.Model = model
req.Messages = [{"Role": "user", "Content": f"{question}\n请以JSON格式输出,格式如下:{json.dumps(schema)}"}]
req.ResponseFormat = {"Type": "json_object"}
try:
resp = client.ChatCompletions(req)
content = resp.Choices[0].Message.Content
return json.loads(content)
except json.JSONDecodeError:
logging.error("模型返回非JSON格式")
raise
except Exception as e:
logging.error(f"调用失败: {e}")
raise注意:ResponseFormat设置为json_object后,模型会尽力输出JSON,但仍有失败可能。生产环境需要增加重试和校验逻辑。
采集系统面对批量调用,必须处理各类错误:
重试策略示例:
import time
from tencentcloud.common.exception import TencentCloudSDKException
def call_with_retry(question: str, max_retries: int = 3):
for attempt in range(max_retries):
try:
return call_hunyuan_sync(question)
except TencentCloudSDKException as e:
if "RequestLimitExceeded" in str(e):
wait = 2 ** attempt
logging.warning(f"限流,等待{wait}s后重试")
time.sleep(wait)
continue
elif "InternalError" in str(e):
time.sleep(1)
continue
else:
raise
raise Exception("重试耗尽,调用失败")每次调用应记录:
logging.info(f"RequestId: {resp.RequestId}, Model: {model}, Cost: {cost_ms}ms")验证结果:正常情况下,返回的回答应包含完整内容,无截断。可以通过检查FinishReason是否为"stop"确认。
本文以腾讯混元为例,介绍了AI回答采集系统中模型调用的工程实践,包括认证、SDK使用、流式输出、结构化响应和错误处理。关键点:使用SDK简化认证和请求构建;流式输出适合实时场景;JSON模式便于解析;完善的错误处理和日志是稳定性的基础。这些方法同样适用于其他兼容OpenAI接口的模型服务,只需替换客户端和认证方式。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。