Python API 错误:“TypeError:字符串索引必须是整数”

Python API error: "TypeError: string indices must be integers"

提问人:CyberSardinha 提问时间:11/7/2023 最后编辑:Goku - stands with PalestineCyberSardinha 更新时间:11/8/2023 访问量:64

问:

我做了这个脚本来获得来自 https://github.com/serge-chat/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)

以下是响应的示例:

"{'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']
TypeError: string indices must be integers

我是 Python 的完全初学者。我不知道为什么这不起作用:/

蟒蛇 json python-3.x rest

评论

1赞 JonSG 11/7/2023
当你说你发布的字符串是响应的一个例子时,这就是你得到的吗?如果你返回 str 还是 dict?response.json()print(type(response_data))

答:

0赞 Goku - stands with Palestine 11/7/2023 #1

您的响应是一个字符串;您可以执行以下操作:

from ast import literal_eval

response_data = literal_eval("{'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}}")

response_data['choices'][0]['text']

#output
'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.'

评论

1赞 tripleee 11/7/2023
也许还要注意,这表明服务器中存在产生此结果的错误。
0赞 Goku - stands with Palestine 11/7/2023
是的,你是对的@tripleee