报错❌ 调用LLM API时发生错误: list index out of range 解决方法 使用流式输出时,chunk中的choices属性在开始是空的,所以需要if判断,当chunk有choices属性并且choices属性不为空才打印chunk.choices[0].delta.content中的内容
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
)
# 处理流式响应
print("✅ 大语言模型响应成功:")
collected_content = []
for chunk in response:
# 检查chunk是否包含choices属性且非空
# 注意:流式响应的第一次chunk可能包含空的choices,这是正常情况
if hasattr(chunk, 'choices') and chunk.choices:
content = chunk.choices[0].delta.content or ""
print(content, end="", flush=True)
collected_content.append(content)