qianfan

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

百度千帆大模型平台 Go SDK

千帆SDK提供大模型工具链最佳实践,让AI工作流和AI原生应用优雅且便捷地访问千帆大模型平台。 目前 SDK 提供了以下功能:

* 大模型推理:实现了对一言(ERNIE-Bot)系列、开源大模型等模型推理的接口封装,支持对话、补全、Embedding等。

Index

Constants

View Source
const (
	DefaultChatCompletionModel = "ERNIE-Bot-turbo"
	DefaultCompletionModel     = "ERNIE-Bot-turbo"
	DefaultEmbeddingModel      = "Embedding-V1"
)

默认使用的模型

View Source
const (
	NoErrorErrCode                    = 0
	UnknownErrorErrCode               = 1
	ServiceUnavailableErrCode         = 2
	UnsupportedMethodErrCode          = 3
	RequestLimitReachedErrCode        = 4
	NoPermissionToAccessDataErrCode   = 6
	GetServiceTokenFailedErrCode      = 13
	AppNotExistErrCode                = 15
	DailyLimitReachedErrCode          = 17
	QPSLimitReachedErrCode            = 18
	TotalRequestLimitReachedErrCode   = 19
	InvalidRequestErrCode             = 100
	APITokenInvalidErrCode            = 110
	APITokenExpiredErrCode            = 111
	InternalErrorErrCode              = 336000
	InvalidArgumentErrCode            = 336001
	InvalidJSONErrCode                = 336002
	InvalidParamErrCode               = 336003
	PermissionErrorErrCode            = 336004
	APINameNotExistErrCode            = 336005
	ServerHighLoadErrCode             = 336100
	InvalidHTTPMethodErrCode          = 336101
	InvalidArgumentSystemErrCode      = 336104
	InvalidArgumentUserSettingErrCode = 336105

	ConsoleInternalErrorErrCode = 500000
)

API 错误码

View Source
const Version = "v0.0.2"

SDK 版本

Variables

View Source
var ChatModelEndpoint = map[string]string{
	"ERNIE-Bot-turbo":              "/chat/eb-instant",
	"ERNIE-Bot":                    "/chat/completions",
	"ERNIE-Bot-4":                  "/chat/completions_pro",
	"ERNIE-Bot-8k":                 "/chat/ernie_bot_8k",
	"ERNIE-3.5-4K-0205":            "/chat/ernie-3.5-4k-0205",
	"ERNIE-3.5-8K-0205":            "/chat/ernie-3.5-8k-0205",
	"ERNIE-Speed":                  "/chat/ernie_speed",
	"ERNIE-Bot-turbo-AI":           "/chat/ai_apaas",
	"EB-turbo-AppBuilder":          "/chat/ai_apaas",
	"BLOOMZ-7B":                    "/chat/bloomz_7b1",
	"Llama-2-7b-chat":              "/chat/llama_2_7b",
	"Llama-2-13b-chat":             "/chat/llama_2_13b",
	"Llama-2-70b-chat":             "/chat/llama_2_70b",
	"Qianfan-BLOOMZ-7B-compressed": "/chat/qianfan_bloomz_7b_compressed",
	"Qianfan-Chinese-Llama-2-7B":   "/chat/qianfan_chinese_llama_2_7b",
	"ChatGLM2-6B-32K":              "/chat/chatglm2_6b_32k",
	"AquilaChat-7B":                "/chat/aquilachat_7b",
	"XuanYuan-70B-Chat-4bit":       "/chat/xuanyuan_70b_chat",
	"Qianfan-Chinese-Llama-2-13B":  "/chat/qianfan_chinese_llama_2_13b",
	"ChatLaw":                      "/chat/chatlaw",
	"Yi-34B-Chat":                  "/chat/yi_34b_chat",
}

内置 chat 模型的 endpoint

View Source
var CompletionModelEndpoint = map[string]string{
	"SQLCoder-7B":           "/completions/sqlcoder_7b",
	"CodeLlama-7b-Instruct": "/completions/codellama_7b_instruct",
}

内置 Completion 模型的 endpoint

View Source
var EmbeddingEndpoint = map[string]string{
	"Embedding-V1": "/embeddings/embedding-v1",
	"bge-large-en": "/embeddings/bge_large_en",
	"bge-large-zh": "/embeddings/bge_large_zh",
	"tao-8k":       "/embeddings/tao_8k",
}

内置 Embedding 模型的 endpoint

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code int
	Msg  string
}

API 返回错误

func (*APIError) Error

func (e *APIError) Error() string

type AccessTokenRequest

