platform

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2023 License: MIT Imports: 10 Imported by: 0

README

Simple OpenAI Platform API

Support list keys add key and delete key with it

checkout test/demo.go file about it

Idea comes from https://github.com/linweiyuan/go-chatgpt-api project. Thanks and respect.

Lib Usage


package main

import (
	"log"
	"github.com/esonhugh/openai-platform-api"
)

func main() {
	c := platform.NewUserPlatformClient("accessToken there")
	_, err := c.LoginWithAccessToken()
	if err != nil {
		log.Println(err)
		return
	}
	// if you want accessToken based without login by username and password please use this with
	//  c.LoginWithAccessToken()
	// or replace it with
	//  c.LoginWithAuth0("username", "password")
	resp, err := c.GetSecretKeys()
	if err != nil {
		log.Println(err)
		return
	}
	log.Println(resp)
}

Cli tool guides

Installation
go install github.com/esonhugh/openai-platform-api/cmd/openai-cli@latest
Before use
# you need create a config file in ~/.config folder
cat << EOF > ~/.config/openai-cli/config.yaml
openai:
  username: your-openai-username
  password: your-openai-password
secret_key_prefix: temp
EOF
Basic Usage
export https_proxy=http://127.0.0.1:7890 # optional
openai-cli key ls

Documentation

Index

Constants

View Source
const (
	PlatformApiPrefix    = "/platform"
	PlatformApiUrlPrefix = "https://api.openai.com"

	AuthorizationHeader                = "Authorization"
	XAuthorizationHeader               = "X-Authorization"
	ContentType                        = "application/x-www-form-urlencoded"
	UserAgent                          = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
	Auth0Url                           = "https://auth0.openai.com"
	LoginUsernameUrl                   = Auth0Url + "/u/login/identifier?state="
	LoginPasswordUrl                   = Auth0Url + "/u/login/password?state="
	ParseUserInfoErrorMessage          = "Failed to parse user login info."
	GetAuthorizedUrlErrorMessage       = "Failed to get authorized url."
	GetStateErrorMessage               = "Failed to get state."
	EmailInvalidErrorMessage           = "Email is not valid."
	EmailOrPasswordInvalidErrorMessage = "Email or password is not correct."
	GetAccessTokenErrorMessage         = "Failed to get access token."
	GetArkoseTokenErrorMessage         = "Failed to get arkose token."

	EmailKey                       = "email"
	AccountDeactivatedErrorMessage = "Account %s is deactivated."

	ReadyHint = "Service go-chatgpt-api is ready."
)

Variables

This section is empty.

Functions

func GetLastMonth added in v0.2.0

func GetLastMonth() (string, string)

func NewHttpClient

func NewHttpClient(logger tls_client.Logger) tls_client.HttpClient

Types

type ActionMap

type ActionMap struct {
	Action      string `json:"action"`
	Name        string `json:"name,omitempty"`
	RedactedKey string `json:"redacted_key,omitempty"`
	CreatedAt   int    `json:"created_at,omitempty"`
}

type CreateSecretKeyResponse

type CreateSecretKeyResponse struct {
	Result string `json:"result"`
	Key    Key    `json:"key"`
}

type DailyCost added in v0.2.0

type DailyCost struct {
	Timestamp float64 `json:"timestamp"`
	LineItems []struct {
		Name string  `json:"name"`
		Cost float64 `json:"cost"`
	} `json:"line_items"`
}

type DashboardLoginResponse

type DashboardLoginResponse struct {
	Object  string        `json:"object"`
	User    User          `json:"user"`
	Invites []interface{} `json:"invites"`
}

type DeleteSecretKeyResponse

type DeleteSecretKeyResponse struct {
	Result string `json:"result"`
}

type GetAccessTokenRequest

type GetAccessTokenRequest struct {
	ClientID    string `json:"client_id"`
	GrantType   string `json:"grant_type"`
	Code        string `json:"code"`
	RedirectURI string `json:"redirect_uri"`
}

type GetAccessTokenResponse

type GetAccessTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	IDToken      string `json:"id_token"`
	Scope        string `json:"scope"`
	ExpiresIn    int    `json:"expires_in"`
	TokenType    string `json:"token_type"`
}

