chatgpt

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2023 License: MIT Imports: 13 Imported by: 1

README

if you want to use GPT-3 apis, look at this one: GPT-3 SDK,

chatgpt-go

chatgpt sdk writen by golang.

Preparation

you should login into the ChatGPT Website firstly, find the Cookies named cf_clearance,__Secure-next-auth.session-token, and copy their values.

_puid cookie is required too, while only plus user can find it in their cookies after login ChatGPT official website.

Quick Start

  1. install chatgpt-go sdk
go get -u github.com/chatgp/chatgpt-go
  1. chat in independent conversation
package main

import (
	"log"
	"net/http"
	"time"

	chatgpt "github.com/chatgp/chatgpt-go"
)

func main() {
	token := `copy-from-cookies`
	cfValue := "copy-from-cookies"
	puid := "copy-from-cookies"

	cookies := []*http.Cookie{
		{
			Name:  "__Secure-next-auth.session-token",
			Value: token,
		},
		{
			Name:  "cf_clearance",
			Value: cfValue,
		},
		{
			Name:  "_puid",
			Value: puid,
		},
	}

	cli := chatgpt.NewClient(
		chatgpt.WithDebug(true),
		chatgpt.WithTimeout(60*time.Second),
		chatgpt.WithCookies(cookies),
	)

	// chat in independent conversation
	message := "say hello to me"
	text, err := cli.GetChatText(message)
	if err != nil {
		log.Fatalf("get chat text failed: %v", err)
	}

	log.Printf("q: %s, a: %s\n", message, text.Content)
}
  1. chat in continuous conversation
package main

import (
	"log"
	"net/http"
	"time"

	chatgpt "github.com/chatgp/chatgpt-go"
)

func main() {
	// new chatgpt client
	token := `copy-from-cookies`
	cfValue := "copy-from-cookies"

	cookies := []*http.Cookie{
		{
			Name:  "__Secure-next-auth.session-token",
			Value: token,
		},
		{
			Name:  "cf_clearance",
			Value: cfValue,
		},
	}

	cli := chatgpt.NewClient(
		chatgpt.WithDebug(true),
		chatgpt.WithTimeout(60*time.Second),
		chatgpt.WithCookies(cookies),
	)

	// chat in continuous conversation

	// first message
	message := "say hello to me"
	text, err := cli.GetChatText(message)
	if err != nil {
		log.Fatalf("get chat text failed: %v", err)
	}

	log.Printf("q: %s, a: %s\n", message, text.Content)

	// continue conversation with new message
	conversationID := text.ConversationID
	parentMessage := text.MessageID
	newMessage := "again"

	newText, err := cli.GetChatText(newMessage, conversationID, parentMessage)
	if err != nil {
		log.Fatalf("get chat text failed: %v", err)
	}

	log.Printf("q: %s, a: %s\n", newMessage, newText.Content)
}

if you want to start a new conversation out of current conversation, you don't need to reset the client. just remove the conversationIDparentMessage arguments in GetChatText method and use it to get a new text reply.

  1. get chat content with stream
package main

import (
	"log"
	"net/http"
	"time"

	chatgpt "github.com/chatgp/chatgpt-go"
)

func main() {
	// new chatgpt client
	token := `copy-from-cookies`
	cfValue := "copy-from-cookies"

	cookies := []*http.Cookie{
		{
			Name:  "__Secure-next-auth.session-token",
			Value: token,
		},
		{
			Name:  "cf_clearance",
			Value: cfValue,
		},
	}

	cli := chatgpt.NewClient(
		chatgpt.WithDebug(true),
		chatgpt.WithTimeout(60*time.Second),
		chatgpt.WithCookies(cookies),
	)

	message := "say hello to me"
	stream, err := cli.GetChatStream(message)
	if err != nil {
		log.Fatalf("get chat stream failed: %v\n", err)
	}

	var answer string
	for text := range stream.Stream {
		log.Printf("stream text: %s\n", text.Content)
		answer = text.Content
	}

	if stream.Err != nil {
		log.Fatalf("stream closed with error: %v\n", stream.Err)
	}

	log.Printf("q: %s, a: %s\n", message, answer)
}