type AccessTokenRequest struct {
	GrantType    string `mapstructure:"grant_type"`
	ClientId     string `mapstructure:"client_id"`
	ClientSecret string `mapstructure:"client_secret"`
}

type AccessTokenResponse

type AccessTokenResponse struct {
	AccessToken      string `json:"access_token"`
	ExpiresIn        int    `json:"expires_in"`
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description"`
	SessionKey       string `json:"session_key"`
	RefreshToken     string `json:"refresh_token"`
	Scope            string `json:"scope"`
	SessionSecret    string `json:"session_secret"`
	// contains filtered or unexported fields
}

func (*AccessTokenResponse) GetErrorCode

func (r *AccessTokenResponse) GetErrorCode() string

func (*AccessTokenResponse) SetResponse

func (r *AccessTokenResponse) SetResponse(Body []byte, RawResponse *http.Response)

设置回复中通用参数的字段

type AuthManager

type AuthManager struct {
	*Requestor
	// contains filtered or unexported fields
}

func GetAuthManager

func GetAuthManager() *AuthManager

func (*AuthManager) GetAccessToken

func (m *AuthManager) GetAccessToken(ak, sk string) (string, error)

func (*AuthManager) GetAccessTokenWithRefresh

func (m *AuthManager) GetAccessTokenWithRefresh(ak, sk string) (string, error)

type BaseModel

type BaseModel struct {
	Model      string // 使用的模型名称
	Endpoint   string // 使用的模型服务地址
	*Requestor        // Requstor 作为基类
}

模型相关的结构体基类

type BaseRequestBody

type BaseRequestBody struct {
	Extra map[string]interface{} `mapstructure:"-"`
}

请求体基类

实现了允许用户传递额外参数的方法

func (*BaseRequestBody) GetExtra

func (r *BaseRequestBody) GetExtra() map[string]interface{}

获取额外参数

func (*BaseRequestBody) SetExtra

func (r *BaseRequestBody) SetExtra(m map[string]interface{})

设置额外参数

func (*BaseRequestBody) SetStream

func (r *BaseRequestBody) SetStream()

将请求设置为流式

type ChatCompletion

type ChatCompletion struct {
	BaseModel
}

用于 chat 类型模型的结构体

func NewChatCompletion

func NewChatCompletion(optionList ...Option) *ChatCompletion

创建一个 ChatCompletion 对象

chat := qianfan.NewChatCompletion()  // 默认使用 ERNIE-Bot-turbo 模型

// 可以通过 WithModel 指定模型
chat := qianfan.NewChatCompletion(
    qianfan.WithModel("ERNIE-Bot-4"),  // 支持的模型可以通过 chat.ModelList() 获取
)
// 或者通过 WithEndpoint 指定 endpoint
chat := qianfan.NewChatCompletion(
    qianfan.WithEndpoint("your_custom_endpoint"),
)

func (*ChatCompletion) Do

发送 chat 请求

func (*ChatCompletion) ModelList

func (c *ChatCompletion) ModelList() []string

chat 支持的模型列表

func (*ChatCompletion) Stream

发送流式请求

type ChatCompletionMessage

type ChatCompletionMessage struct {
	Role         string        `json:"role"`                    // 角色,可选 "user", "assistant", "function"
	Content      string        `json:"content"`                 // 对话内容
	Name         string        `json:"name,omitempty"`          // message 作者
	FunctionCall *FunctionCall `json:"function_call,omitempty"` // 函数调用
}

表示对话内容的结构体

func ChatCompletionAssistantMessage

func ChatCompletionAssistantMessage(message string) ChatCompletionMessage

创建一个 Assistant 的消息

func ChatCompletionUserMessage

func ChatCompletionUserMessage(message string) ChatCompletionMessage

创建一个 User 的消息

type ChatCompletionRequest

