我编写这个脚本是为了从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的初学者。我不知道为什么它不起作用:/
1条答案
按热度按时间tez616oj1#
你的响应是一个字符串;你可以这样做:
字符串