You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Serge API提取响应文本时触发TypeError错误求助

问题:从Serge API提取响应文本时出现TypeError错误

问题详情

我编写了一段Python脚本用于从Serge获取API响应,脚本内容如下:

import requests
import json

# Define the base URL and chat ID
base_url = "http://192.168.0.2:8008"
chat_id = "85548e08-d142-4960-b214-9f95479509ad"

# Define the endpoint and parameters
endpoint = f"/api/chat/{chat_id}/question"
params = {
    "prompt": "What is the answer to life, the universe, and everything?"
}

# Send a POST request to the API
url = base_url + endpoint
response = requests.post(url, params=params, headers={"accept": "application/json"})

# Check the response status code
if response.status_code == 200:
    # Parse the JSON response
    response_data = response.json()
    text = response_data['choices'][0]['text']
    print("Response text: ", text)
else:
    print("Error:", response.status_code)

API的示例响应为:

"{'id': 'cmpl-8bee81c9-1548-4b57-b54d-00f9ab16b486', 'object': 'text_completion', 'created': 1699361498, 'model': '/usr/src/app/weights/WizardLM-Uncensored-7B.bin', 'choices': [{'text': 'The answer to that question would depend on who you ask as it varies from person to person. However, in the context of ARK: Survival Evolved, the answer would be 42.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 252, 'completion_tokens': 44, 'total_tokens': 296}}"

执行脚本时,在text = response_data['choices'][0]['text']行出现错误:

text = response_data['choices'][0]['text']
TypeError: string indices must be integers

我是Python新手,不清楚问题原因,请求帮助。

解决方案

问题根源

从示例响应能看出,API返回的是被双引号包裹的字符串格式数据,而且内部用单引号分隔键值,不符合标准JSON格式。调用response.json()后,得到的并不是字典,而是一个字符串,所以用字符串去访问['choices']这类键就会触发“字符串索引必须是整数”的错误。

修复方案

方案1:转换为标准JSON格式解析

  1. 先获取响应的原始文本,去掉首尾包裹的双引号
  2. 将文本中的单引号替换为双引号,转换成标准JSON格式
  3. 用json.loads()解析为字典

修改后的代码:

import requests
import json

# Define the base URL and chat ID
base_url = "http://192.168.0.2:8008"
chat_id = "85548e08-d142-4960-b214-9f95479509ad"

# Define the endpoint and parameters
endpoint = f"/api/chat/{chat_id}/question"
params = {
    "prompt": "What is the answer to life, the universe, and everything?"
}

# Send a POST request to the API
url = base_url + endpoint
response = requests.post(url, params=params, headers={"accept": "application/json"})

# Check the response status code
if response.status_code == 200:
    # 处理非标准JSON响应
    raw_response = response.text.strip('"')  # 去掉首尾的双引号
    raw_response = raw_response.replace("'", '"')  # 替换单引号为双引号
    response_data = json.loads(raw_response)  # 解析为字典
    text = response_data['choices'][0]['text']
    print("Response text: ", text)
else:
    print("Error:", response.status_code)

方案2:用ast.literal_eval直接解析(更健壮)

如果响应文本里存在带转义的单引号(比如'don\'t'),方案1的替换会出错,这时可以用ast.literal_eval()来直接解析Python格式的字符串字典:

替换解析部分的代码即可:

import ast
# ...其他代码保持不变
if response.status_code == 200:
    raw_response = response.text.strip('"')
    response_data = ast.literal_eval(raw_response)
    text = response_data['choices'][0]['text']
    print("Response text: ", text)

内容的提问来源于stack exchange,提问作者CyberSardinha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:18:17