Tests

under examples folder there are some tests, execute go test command and get outputs like below:

  • get chat text

  • get chat text in continuous conversation

  • get chat text from stream

Communication

Documentation

Index

Constants

View Source
const (
	BASE_URI         = "https://chat.openai.com"
	AUTH_SESSION_URI = "https://chat.openai.com/api/auth/session"
	CONVERSATION_URI = "https://chat.openai.com/backend-api/conversation"
	GET_MODELS_URI   = "https://chat.openai.com/backend-api/models"
	USER_AGENT       = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
	EOF_TEXT         = "[DONE]"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatStream

type ChatStream struct {
	Stream chan *ChatText // chat text stream
	Err    error          // error message
}

ChatStream chat reply with sream

type ChatText

type ChatText struct {
	ConversationID string `json:"conversation_id"` // conversation context id
	MessageID      string `json:"message_id"`      // current message id, can used as next chat's parent_message_id
	Content        string `json:"content"`         // text content
	Model          string `json:"model"`           // chat model
	CreatedAt      int64  `json:"created_at"`      // message create_time
	// contains filtered or unexported fields
}

ChatText chat reply with text format

func (*ChatText) Raw added in v1.4.0

func (c *ChatText) Raw() string

ChatText raw data

func (*ChatText) String added in v1.3.0

func (c *ChatText) String() string

ChatText format to string

type Client

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

Client is a ChatGPT request client

func NewClient

func NewClient(options ...Option) *Client

NewClient will return a ChatGPT request client

func (*Client) AuthSession added in v1.4.0

func (c *Client) AuthSession() (*gjson.Result, error)

AuthSession will check if session is expired and return a new accessToken

func (*Client) GetChatStream added in v1.1.0

func (c *Client) GetChatStream(message string, args ...string) (*ChatStream, error)

GetChatStream will return text stream

func (*Client) GetChatText

func (c *Client) GetChatText(message string, args ...string) (*ChatText, error)

GetChatText will return text message

func (*Client) GetModels added in v1.4.0

func (c *Client) GetModels() (*gjson.Result, []*http.Cookie, error)

GetModels to get all availabel model s

func (*Client) WithModel added in v1.4.0

func (c *Client) WithModel(model string) *Client

WithModel: set chat model

type MixMap

type MixMap = map[string]interface{}

MixMap is a type alias for map[string]interface{}

type Option

type Option func(*Client)

Option is used to set custom option

func WithAccessToken added in v1.2.0

func WithAccessToken(accessToken string) Option

WithAccessToken is used to set accessToken

func WithCookie added in v1.2.0

func WithCookie(cookie string) Option

WithCookie is used to set request cookies in header

func WithCookies added in v1.1.0

func WithCookies(cookies []*http.Cookie) Option

WithCookies is used to set request cookies

func WithDebug added in v1.1.0

func WithDebug(debug bool) Option

WithDebug is used to output debug message

func WithModel added in v1.3.0

func WithModel(model string) Option

WithModel is used to set chat model

func WithProxy added in v1.2.0

func WithProxy(proxy string) Option

WithProxy is used to set request proxy

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout is used to set request timeout

func WithUserAgent added in v1.1.0

func WithUserAgent(userAgent string) Option

WithUserAgent is used to set request user-agent

type Options

type Options struct {
	// Debug is used to output debug message
	Debug bool
	// Timeout is used to end http request after timeout duration
	Timeout time.Duration
	// UserAgent is used for custom user-agent
	UserAgent string
	// Cookies is request cookies for each api
	Cookies []*http.Cookie
	// Cookie will set in request headers with string format
	Cookie string
	// Proxy is used to proxy request
	Proxy string
	// AccessToken is used to authorization
	AccessToken string
	// Model is the chat model
	Model string
}

Options can set custom options for ChatGPT request client

Jump to

Keyboard shortcuts

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