如何修复Llama API调用时出现的TypeError错误
问题修复方案
错误原因分析
报错TypeError: list indices must be integers or slices, not str是因为Llama API返回的错误响应是列表格式,但SDK的run_sync方法错误地将其当作字典去取['detail']字段,导致索引类型错误。
修复步骤
1. 先查看真实的API错误信息
先修改代码,捕获异常并打印完整响应内容,明确API返回的具体错误:
import json from llamaapi import LlamaAPI llama = LlamaAPI("你的实际API Token") api_request_json = { "model": "llama3.1-70b", "messages": [ {"role": "user", "content": "What is the weather like in Boston?"}, ], "functions": [ { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "days": { "type": "number", "description": "for how many days ahead you wants the forecast", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, }, "required": ["location", "days"], } ], "stream": False, "function_call": "get_current_weather", } try: response = llama.run(api_request_json) print(json.dumps(response.json(), indent=2)) except Exception as e: import traceback traceback.print_exc() # 打印完整响应文本,查看真实错误 print("\nAPI响应内容:", response.text)
2. 针对常见问题的修复
根据API返回的错误,通常有以下几个可能的问题:
(1)API Token未正确替换
确保代码中的<your_api_token>已经替换为你从Llama平台获取的有效API Token。
(2)function_call格式错误
多数LLM API要求function_call是字典格式而非字符串,修改为:
"function_call": {"name": "get_current_weather"}
(3)函数参数不完整
你的functions定义中required字段包含location和days,但用户提问未指定days参数。可以:
- 在用户消息中补充天数信息,比如:
"content": "What is the weather like in Boston for 3 days?" - 或者将
days从required列表中移除,根据需求调整参数要求。
(4)模型名称错误或无权限访问
确认llama3.1-70b是你有权限使用的模型,部分模型可能需要额外申请权限,或名称存在拼写错误(比如应为llama3.1-70b-chat)。
3. 修复SDK的错误处理(可选)
如果SDK本身的错误处理逻辑有问题,可以修改llamaapi.py中的run_sync方法,让它能正确处理列表格式的错误响应:
找到llamaapi.py文件中的以下代码:
raise Exception(f"POST {response.status_code} {response.json()['detail']}")
替换为:
error_data = response.json() if isinstance(error_data, list): error_msg = "; ".join(str(item) for item in error_data) else: error_msg = error_data.get('detail', str(error_data)) raise Exception(f"POST {response.status_code} {error_msg}")
内容的提问来源于stack exchange,提问作者user1700890
相关产品推荐
相关产品推荐

