chatgpt

package module
v0.0.0-...-51a04cc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2023 License: GPL-3.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ChatGPT
ChatGPT - A Golang wrapper for the GPT model from OpenAI

ChatGPT

GoDoc Go Report Card GitHub license GitHub Actions Discuss on Telegram

ChatGPT is a wrapper for the GPT model from OpenAI purely built on Golang. The application has various features, including asking questions and getting responses, remembering the context of the conversation, exporting the conversation to a file, and importing the conversation from a file.

The app also allows users to get the conversation history, use multiple models such as davinci, gpt 3, gpt 3.5, and gpt 4. Other features include API Key Authentication, Customizable temperature of the model, Inbuilt Tokenizer for the model, and http/https proxy support for the client.

Table of Contents

Features

Here are some notable features of the wrapper:

  • Authenticate using the API Key, which can be obtained from the OpenAI Dashboard.
  • Authenticate using the access_token or email/password.
  • Cache the authentication token for future use.
  • Multiple Accounts support, with same cache file.
  • Remember the context of the conversation.
  • Export the conversation to a file.
  • Get the conversation history.
  • Models: davinci, gpt 3, gpt 3.5, gpt 4.
  • API Key Authentication.
  • Customizable temperature of the model.
  • Inbuilt Tokenizer for the model.
  • https Proxy support for the client.
  • Support for streaming the response via a channel.

TODO

Below are some things that need to be added to the application:

  • Implement the internet plugin for the GPT model.
  • Add support for the top_p parameter.

Documentation

You can find the complete documentation for the CHATGPT package at GoDoc

Installation

You can install ChatGPT by running the following command on your terminal:

go get github.com/amarnathcjd/chatgpt

Or usking gopkg.in:

go get gopkg.in/chatgpt.v1

Usage

Here is an example of how to use ChatGPT package:

package chatgpt

import (
    "fmt"
    "context"

    "github.com/amarnathcjd/chatgpt"
)

func main() {
    client := chatgpt.NewClient(&chatgpt.Config{
        Email: "email@domain.com",
        Password: "password", // or ApiKey: "sk-xxxxxxxxxxxx",
    })
    if err := client.Start(); err != nil {
        panic(err) 
    }
    ask, err := client.Ask(context.Background(), "Hello, nice to meet you")
    if err != nil {
        panic(err)
    }
    fmt.Println("ChatGPT: ", ask.Message)
}

More examples can be found in the examples folder.

License

ChatGPT is released under the terms of the GPT-3 License. See LICENSE for more information or see The GPT-3 License.

Documentation

Index

Constants

View Source
const (
	ApiKeyMode      = iota // Set a value of 0 to ApiKeyMode. This indicates that the user of the program has set up API key properly.
	AccessTokenMode        // Set a value of 1 to AccessTokenMode. This indicates that the user of the program has set up access token properly.
)
View Source
const DEFAULT_INIT_MESSAGE = "You are chatGPT, trained on a very huge dataset of conversations. Act conversationally"

The default "system" message when starting a new conversation.

View Source
const OPENAI_HOST = "https://api.openai.com/v1/chat/completions"

The OpenAI API endpoint for chat completions.

Variables

This section is empty.

Functions

This section is empty.

Types

type AskOpts

type AskOpts struct {
	// The conversation ID to use for this request. If not specified, a new conversation ID will be generated.
	ConversationID string
	// The parent ID to use for this request. If not specified, a new parent ID will be generated.
	ParentID string
}

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

func (*Auth) ExpiresIn

func (a *Auth) ExpiresIn() time.Duration

ExpiresIn returns the remaining duration before the access token expires.

func (*Auth) GetAccessToken

func (a *Auth) GetAccessToken() (string, error)

GetAccessToken generates and retrieves the OpenAI API access token by performing a series of authentication steps.

type ChatError

type ChatError struct {
	Message string `json:"message,omitempty"`
	Code    int    `json:"code,omitempty"`
}

ChatError represents a chat/auth-specific error returned by this client.

func (*ChatError) Error

func (e *ChatError) Error() string

Error returns the string representation of a ChatError.

type ChatResponse

type ChatResponse struct {
	Message        string `json:"message,omitempty"`
	ConversationID string `json:"conversation_id,omitempty"`
	ParentID       string `json:"parent_id,omitempty"`
	Model          string `json:"model,omitempty"`
}

ChatResponse represents the response returned by this client.

type Choice

