Dino Geek, try to help you

How to parse response from ChatGPT API?


When you make a request to the ChatGPT API, you will receive a JSON response. Here is what a typical response from the API might look like:

```
{ ‘id’: ‘chatcmpl-ZZYZYZYZYZ’, ‘object’: ‘chat.completion’, ‘created’: 1626189075, ‘model’: ‘text-davinci-002’, ‘usage’: {‘prompt_tokens’: 56, ‘completion_tokens’: 31, ‘total_tokens’: 87}, ‘choices’: [ { ‘message’: { ‘role’: ‘system’, ‘content’: ‘You are a helpful assistant.‘ }, ‘finish_reason’: ‘stop’, ‘index’: 0 }, { ‘message’: { ‘role’: ‘user’, ‘content’: ‘Who won the world series in 2020?‘ }, ‘finish_reason’: ‘stop’, ‘index’: 1 }, { ‘message’: { ‘role’: ‘assistant’, ‘content’: ‘The Los Angeles Dodgers won the World Series in 2020.‘ }, ‘finish_reason’: ‘stop’, ‘index’: 2 }]
}
```

To parse this response, you would typically use the json package in Python. Here is how you might do it:

```
import json

  1. Assume `response` is the JSON response you received from the API.
    parsed_response = json.loads(response)
  1. Now you can access the fields in the response.
    for choice in parsed_response[‘choices’]: role = choice[‘message’][‘role’] content = choice[‘message’][‘content’] print(f”{role}: {content}”)
    ```

This will print:

```
system: You are a helpful assistant.
user: Who won the world series in 2020?
assistant: The Los Angeles Dodgers won the World Series in 2020.
```

Of course, the exact structure of the response might vary depending on the specific API and parameters you used. Always check the API documentation for accurate details.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use