在构建AI回答采集系统时,模型调用是整个链路中最关键也最容易出问题的一环。本文以腾讯混元为例,从认证、SDK使用、流式输出、结构化响应到错误处理,逐步讲解如何稳定地调用大模型接口。文章提供可运行的代码片段,并说明如何验证调用结果、处理异常以及控制成本。适合需要接入大模型API的开发者,尤其是正在构建AI搜索监测、品牌可见度分析等系统的技术团队。
假设我们要构建一个AI回答采集系统,需要向多个大模型提问,并保存原始回答用于后续分析。在一次实际开发中,我们发现调用腾讯混元接口时,经常出现超时、返回格式不稳定、认证失败等问题。这些问题导致采集任务中断,数据缺失。
本文要解决的核心问题是:如何稳定地调用腾讯混元模型,获取结构化响应,并处理各种异常情况。
tencentcloud-sdk-python。pip install tencentcloud-sdk-python腾讯混元API使用腾讯云标准的签名认证。我们使用官方SDK初始化客户端。
from tencentcloud.common import credential
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
cred = credential.Credential("YOUR_SECRET_ID", "YOUR_SECRET_KEY")
client = hunyuan_client.HunyuanClient(cred, "ap-guangzhou")说明:
YOUR_SECRET_ID和YOUR_SECRET_KEY需要替换为实际值,且不能硬编码在代码中,应使用环境变量或密钥管理服务。ap-guangzhou为示例,实际地域需与开通服务的地域一致。我们使用ChatCompletion接口进行对话。以下是一个简单的请求示例:
req = models.ChatCompletionRequest()
req.Model = "hunyuan-lite"
req.Messages = [
{"Role": "user", "Content": "请用一句话介绍腾讯混元。"}
]
resp = client.ChatCompletion(req)
print(resp.Choices[0].Message.Content)说明:
Model指定模型版本,这里使用hunyuan-lite,实际可用的模型列表请参考官方文档。Messages是对话历史,这里只包含一条用户消息。Choices[0].Message.Content是模型生成的文本。对于长回答,流式输出可以降低首字延迟,提升用户体验。SDK支持流式调用:
req.Stream = True
resp = client.ChatCompletion(req)
for event in resp:
if hasattr(event, 'Choices') and event.Choices:
delta = event.Choices[0].Delta
if delta and delta.Content:
print(delta.Content, end='')说明:
Stream=True后,响应变为迭代器,每次返回一个事件。Choices[0].Delta.Content是增量内容。为了便于程序解析,我们要求模型返回JSON格式。可以通过提示词实现:
prompt = "请以JSON格式返回:{\"brand\": \"品牌名\", \"mention\": true, \"recommend\": false}"
req.Messages = [{"Role": "user", "Content": prompt}]
resp = client.ChatCompletion(req)
content = resp.Choices[0].Message.Content
import json
try:
data = json.loads(content)
print(data["brand"])
except json.JSONDecodeError:
print("模型返回非JSON格式,需重试或后处理")说明:
网络抖动、限流、模型过载都可能导致调用失败。我们需要实现重试机制。
import time
from tencentcloud.common.exception import TencentCloudSDKException
def call_with_retry(req, max_retries=3):
for i in range(max_retries):
try:
resp = client.ChatCompletion(req)
return resp
except TencentCloudSDKException as e:
if e.code in ["ResourceNotFound", "AuthFailure"]:
raise
if i < max_retries - 1:
time.sleep(2 ** i)
else:
raise说明:
采集系统通常需要并发调用多个模型,但要注意并发限制。
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_answer(question):
req = models.ChatCompletionRequest()
req.Model = "hunyuan-lite"
req.Messages = [{"Role": "user", "Content": question}]
resp = call_with_retry(req)
return resp.Choices[0].Message.Content
questions = ["问题1", "问题2", "问题3"]
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(fetch_answer, q) for q in questions]
for future in as_completed(futures):
try:
result = future.result()
print(result)
except Exception as e:
print(f"调用失败: {e}")说明:
每次调用都应记录日志,包括请求参数、响应状态、耗时等,便于排查问题。
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
start = time.time()
resp = call_with_retry(req)
cost = time.time() - start
logger.info(f"请求成功,耗时{cost}s,响应内容长度{len(resp.Choices[0].Message.Content)}")说明:
模型调用按Token计费,需要统计成本。
usage = resp.Usage
prompt_tokens = usage.PromptTokens
completion_tokens = usage.CompletionTokens
cost = (prompt_tokens * price_per_1k_prompt + completion_tokens * price_per_1k_completion) / 1000说明:
AuthFailure。本文以腾讯混元为例,介绍了AI回答采集中的模型调用工程实践,包括认证、SDK使用、流式输出、结构化响应、错误处理、并发控制和成本统计。这些方法同样适用于其他大模型API。关键点在于:
在实际系统中,还需要考虑数据存储、任务调度和异常恢复,这些将在后续文章中展开。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。