type Choice struct {
	Message      Message `json:"message,omitempty"`
	FinishReason string  `json:"finish_reason,omitempty"`
}

Choice represents a possible response and its finish reason from OpenAI's API.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a connection to the OpenAI API. It contains the client's API key, access token, HTTP client, conversation history, settings, and stream details.

func NewClient

func NewClient(config *Config, sessionName ...string) *Client

NewClient creates a new OpenAI API client with the given configuration. sessionName is an optional parameter that can be used to identify the client in case of multiple clients.

func (*Client) Ask

func (c *Client) Ask(ctx context.Context, prompt string, askOpts ...AskOpts) (*ChatResponse, error)

Ask sends a question to OpenAI API using the specified conversation ID or the default one.

func (*Client) AskInternet

func (c *Client) AskInternet(ctx context.Context, prompt string) (*ChatResponse, error)

AskInternet sends a question to the specified internet engine and returns the response/error.

func (*Client) AskStream

func (c *Client) AskStream(ctx context.Context, prompt string, askOpts ...AskOpts) (chan *ChatResponse, error)

AskStream sends a question to OpenAI API using the specified conversation ID or the default one and streams the response.

func (*Client) GetAPIKey

func (c *Client) GetAPIKey() string

GetAPIKey returns the API key used for authentication.

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() string

GetAccessToken returns the access token used for conversations.

func (*Client) GetConversation

func (c *Client) GetConversation(id string) (*Conversation, error)

GetConversation returns a specific conversation by ID, or an error if it doesn't exist.

func (*Client) GetConversations

func (c *Client) GetConversations() map[string]Conversation

GetConversations returns a map of all conversations currently stored in memory.

func (*Client) GetEnableInternet

func (c *Client) GetEnableInternet() bool

GetEnableInternet returns true if external websites can be accessed in responses.

func (*Client) GetEngine

func (c *Client) GetEngine() string

GetEngine returns the name of the GPT model being used.

func (*Client) GetProxy

func (c *Client) GetProxy() *url.URL

GetProxy returns the URL of the proxy server to use for requests.

func (*Client) GetStream

func (c *Client) GetStream() bool

GetStream returns true if response messages are streamed as they come in.

func (*Client) ResetConversation

func (c *Client) ResetConversation(id string) error

ResetConversation deletes a specific conversation by ID, or returns an error if it doesn't exist.

func (*Client) ResetConversations

func (c *Client) ResetConversations()

ResetConversations deletes all conversations from memory.

func (*Client) SetAPIKey

func (c *Client) SetAPIKey(apiKey string)

SetAPIKey sets the API key used for authentication.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(accessToken string)

SetAccessToken sets the access token used for conversations.

func (*Client) SetConversation

func (c *Client) SetConversation(id string, conv Conversation)

SetConversation sets a specific conversation by ID.

func (*Client) SetEmailAndPassword

func (c *Client) SetEmailAndPassword(email, password string)

SetEmailAndPassword sets the email and password used for authentication.

func (*Client) SetEngine

func (c *Client) SetEngine(engine string)

SetEngine sets the GPT model being used.

func (*Client) SetProxy

func (c *Client) SetProxy(proxy *url.URL)

SetProxy sets the proxy server to use for requests.

func (*Client) SetSessionName

func (c *Client) SetSessionName(sessionName string)

SetSessionName sets the session name used for authentication.

func (*Client) Start

func (c *Client) Start() error

Start initializes the client by checking credentials and authenticating with the OpenAI API.

func (*Client) ToggleInternet

func (c *Client) ToggleInternet(t bool)

ToggleInternet toggles whether or not to allow the use of external websites in responses.

func (*Client) ToggleStream

func (c *Client) ToggleStream(t bool)

ToggleStream toggles whether or not to stream response messages as they come in.

type Config

type Config struct {
	ApiKey         string   `json:"api_key,omitempty"`         // The API key used for authentication with OpenAI.
	Email          string   `json:"email,omitempty"`           // The email used for authentication with OpenAI.
	Password       string   `json:"password,omitempty"`        // The password used for authentication with OpenAI.
	AccessToken    string   `json:"access_token,omitempty"`    // The access token used for conversations with OpenAI.
	Engine         string   `json:"engine,omitempty"`          // The name of the GPT model being used.
	InitMessage    string   `json:"init_message,omitempty"`    // The initial message sent to start a new conversation.
	BaseURL        string   `json:"base_url,omitempty"`        // Custom base URL for the OpenAI API.
	Temperature    float64  `json:"temperature,omitempty"`     // The sampling temperature for generating text.
	LogLevel       LogLevel `json:"log_level,omitempty"`       // The log level to use for logging messages.
	IsPaid         bool     `json:"is_paid,omitempty"`         // Whether or not the account is a paid account.
	EnableInternet bool     `json:"enable_internet,omitempty"` // Whether or not to allow the use of external websites in responses.
	Stream         bool     `json:"stream,omitempty"`          // Whether or not to stream response messages as they come in.
	DisableCache   bool     `json:"disable_cache,omitempty"`   // Whether or not to disable caching of access tokens.
	Proxy          *url.URL `json:"proxy,omitempty"`           // The URL of the proxy server to use for requests.
}