type ChatCompletionRequest struct {
	BaseRequestBody `mapstructure:"-"`
	Messages        []ChatCompletionMessage `mapstructure:"messages"`                    // 聊天上下文信息
	Temperature     float64                 `mapstructure:"temperature,omitempty"`       // 较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定,范围 (0, 1.0],不能为0
	TopP            float64                 `mapstructure:"top_p,omitempty"`             // 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围 [0, 1.0]
	PenaltyScore    float64                 `mapstructure:"penalty_score,omitempty"`     // 通过对已生成的token增加惩罚,减少重复生成的现象。说明:值越大表示惩罚越大,取值范围:[1.0, 2.0]
	System          string                  `mapstructure:"system,omitempty"`            // 模型人设,主要用于人设设定
	Stop            []string                `mapstructure:"stop,omitempty"`              // 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成
	DisableSearch   bool                    `mapstructure:"disable_search,omitempty"`    // 是否强制关闭实时搜索功能
	EnableCitation  bool                    `mapstructure:"enable_citation,omitempty"`   // 是否开启上角标返回
	MaxOutputTokens int                     `mapstructure:"max_output_tokens,omitempty"` // 指定模型最大输出token数
	ResponseFormat  string                  `mapstructure:"response_format,omitempty"`   // 指定响应内容的格式
	UserID          string                  `mapstructure:"user_id,omitempty"`           // 表示最终用户的唯一标识符
	Functions       []Function              `mapstructure:"functions,omitempty"`         // 一个可触发函数的描述列表
	ToolChoice      *ToolChoice             `mapstructure:"tool_choice,omitempty"`       // 在函数调用场景下,提示大模型选择指定的函数
}

chat 模型的请求结构体

type Completion

type Completion struct {
	BaseModel
	// contains filtered or unexported fields
}

用于 Completion 模型请求的结构体

func NewCompletion

func NewCompletion(optionList ...Option) *Completion

创建一个 Completion 实例

completion := qianfan.NewCompletion()  // 默认使用 ERNIE-Bot-turbo 模型

// 可以通过 WithModel 指定模型
completion := qianfan.NewCompletion(
    qianfan.WithModel("ERNIE-Bot-4"),
    // 支持的模型可以通过 completion.ModelList() 获取
)
// 或者通过 WithEndpoint 指定 endpoint
completion := qianfan.NewCompletion(
   qianfan.WithEndpoint("your_custom_endpoint"),
)

func (*Completion) Do

发送请求

func (*Completion) ModelList

func (c *Completion) ModelList() []string

Completion 支持的模型列表

func (*Completion) Stream

发送流式请求

type CompletionRequest

type CompletionRequest struct {
	BaseRequestBody
	Prompt          string   `mapstructure:"prompt"`                      // 请求信息
	Temperature     float64  `mapstructure:"temperature,omitempty"`       // 较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定,范围 (0, 1.0],不能为0
	TopK            int      `mapstructure:"top_k,omitempty"`             // Top-K 采样参数,在每轮token生成时,保留k个概率最高的token作为候选
	TopP            float64  `mapstructure:"top_p,omitempty"`             // 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围 [0, 1.0]
	PenaltyScore    float64  `mapstructure:"penalty_score,omitempty"`     // 通过对已生成的token增加惩罚,减少重复生成的现象。说明:值越大表示惩罚越大,取值范围:[1.0, 2.0]
	System          string   `mapstructure:"system,omitempty"`            // 模型人设,主要用于人设设定
	Stop            []string `mapstructure:"stop,omitempty"`              // 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成
	DisableSearch   bool     `mapstructure:"disable_search,omitempty"`    // 是否强制关闭实时搜索功能
	EnableCitation  bool     `mapstructure:"enable_citation,omitempty"`   // 是否开启上角标返回
	MaxOutputTokens int      `mapstructure:"max_output_tokens,omitempty"` // 指定模型最大输出token数
	ResponseFormat  string   `mapstructure:"response_format,omitempty"`   // 指定响应内容的格式
	UserID          string   `mapstructure:"user_id,omitempty"`           // 表示最终用户的唯一标识符
}

Completion 模型请求的参数结构体,但并非每个模型都完整支持如下参数,具体是否支持以 API 文档为准

type Config

type Config struct {
	AK                            string  `mapstructure:"QIANFAN_AK"`
	SK                            string  `mapstructure:"QIANFAN_SK"`
	AccessKey                     string  `mapstructure:"QIANFAN_ACCESS_KEY"`
	SecretKey                     string  `mapstructure:"QIANFAN_SECRET_KEY"`
	BaseURL                       string  `mapstructure:"QIANFAN_BASE_URL"`
	IAMSignExpirationSeconds      int     `mapstructure:"QIANFAN_IAM_SIGN_EXPIRATION_SEC"`
	ConsoleBaseURL                string  `mapstructure:"QIANFAN_CONSOLE_BASE_URL"`
	AccessTokenRefreshMinInterval int     `mapstructure:"QIANFAN_ACCESS_TOKEN_REFRESH_MIN_INTERVAL"`
	LLMRetryCount                 int     `mapstructure:"QIANFAN_LLM_API_RETRY_COUNT"`
	LLMRetryTimeout               float32 `mapstructure:"QIANFAN_LLM_API_RETRY_TIMEOUT"`
	LLMRetryBackoffFactor         float32 `mapstructure:"QIANFAN_LLM_API_RETRY_BACKOFF_FACTOR"`
}

