labteral / chatgpt-python

Unofficial Python SDK for OpenAI's ChatGPT
https://labteral.github.io/chatgpt-python/
GNU General Public License v3.0
523 stars 76 forks source link
chatgpt davinci gpt-3 gpt3-library openai

ChatGPT Python SDK

Library that allows developers to easily integrate the ChatGPT into their Python projects.

PyPi PyPi License

Install or update

pip install -U chatgpt

Config

Create a file with your credentials

Create the file config.json in your working directory:

{
    "email": "email@example.org",
    "password": "xxx"
}

With proxy

{
    "email": "email@example.org",
    "password": "xxx",
    "proxy": "socks5://user:pass@host:port"
}

With other parameters

{
    "email": "email@example.org",
    "password": "xxx",
    "timeout":300,
    "cache_file_path":"/path/filename",
    "access_token_seconds_to_expire":1800
}

Environment variable

You can specify the default configuration folder for chatgpt by setting the CHATGPT_HOME environment variable to the desired directory path.

export CHATGPT_HOME="/home/$USER/.config/chatgpt"

Usage

CLI

You can launch the CLI with:

chatgpt

or

python -m chatgpt

These are the available commands:


![](img/cli_example.gif)


SDK

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from chatgpt import Conversation

conversation = Conversation()

# Stream the message as it arrives.
for chunk in conversation.stream("We are going to start a conversation. I will speak English and you will speak Portuguese."):
    print(chunk, end="")
    sys.stdout.flush()

# Wait until the message is fully received.
print(conversation.chat("What's the color of the sky?"))

# The AI will forget it was speaking Portuguese
conversation.reset()
print(conversation.chat("What's the color of the sun?"))

it is recommended to use stream instead of chat.

Exceptions:

from chatgpt import ChatgptError, ChatgptErrorCodes

try:

    for chunk in conversation.stream("Hello, world!"):
        print(chunk, end="")
        sys.stdout.flush()

except ChatgptError as chatgpt_error:

    message = chatgpt_error.message
    code = chatgpt_error.code

    if code == ChatgptErrorCodes.INVALID_ACCESS_TOKEN:
        print("Invalid token")

Chatgpt Error codes: