Issue
I did this script to get a api response from https://github.com/serge-chat/serge:
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)
This is the example of a response:
"{'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}}"
I wanted the script to output the text only from this response but I get this error:
text = response_data['choices'][0]['text']
TypeError: string indices must be integers
I'm a complete beginner at Python. I have no clue why that doesn't work :/
Solution
Your response is a string; you can do:
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.'
Answered By - Goku
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.