SDK 使用的全局配置,可以用 GetConfig() 获取

func GetConfig

func GetConfig() *Config

获取全局配置,可以通过如下方式修改配置 可以在代码中手动设置 `AccessKey` 和 `SecretKey`,具体如下:

qianfan.GetConfig().AccessKey = "your_access_key"
qianfan.GetConfig().SecretKey = "your_secret_key"

type CredentialNotFoundError

type CredentialNotFoundError struct {
}

鉴权所需信息不足,需确保 (AccessKey, SecretKey) 或 (AK, SK) 存在

func (*CredentialNotFoundError) Error

func (e *CredentialNotFoundError) Error() string

type Embedding

type Embedding struct {
	BaseModel
}

用于 Embedding 相关操作的结构体

func NewEmbedding

func NewEmbedding(optionList ...Option) *Embedding

创建 Embedding 实例

func (*Embedding) Do

发送 Embedding 请求

func (*Embedding) ModelList

func (c *Embedding) ModelList() []string

获取 Embedding 支持的模型列表

type EmbeddingData

type EmbeddingData struct {
	Object    string    `json:"object"`    // 固定值"embedding"
	Embedding []float64 `json:"embedding"` // embedding 内容
	Index     int       `json:"index"`     // 序号
}

具体的 Embedding 信息

type EmbeddingRequest

type EmbeddingRequest struct {
	BaseRequestBody
	Input  []string `mapstructure:"input"`             // 输入的文本列表
	UserID string   `mapstructure:"user_id,omitempty"` // 表示最终用户的唯一标识符
}

Embedding 请求

type EmbeddingResponse

type EmbeddingResponse struct {
	Id            string          `json:"id"`      // 请求的id
	Object        string          `json:"object"`  // 回包类型,固定值“embedding_list”
	Created       int             `json:"created"` // 创建时间
	Usage         ModelUsage      `json:"usage"`   // token统计信息
	Data          []EmbeddingData `json:"data"`    // embedding 数据
	ModelAPIError                 // API 错误信息
	// contains filtered or unexported fields
}

返回的 Embedding 数据

func (*EmbeddingResponse) SetResponse

func (r *EmbeddingResponse) SetResponse(Body []byte, RawResponse *http.Response)

设置回复中通用参数的字段

type Function

type Function struct {
	Name        string              `json:"name"`                // 函数名
	Description string              `json:"description"`         // 函数描述
	Parameters  any                 `json:"parameters"`          // 函数请求参数
	Responses   any                 `json:"responses,omitempty"` // 函数响应参数
	Examples    [][]FunctionExample `json:"examples,omitempty"`  // function调用的一些历史示例
}

表示函数的结构体

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name"`               // 触发的function名
	Arguments string `json:"arguments"`          // 请求参数
	Thoughts  string `json:"thoughts,omitempty"` // 模型思考过程
}

函数调用的结构体

type FunctionExample

type FunctionExample struct {
	Role         string        `json:"role"`                    // 角色,可选 "user", "assistant", "function"
	Content      string        `json:"content"`                 // 对话内容
	Name         string        `json:"name,omitempty"`          // message 作者
	FunctionCall *FunctionCall `json:"function_call,omitempty"` // 函数调用
}

function调用的示例

type InternalError

type InternalError struct {
	Msg string
}

SDK 内部错误,若遇到请联系我们

func (*InternalError) Error

func (e *InternalError) Error() string

type InvalidParamError

type InvalidParamError struct {
	Msg string
}

参数非法

func (*InvalidParamError) Error

func (e *InvalidParamError) Error() string

type ModelAPIError

type ModelAPIError struct {
	ErrorCode int    `json:"error_code"` // 错误码
	ErrorMsg  string `json:"error_msg"`  // 错误消息
}

API 错误信息

func (*ModelAPIError) ClearError

func (e *ModelAPIError) ClearError()

清除错误码

func (*ModelAPIError) GetError

func (e *ModelAPIError) GetError() (int, string)

获取错误码和错误信息

func (*ModelAPIError) GetErrorCode

func (e *ModelAPIError) GetErrorCode() string

获取错误码

type ModelAPIResponse

type ModelAPIResponse interface {
	GetError() (int, string)
	ClearError()
}

type ModelNotSupportedError

type ModelNotSupportedError struct {
	Model string
}

模型不被支持,请使用 `ModelList()` 获取支持的模型列表

func (*ModelNotSupportedError) Error

func (e *ModelNotSupportedError) Error() string

type ModelResponse