type GetSecretKeysResponse

type GetSecretKeysResponse struct {
	Object string `json:"object"`
	Data   []Key  `json:"data"`
}

type Key

type Key struct {
	SensitiveID string `json:"sensitive_id"`
	Object      string `json:"object"`
	Name        string `json:"name"`
	Created     int    `json:"created"`
	LastUse     int    `json:"last_use"`
	Publishable bool   `json:"publishable"`
}

type Org

type Org struct {
	Object      string        `json:"object"`
	ID          string        `json:"id"`
	Created     int           `json:"created"`
	Title       string        `json:"title"`
	Name        string        `json:"name"`
	Description interface{}   `json:"description"`
	Personal    bool          `json:"personal"`
	IsDefault   bool          `json:"is_default"`
	Role        string        `json:"role"`
	Groups      []interface{} `json:"groups"`
}

type Orgs

type Orgs struct {
	Object string `json:"object"`
	Data   []Org  `json:"data"`
}

type PaymentHistoryResponse added in v0.2.0

type PaymentHistoryResponse struct {
	Object string `json:"object"`
	Data   []struct {
		Object            string      `json:"object"`
		ID                string      `json:"id"`
		Number            string      `json:"number"`
		AmountDue         int         `json:"amount_due"`
		AmountPaid        int         `json:"amount_paid"`
		Tax               int         `json:"tax"`
		TotalExcludingTax int         `json:"total_excluding_tax"`
		Total             int         `json:"total"`
		Created           int         `json:"created"`
		PdfURL            string      `json:"pdf_url"`
		HostedInvoiceURL  string      `json:"hosted_invoice_url"`
		CollectionMethod  string      `json:"collection_method"`
		DueDate           interface{} `json:"due_date"`
		Status            string      `json:"status"`
	} `json:"data"`
}

type PaymentMethodResponse added in v0.2.0

type PaymentMethodResponse struct {
	Object string `json:"object"`
	Data   []struct {
		Object string `json:"object"`
		ID     string `json:"id"`
		Type   string `json:"type"`
		Card   struct {
			Brand    string `json:"brand"`
			Last4    string `json:"last4"`
			ExpMonth int    `json:"exp_month"`
			ExpYear  int    `json:"exp_year"`
			Country  string `json:"country"`
		} `json:"card"`
		IsDefault bool `json:"is_default"`
	} `json:"data"`
}

type Session

type Session struct {
	SensitiveID string      `json:"sensitive_id"`
	Object      string      `json:"object"`
	Name        interface{} `json:"name"`
	Created     int         `json:"created"`
	LastUse     int         `json:"last_use"`
	Publishable bool        `json:"publishable"`
}

type SubscriptionResponse added in v0.2.0

type SubscriptionResponse struct {
	Object             string      `json:"object"`
	HasPaymentMethod   bool        `json:"has_payment_method"`
	Canceled           bool        `json:"canceled"`
	CanceledAt         interface{} `json:"canceled_at"`
	Delinquent         interface{} `json:"delinquent"`
	AccessUntil        int         `json:"access_until"`
	SoftLimit          int         `json:"soft_limit"`
	HardLimit          int         `json:"hard_limit"`
	SystemHardLimit    int         `json:"system_hard_limit"`
	SoftLimitUsd       float64     `json:"soft_limit_usd"`
	HardLimitUsd       float64     `json:"hard_limit_usd"`
	SystemHardLimitUsd float64     `json:"system_hard_limit_usd"`
	Plan               struct {
		Title string `json:"title"`
		ID    string `json:"id"`
	} `json:"plan"`
	Primary        bool        `json:"primary"`
	AccountName    string      `json:"account_name"`
	PoNumber       interface{} `json:"po_number"`
	BillingEmail   interface{} `json:"billing_email"`
	TaxIds         interface{} `json:"tax_ids"`
	BillingAddress struct {
		City       string `json:"city"`
		Line1      string `json:"line1"`
		Line2      string `json:"line2"`
		State      string `json:"state"`
		Country    string `json:"country"`
		PostalCode string `json:"postal_code"`
	} `json:"billing_address"`
	BusinessAddress interface{} `json:"business_address"`
}