Config represents the configuration options for a connection to the OpenAI API. Each field is optional and can be omitted from the JSON representation of the config object.

type Conversation

type Conversation struct {
	InitMessage string    // First message sent in the conversation.
	LastMessage string    // Most recent message sent in the conversation.
	Messages    []Message // Slice of Message structs representing all messages sent in the conversation.
}

Conversation represents a struct with three fields: InitMessage, LastMessage, and Messages.

func (*Conversation) Marshal

func (c *Conversation) Marshal() string

type InternetResponse

type InternetResponse []struct {
	// The title of the search result.
	Title string `json:"title"`

	// The URL of the search result.
	Link string `json:"link"`

	// A brief snippet of text from the search result.
	Snippet string `json:"snippet"`
}

InternetResponse is a slice of structs representing search results obtained from an internet search engine.

type LogLevel

type LogLevel int

LogLevel is an enum for the different log levels.

const (
	// LogLevelNone disables all logging.
	LogLevelNone LogLevel = iota
	// LogLevelDebug logs debug messages.
	LogLevelDebug
	// LogLevelInfo logs informational messages.
	LogLevelInfo
	// LogLevelWarn logs warning messages.
	LogLevelWarn
	// LogLevelError logs error messages.
	LogLevelError
)

type Logger

type Logger struct {
	// The minimum level of messages to log.
	Level LogLevel
	// contains filtered or unexported fields
}

Logger is a simple logger that can be used to log messages to the console.

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug logs a debug message.

func (*Logger) Error

func (l *Logger) Error(msg string)

Error logs an error message.

func (*Logger) Info

func (l *Logger) Info(msg string)

Info logs an informational message.

func (*Logger) SessionName

func (l *Logger) SessionName() string

SessionName returns the name of the session, or an empty string if it's the default session.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel sets the minimum level of messages to log.

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn logs a warning message.

type Message

type Message struct {
	Role    string `json:"role,omitempty"`    // Tag defies the JSON key name as "role" or omits the key if the value is empty.
	Content string `json:"content,omitempty"` // Tag defies the JSON key name as "content" or omits the key if the value is empty.
}

Message represents a struct with two fields: Role and Content.

type OpenAIError

type OpenAIError struct {
	ErrorData struct {
		Message string `json:"message"`
		Type    string `json:"type"`
		Param   string `json:"param"`
		Code    int    `json:"code"`
	} `json:"error"`
}

OpenAIError represents an error returned by OpenAI's API.

type OpenAIResponse

type OpenAIResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Usage   struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
	Choices []Choice `json:"choices"`
}

OpenAIResponse represents the response returned by OpenAI's API.

func (*OpenAIResponse) GetResponse

func (r *OpenAIResponse) GetResponse() string

type Payload

type Payload struct {
	// The ID of the OpenAI model to use for the request.
	Model string `json:"model"`

	// An array of Message structs representing the conversation so far.
	Messages []Message `json:"messages"`

	// The "temperature" parameter controls the "creativity" of the AI's responses. Higher values will generate more diverse and unexpected responses.
	Temperature float64 `json:"temperature"`

	// The "top-p" parameter controls the "conservatism" of the AI's responses. Lower values will generate more predictable and "safe" responses.
	TopP float64 `json:"top_p"`
}

Payload represents the structure of the JSON payload sent by askOpenAI.

type TokenGen

type TokenGen struct {
	// contains filtered or unexported fields
}

func NewTokenGen

func NewTokenGen() *TokenGen

func (*TokenGen) CloseChrome

func (t *TokenGen) CloseChrome()

func (*TokenGen) GetToken

func (t *TokenGen) GetToken(email, password string) (string, error)

func (*TokenGen) StartChrome

func (t *TokenGen) StartChrome() (context.Context, error)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址