type ModelResponse struct {
	Id               string        `json:"id"`                 // 本轮对话的id
	Object           string        `json:"object"`             // 回包类型
	Created          int           `json:"created"`            // 时间戳
	SentenceId       int           `json:"sentence_id"`        // 表示当前子句的序号。只有在流式接口模式下会返回该字段
	IsEnd            bool          `json:"is_end"`             // 表示当前子句是否是最后一句。只有在流式接口模式下会返回该字段
	IsTruncated      bool          `json:"is_truncated"`       // 当前生成的结果是否被截断
	Result           string        `json:"result"`             // 对话返回结果
	NeedClearHistory bool          `json:"need_clear_history"` // 表示用户输入是否存在安全风险,是否关闭当前会话,清理历史会话信息
	Usage            ModelUsage    `json:"usage"`              // token统计信息
	FunctionCall     *FunctionCall `json:"function_call"`      // 由模型生成的函数调用,包含函数名称,和调用参数
	BanRound         int           `json:"ban_round"`          // 当need_clear_history为true时,此字段会告知第几轮对话有敏感信息,如果是当前问题,ban_round=-1
	SearchInfo       *SearchInfo   `json:"search_info"`        // 搜索数据,当请求参数enable_citation为true并且触发搜索时,会返回该字段
	ModelAPIError                  // API 错误信息
	// contains filtered or unexported fields
}

模型响应的结果

func (*ModelResponse) SetResponse

func (r *ModelResponse) SetResponse(Body []byte, RawResponse *http.Response)

设置回复中通用参数的字段

type ModelResponseStream

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

用于获取ModelResponse流式结果的结构体

func (ModelResponseStream) Close

func (si ModelResponseStream) Close()

关闭流

func (*ModelResponseStream) Recv

func (s *ModelResponseStream) Recv() (*ModelResponse, error)

获取ModelResponse流式结果

type ModelUsage

type ModelUsage struct {
	PromptTokens     int `json:"prompt_tokens"`     // 问题tokens数
	CompletionTokens int `json:"completion_tokens"` // 回答tokens数
	TotalTokens      int `json:"total_tokens"`      // tokens总数
}

使用量信息

type Option

type Option func(*Options)

func WithEndpoint

func WithEndpoint(endpoint string) Option

用于模型类对象设置使用的 endpoint

func WithLLMRetryBackoffFactor

func WithLLMRetryBackoffFactor(factor float32) Option

设置重试退避因子

func WithLLMRetryCount

func WithLLMRetryCount(count int) Option

设置重试次数

func WithLLMRetryTimeout

func WithLLMRetryTimeout(timeout float32) Option

设置重试超时时间

func WithModel

func WithModel(model string) Option

用于模型类对象设置使用的模型

type Options

type Options struct {
	Model                 *string
	Endpoint              *string
	LLMRetryCount         int
	LLMRetryTimeout       float32
	LLMRetryBackoffFactor float32
}

type QfRequest

type QfRequest struct {
	Type    string                 // 请求类型,用于区分是模型的请求 `modelRequest` 还是管控类请求 `consoleRequest`
	Method  string                 // HTTP 方法
	URL     string                 // 请求的完整地址
	Headers map[string]string      // HTTP 请求头
	Params  map[string]string      // HTTP 请求参数
	Body    map[string]interface{} // HTTP 请求体
}

SDK 内部表示请求的类

type QfResponse

type QfResponse interface {
	SetResponse(Body []byte, RawResponse *http.Response)
	GetErrorCode() string
}

所有回复类型需实现的接口

type RequestBody

type RequestBody interface {
	SetExtra(m map[string]interface{})
	GetExtra() map[string]interface{}
}

所有请求类型需实现的接口

定义了提供额外参数的接口

type Requestor

type Requestor struct {
	Options *Options
	// contains filtered or unexported fields
}

请求器,负责 SDK 中所有请求的发送,是所有对外暴露对象的基类

type SearchInfo

type SearchInfo struct {
	SearchResults []SearchResult `json:"search_results"` // 搜索结果列表
}

搜索结果列表

type SearchResult

type SearchResult struct {
	Index int    `json:"index"` // 序号
	URL   string `json:"url"`   // 搜索结果URL
	Title string `json:"title"` // 搜索结果标题
}

搜索结果

type ToolChoice

type ToolChoice struct {
	Type     string    `json:"type"`     // 指定工具类型
	Function *Function `json:"function"` // 指定要使用的函数
	Name     string    `json:"name"`     // 指定要使用的函数名
}

可选的工具

Jump to

Keyboard shortcuts

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