Dino Geek, try to help you

How to save ChatGPT API responses to a database?


Here’s a simple Python example of saving a ChatGPT API response to a SQLite database.

First, install necessary packages (if not already installed) using pip:
```
pip install openai sqlite3
```

And here’s the Python code to do it:

```
import sqlite3
from openai import OpenAI

openai.api_key = ‘your-api-key’

  1. Get a chat response from the OpenAI API
    response = openai.ChatCompletion.create( model=“gpt-3.5-turbo”, messages=[ {“role”: “system”, “content”: “You are a helpful assistant.”}, {“role”: “user”, “content”: “Who won the world series in 2020?”}, ]
    )
  1. Establish a connection to the SQLite database (this will create the file if it doesn’t exist)
    conn = sqlite3.connect(‘chat_gpt_responses.db’)
  1. Create a cursor object
    c = conn.cursor()
  1. Create table
    c.execute(‘’‘CREATE TABLE IF NOT EXISTS responses (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT)’‘’)
  1. Save the API response to the database
    c.execute(“INSERT INTO responses (content) VALUES (?)”,(str(response),))
  1. Commit the transaction and close the connection
    conn.commit()
    conn.close()
    ```

Please replace `‘your-api-key’` with your actual OpenAI API key!

This example saves the entire API response into a SQLite database in your local file system. Please also adjust to suit your needs! The response is saved as a string. You may want to save individual fields in separate columns, or in some other way.

Remember, for a real-world application, you’ll probably want to use a more robust approach to handle database connections and errors! Also consider appropriate safety and privacy aspects when storing responses.

By the way, installing `sqlite3` might not be necessary, because it’s included in Python by default from version 2.5 onwards.


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