type UsageResponse added in v0.2.0

type UsageResponse struct {
	Object     string      `json:"object"`
	DailyCosts []DailyCost `json:"daily_costs"`
	TotalUsage float64     `json:"total_usage"`
}

type User

type User struct {
	Object       string        `json:"object"`
	ID           string        `json:"id"`
	Email        string        `json:"email"`
	Name         string        `json:"name"`
	Picture      string        `json:"picture"`
	Created      int           `json:"created"`
	Groups       []interface{} `json:"groups"`
	Session      Session       `json:"session"`
	Orgs         Orgs          `json:"orgs"`
	IntercomHash string        `json:"intercom_hash"`
	Amr          []interface{} `json:"amr"`
}

type UserClient

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

func NewUserPlatformClient

func NewUserPlatformClient(accessToken string) *UserClient

NewUserPlatformClient called NewHttpClient with log.

func (*UserClient) AccessToken

func (u *UserClient) AccessToken() string

func (*UserClient) CreateSecretKey

func (u *UserClient) CreateSecretKey(name string) (CreateSecretKeyResponse, error)

func (*UserClient) DashboardOnBoarding

func (u *UserClient) DashboardOnBoarding() (DashboardLoginResponse, error)

func (*UserClient) DashboardSubscription added in v0.2.0

func (u *UserClient) DashboardSubscription() (SubscriptionResponse, error)

func (*UserClient) DeleteSecretKey

func (u *UserClient) DeleteSecretKey(key Key) (DeleteSecretKeyResponse, error)

func (*UserClient) GetInvoices added in v0.2.0

func (u *UserClient) GetInvoices() (PaymentHistoryResponse, error)

func (*UserClient) GetSecretKeys

func (u *UserClient) GetSecretKeys() (GetSecretKeysResponse, error)

func (*UserClient) LastResponse added in v0.2.0

func (u *UserClient) LastResponse() *http.Response

func (*UserClient) LoginWithAccessToken

func (u *UserClient) LoginWithAccessToken() (DashboardLoginResponse, error)

func (*UserClient) LoginWithAuth0

func (u *UserClient) LoginWithAuth0(Username, Password string) error

func (*UserClient) Logout

func (u *UserClient) Logout() error

func (*UserClient) PaymentHistory added in v0.2.0

func (u *UserClient) PaymentHistory() (PaymentHistoryResponse, error)

func (*UserClient) PaymentMethod added in v0.2.0

func (u *UserClient) PaymentMethod() (PaymentMethodResponse, error)

func (*UserClient) RawCheckPassword added in v0.2.0

func (u *UserClient) RawCheckPassword(state string, username string, password string) (string, int, error)

func (*UserClient) RawCheckUsername added in v0.2.0

func (u *UserClient) RawCheckUsername(state string, username string) (int, error)

func (*UserClient) RawDashboardLogin added in v0.2.0

func (u *UserClient) RawDashboardLogin(AccessToken string) (string, int, error)

func (*UserClient) RawGetAccessToken added in v0.2.0

func (u *UserClient) RawGetAccessToken(code string) (string, int, error)

func (*UserClient) RawGetAuthorizedUrl added in v0.2.0

func (u *UserClient) RawGetAuthorizedUrl(csrfToken string) (string, int, error)

func (*UserClient) RawGetStateByAuthorizedUrl added in v0.2.0

func (u *UserClient) RawGetStateByAuthorizedUrl(authorizedUrl string) (string, int, error)

func (*UserClient) SessionKey

func (u *UserClient) SessionKey() string

func (*UserClient) UsageWithSecretKey added in v0.2.0

func (u *UserClient) UsageWithSecretKey(sk, StartDate, EndDate string) (UsageResponse, error)

func (*UserClient) UsageWithSessionToken added in v0.2.0

func (u *UserClient) UsageWithSessionToken(StartDate, EndDate string) (UsageResponse, error)

func (*UserClient) WithCustomHttpClient added in v0.2.0

func (u *UserClient) WithCustomHttpClient(client tls_client.HttpClient) *UserClient

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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