qianfan

package module
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 24 Imported by: 6

Documentation

Overview

百度千帆大模型平台 Go SDK

简介

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

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

文档:https://github.com/baidubce/bce-qianfan-sdk/blob/main/go/README.md 示例代码:https://github.com/baidubce/bce-qianfan-sdk/tree/main/go/examples

Index

Constants

View Source
const (
	DefaultChatCompletionModel = "ERNIE-Lite-8K"
	DefaultCompletionModel     = "ERNIE-Lite-8K"
	DefaultEmbeddingModel      = "Embedding-V1"
	DefaultText2ImageModel     = "Stable-Diffusion-XL"
)

默认使用的模型

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
	RPMLimitReachedErrCode            = 336501
	TPMLimitReachedErrCode            = 336502

	ConsoleInternalErrorErrCode = 500000
)

API 错误码

View Source
const (
	TokenizerModeLocal  = TokenizerMode("local")
	TokenizerModeRemote = TokenizerMode("remote")
)

TokenizerMode 枚举

View Source
const Version = "v0.0.14"

SDK 版本

Variables

View Source
var ChatModelEndpoint = map[string]string{
	"ERNIE-4.0-Turbo-8K":            "/chat/ernie-4.0-turbo-8k",
	"ERNIE-4.0-8K-Latest":           "/chat/ernie-4.0-8k-latest",
	"ERNIE-4.0-8K-0613":             "/chat/ernie-4.0-8k-0613",
	"ERNIE-3.5-8K-0613":             "/chat/ernie-3.5-8k-0613",
	"ERNIE-Bot-turbo":               "/chat/eb-instant",
	"ERNIE-Lite-8K-0922":            "/chat/eb-instant",
	"ERNIE-Lite-8K":                 "/chat/ernie-lite-8k",
	"ERNIE-Lite-8K-0308":            "/chat/ernie-lite-8k",
	"ERNIE-Lite-AppBuilder-8K-0614": "/chat/ai_apaas_lite",
	"ERNIE-Lite-Pro-8K":             "/chat/ernie-lite-pro-8k",
	"ERNIE-Lite-V":                  "/chat/ernie-lite-v",
	"ERNIE-3.5-8K":                  "/chat/completions",
	"ERNIE-Bot":                     "/chat/completions",
	"ERNIE-4.0-8K":                  "/chat/completions_pro",
	"ERNIE-4.0-8K-Preview":          "/chat/ernie-4.0-8k-preview",
	"ERNIE-4.0-8K-Preview-0518":     "/chat/completions_adv_pro",
	"ERNIE-4.0-8K-0329":             "/chat/ernie-4.0-8k-0329",
	"ERNIE-4.0-8K-0104":             "/chat/ernie-4.0-8k-0104",
	"ERNIE-Bot-4":                   "/chat/completions_pro",
	"ERNIE-Bot-8k":                  "/chat/ernie_bot_8k",
	"ERNIE-3.5-128K":                "/chat/ernie-3.5-128k",
	"ERNIE-3.5-8K-preview":          "/chat/ernie-3.5-8k-preview",
	"ERNIE-3.5-8K-0329":             "/chat/ernie-3.5-8k-0329",
	"ERNIE-3.5-4K-0205":             "/chat/ernie-3.5-4k-0205",
	"ERNIE-3.5-8K-0205":             "/chat/ernie-3.5-8k-0205",
	"ERNIE-3.5-8K-0701":             "/chat/ernie-3.5-8k-0701",
	"ERNIE-3.5-8K-1222":             "/chat/ernie-3.5-8k-1222",
	"ERNIE Speed":                   "/chat/ernie_speed",
	"ERNIE-Speed":                   "/chat/ernie_speed",
	"ERNIE-Speed-8K":                "/chat/ernie_speed",
	"ERNIE-Speed-128K":              "/chat/ernie-speed-128k",
	"ERNIE Speed-AppBuilder":        "/chat/ai_apaas",
	"ERNIE-Speed-Pro-8K":            "/chat/ernie-speed-pro-8k",
	"ERNIE-Speed-Pro-128K":          "/chat/ernie-speed-pro-128k",
	"ERNIE-Tiny-8K":                 "/chat/ernie-tiny-8k",
	"ERNIE-Function-8K":             "/chat/ernie-func-8k",
	"ERNIE-Character-8K":            "/chat/ernie-char-8k",
	"ERNIE-Character-Fiction-8K":    "/chat/ernie-char-fiction-8k",
	"ERNIE-Bot-turbo-AI":            "/chat/ai_apaas",
	"ERNIE-Novel-8K":                "/chat/ernie-novel-8k",
	"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-Chinese-Llama-2-7B":    "/chat/qianfan_chinese_llama_2_7b",
	"Qianfan-Chinese-Llama-2-13B":   "/chat/qianfan_chinese_llama_2_13b",
	"Qianfan-Chinese-Llama-2-70B":   "/chat/qianfan_chinese_llama_2_70b",
	"Meta-Llama-3-8B":               "/chat/llama_3_8b",
	"Meta-Llama-3-70B":              "/chat/llama_3_70b",
	"Qianfan-BLOOMZ-7B-compressed":  "/chat/qianfan_bloomz_7b_compressed",
	"ChatGLM2-6B-32K":               "/chat/chatglm2_6b_32k",
	"AquilaChat-7B":                 "/chat/aquilachat_7b",
	"XuanYuan-70B-Chat-4bit":        "/chat/xuanyuan_70b_chat",
	"ChatLaw":                       "/chat/chatlaw",
	"Yi-34B-Chat":                   "/chat/yi_34b_chat",
	"Mixtral-8x7B-Instruct":         "/chat/mixtral_8x7b_instruct",
	"Gemma-7B-it":                   "/chat/gemma_7b_it",
	"Qianfan-Dynamic-8K":            "/chat/qianfan-dynamic-8k",
}

内置 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

View Source
var (
	ErrInternal = errors.New("internal error")
)

ErrInternal 定义错误类型

View Source
var Text2ImageEndpoint = map[string]string{
	"Stable-Diffusion-XL": "/text2image/sd_xl",
}

内置 Text2Image 模型的 endpoint

Functions

func GetBearerToken added in v0.0.13

func GetBearerToken() (string, error)

func SetLogLevel added in v0.0.10

func SetLogLevel(level logrus.Level)

Types

type APIError added in v0.0.2

type APIError struct {
	Code int
	Msg  string
}

API 返回错误

func (*APIError) Error added in v0.0.2

func (e *APIError) Error() string

type AccessTokenRequest added in v0.0.2

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

type AccessTokenResponse added in v0.0.2

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 added in v0.0.2

func (r *AccessTokenResponse) GetErrorCode() string

func (*AccessTokenResponse) GetResponse added in v0.0.4

func (r *AccessTokenResponse) GetResponse() *http.Response

func (*AccessTokenResponse) SetResponse added in v0.0.2

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

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

type AuthManager added in v0.0.2

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

func GetAuthManager added in v0.0.2

func GetAuthManager() *AuthManager

func (*AuthManager) GetAccessToken added in v0.0.2

func (m *AuthManager) GetAccessToken(ctx context.Context, ak, sk string) (string, error)

func (*AuthManager) GetAccessTokenWithRefresh added in v0.0.2

func (m *AuthManager) GetAccessTokenWithRefresh(ctx context.Context, ak, sk string) (string, error)

type BaseModel

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

模型相关的结构体基类

func NewBaseModel added in v0.0.12

func NewBaseModel(options ...Option) *BaseModel

func (*BaseModel) Do added in v0.0.12

func (m *BaseModel) Do(ctx context.Context, request *QfRequest) (*RawResponse, error)

func (*BaseModel) Stream added in v0.0.12

func (m *BaseModel) Stream(ctx context.Context, request *QfRequest) (*RawModelResponseStream, error)

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 BearerToken added in v0.0.14

type BearerToken struct {
	ExpireTime     time.Time
	ExpireTimeBuff time.Duration
	// contains filtered or unexported fields
}

type BearerTokenManager added in v0.0.14

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

func GetBearerTokenManager added in v0.0.14

func GetBearerTokenManager() *BearerTokenManager

func (*BearerTokenManager) GetAccessTokenWithRefresh added in v0.0.14

func (m *BearerTokenManager) GetAccessTokenWithRefresh() (string, error)

type ChatCompletion

type ChatCompletion struct {
	BaseModel
}

用于 chat 类型模型的结构体

func NewChatCompletion

func NewChatCompletion(optionList ...Option) *ChatCompletion

创建一个 ChatCompletion 对象

chat := qianfan.NewChatCompletion() // 使用默认模型

可以通过 WithModel 指定模型 chat := qianfan.NewChatCompletion(

qianfan.WithModel("ERNIE-4.0-8K"),  // 支持的模型可以通过 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 ChatCompletionV2 added in v0.0.13

type ChatCompletionV2 struct {
	Model      string `mapstructure:"model"` // 模型ID
	*Requestor        // Requstor 作为基类
}

用于 chat v2 类型模型的结构体

func NewChatCompletionV2 added in v0.0.13

func NewChatCompletionV2(optionList ...Option) *ChatCompletionV2

创建一个 ChatCompletion 对象

chat := qianfan.NewChatCompletion() // 使用默认模型

可以通过 WithModel 指定模型 chat := qianfan.NewChatCompletion(

qianfan.WithModel("ERNIE-4.0-8K"),  // 支持的模型可以通过 chat.ModelList() 获取

) 或者通过 WithEndpoint 指定 endpoint chat := qianfan.NewChatCompletion(

qianfan.WithEndpoint("your_custom_endpoint"),

)

func (*ChatCompletionV2) Do added in v0.0.13

发送 chat 请求

func (*ChatCompletionV2) Stream added in v0.0.13

发送流式请求

type ChatCompletionV2Choice added in v0.0.13

type ChatCompletionV2Choice struct {
	Index        int                     `mapstructure:"index"`         // 生成结果索引
	Message      ChatCompletionV2Message `mapstructure:"message"`       // 生成结果
	Delta        ChatCompletionV2Delta   `mapstructure:"delta"`         // 生成结果
	FinishReason string                  `mapstructure:"finish_reason"` // 生成结果的分数
	Flag         int                     `mapstructure:"flag"`          // 生成结果的标志
	BanRound     int                     `mapstructure:"ban_round"`     // 生成结果
}

type ChatCompletionV2Delta added in v0.0.13

type ChatCompletionV2Delta struct {
	Content   string     `mapstructure:"content"`              // 生成结果
	ToolCalls []ToolCall `mapstructure:"tool_calls,omitempty"` // 函数调用
}

type ChatCompletionV2Error added in v0.0.13

type ChatCompletionV2Error struct {
	Code    string `mapstructure:"code"`
	Message string `mapstructure:"message"`
	Type    string `mapstructure:"type"`
}

type ChatCompletionV2Message added in v0.0.14

type ChatCompletionV2Message struct {
	Role       string     `mapstructure:"role" json:"role,omitempty"`
	Content    string     `mapstructure:"content,omitempty" json:"content,omitempty"`
	Name       string     `mapstructure:"name" json:"name,omitempty"`
	ToolCalls  []ToolCall `mapstructure:"tool_calls,omitempty" json:"tool_calls,omitempty"` // 函数调用
	ToolCallId string     `mapstructure:"tool_call_id,omitempty" json:"tool_call_id,omitempty"`
}

type ChatCompletionV2Request added in v0.0.13

type ChatCompletionV2Request struct {
	BaseRequestBody     `mapstructure:"-"`
	Model               string                    `mapstructure:"model"`                           // 模型ID
	Messages            []ChatCompletionV2Message `mapstructure:"messages"`                        // 聊天上下文信息
	StreamOptions       *StreamOptions            `mapstructure:"stream_options,omitempty"`        // 流式选项
	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]
	MaxCompletionTokens int                       `mapstructure:"max_completion_tokens,omitempty"` // 指定模型最大输出token数
	Seed                int                       `mapstructure:"seed,omitempty"`                  // 随机种子
	Stop                []string                  `mapstructure:"stop,omitempty"`                  // 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成
	User                string                    `mapstructure:"user,omitempty"`                  // 表示最终用户的唯一标识符
	FrequencyPenalty    float64                   `mapstructure:"frequency_penalty,omitempty"`     // 指定频率惩罚,用于控制生成文本的重复程度。取值范围 [0.0,
	PresencePenalty     float64                   `mapstructure:"presence_penalty,omitempty"`      // 指定存在惩罚,用于控制生成文本的重复程度。取值范围 [0.0         int                     `mapstructure:"num_samples,omitempty"`      // 指定采样次数,取值范围 [1, 20]
	Tools               []Tool                    `mapstructure:"tools,omitempty"`
	ToolChoice          any                       `mapstructure:"tool_choice,omitempty"`
	ParallelToolCalls   bool                      `mapstructure:"parallel_tool_calls,omitempty"` // 是否并行调用工具
	ResponseFormat      *ResponseFormat           `mapstructure:"response_format,omitempty"`
}

chat 模型的请求结构体

type ChatCompletionV2Response added in v0.0.13

type ChatCompletionV2Response struct {
	ID      string                   `mapstructure:"id"`      // 请求ID
	Object  string                   `mapstructure:"object"`  // 对象类型
	Created int64                    `mapstructure:"created"` // 创建时间
	Model   string                   `mapstructure:"model"`   // 模型ID
	Choices []ChatCompletionV2Choice `mapstructure:"choices"` // 生成结果
	Usage   *ModelUsage              `mapstructure:"usage"`   // 请求信息
	Error   *ChatCompletionV2Error   `mapstructure:"error"`   // 错误信息
	// contains filtered or unexported fields
}

func (*ChatCompletionV2Response) GetErrorCode added in v0.0.13

func (c *ChatCompletionV2Response) GetErrorCode() string

func (*ChatCompletionV2Response) GetResponse added in v0.0.13

func (r *ChatCompletionV2Response) GetResponse() *http.Response

func (*ChatCompletionV2Response) SetResponse added in v0.0.13

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

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

type ChatCompletionV2ResponseStream added in v0.0.13

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

func (ChatCompletionV2ResponseStream) Close added in v0.0.13

func (si ChatCompletionV2ResponseStream) Close()

关闭流

func (ChatCompletionV2ResponseStream) Recv added in v0.0.13

func (si ChatCompletionV2ResponseStream) Recv(resp QfResponse) error

接受流中的响应,并将结果解析至 resp

type Completion

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

用于 Completion 模型请求的结构体

func NewCompletion

func NewCompletion(optionList ...Option) *Completion

创建一个 Completion 实例

completion := qianfan.NewCompletion()  // 默认使用 ERNIE-Lite-8K 模型

// 可以通过 WithModel 指定模型
completion := qianfan.NewCompletion(
    qianfan.WithModel("ERNIE-4.0-8K"),
    // 支持的模型可以通过 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 `mapstructure:"-"`
	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"`
	AccessToken                   string  `mapstructure:"QIANFAN_ACCESS_TOKEN"`
	BearerToken                   string  `mapstructure:"QIANFAN_BEARER_TOKEN"`
	BaseURL                       string  `mapstructure:"QIANFAN_BASE_URL"`
	IAMSignExpirationSeconds      int     `mapstructure:"QIANFAN_IAM_SIGN_EXPIRATION_SEC"`
	BearerTokenExpirationSeconds  int     `mapstructure:"QIANFAN_BEARER_TOKEN_EXPIRATION_SEC"`
	BearerTokenRefreshAdvance     int     `mapstructure:"QIANFAN_BEARER_TOKEN_REFRESH_ADVANCE"`
	ConsoleBaseURL                string  `mapstructure:"QIANFAN_CONSOLE_BASE_URL"`
	IAMBaseURL                    string  `mapstructure:"QIANFAN_IAM_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"`
	InferResourceRefreshInterval  int     `mapstructure:"QIANFAN_INFER_RESOURCE_REFRESH_MIN_INTERVAL"`
	RetryErrCodes                 []int
}

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

func GetConfig

func GetConfig() *Config

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

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

type ConsoleAPIError added in v0.0.4

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

func (*ConsoleAPIError) GetError added in v0.0.4

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

获取错误码和错误信息

func (*ConsoleAPIError) GetErrorCode added in v0.0.4

func (e *ConsoleAPIError) GetErrorCode() string

获取错误码

type ConsoleAPIResponse added in v0.0.4

type ConsoleAPIResponse interface {
	GetError() (int, string)
}

type ConsoleAction added in v0.0.10

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

func NewConsoleAction added in v0.0.10

func NewConsoleAction(optionList ...Option) *ConsoleAction

func (*ConsoleAction) Call added in v0.0.10

func (ca *ConsoleAction) Call(ctx context.Context, route string, action string, params map[string]interface{}) (*ConsoleResponse, error)

type ConsoleResponse added in v0.0.4

type ConsoleResponse struct {
	LogID   string `json:"log_id"`
	Success bool   `json:"success"`
	ConsoleAPIError
	// contains filtered or unexported fields
}

func (*ConsoleResponse) GetResponse added in v0.0.4

func (r *ConsoleResponse) GetResponse() *http.Response

func (*ConsoleResponse) SetResponse added in v0.0.4

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

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

type CredentialNotFoundError added in v0.0.2

type CredentialNotFoundError struct {
}

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

func (*CredentialNotFoundError) Error added in v0.0.2

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 `mapstructure:"-"`
	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) GetResponse added in v0.0.4

func (r *EmbeddingResponse) GetResponse() *http.Response

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 FunctionCallV2 added in v0.0.14

type FunctionCallV2 struct {
	Name      string `mapstructure:"name,omitempty" json:"name,omitempty"`
	Arguments string `mapstructure:"arguments,omitempty" json:"arguments,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 FunctionV2 added in v0.0.14

type FunctionV2 struct {
	Name        string `mapstructure:"name" json:"name,omitempty"`
	Description string `mapstructure:"description" json:"description,omitempty"`
	Parameters  any    `mapstructure:"parameters" json:"parameters,omitempty"`
}

type IAMBearerTokenResponse added in v0.0.13

type IAMBearerTokenResponse struct {
	UserID     string `json:"userId"`
	Token      string `json:"token"`
	Status     string `json:"status"`
	CreateTime string `json:"createTime"`
	ExpireTime string `json:"expireTime"`
	// contains filtered or unexported fields
}

func (*IAMBearerTokenResponse) GetErrorCode added in v0.0.13

func (r *IAMBearerTokenResponse) GetErrorCode() string

func (*IAMBearerTokenResponse) GetResponse added in v0.0.13

func (r *IAMBearerTokenResponse) GetResponse() *http.Response

func (*IAMBearerTokenResponse) SetResponse added in v0.0.13

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

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

type IAMError added in v0.0.4

type IAMError struct {
	Code string
	Msg  string
}

IAM 错误

func (*IAMError) Error added in v0.0.4

func (e *IAMError) Error() string

type InternalError added in v0.0.2

type InternalError struct {
	Msg string
}

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

func (*InternalError) Error added in v0.0.2

func (e *InternalError) Error() string

type InvalidParamError added in v0.0.2

type InvalidParamError struct {
	Msg string
}

参数非法

func (*InvalidParamError) Error added in v0.0.2

func (e *InvalidParamError) Error() string

type ModelAPIError

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

API 错误信息

func (*ModelAPIError) ClearError added in v0.0.2

func (e *ModelAPIError) ClearError()

清除错误码

func (*ModelAPIError) GetError

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

获取错误码和错误信息

func (*ModelAPIError) GetErrorCode added in v0.0.2

func (e *ModelAPIError) GetErrorCode() string

获取错误码

type ModelAPIResponse

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

type ModelNotSupportedError added in v0.0.2

type ModelNotSupportedError struct {
	Model string
}

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

func (*ModelNotSupportedError) Error added in v0.0.2

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) GetResponse added in v0.0.4

func (r *ModelResponse) GetResponse() *http.Response

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 WithContext added in v0.0.5

func WithContext(ctx context.Context) Option

设置初始化时的 Context

func WithEndpoint

func WithEndpoint(endpoint string) Option

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

func WithLLMRetryBackoffFactor added in v0.0.2

func WithLLMRetryBackoffFactor(factor float32) Option

设置重试退避因子

func WithLLMRetryCount added in v0.0.2

func WithLLMRetryCount(count int) Option

设置重试次数

func WithLLMRetryTimeout added in v0.0.2

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
	Context               context.Context
}

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 内部表示请求的类

func NewBearerTokenRequest added in v0.0.13

func NewBearerTokenRequest(method string, url string, body RequestBody) (*QfRequest, error)

创建一个使用Bearer Token鉴权的 Request

func NewConsoleRequest added in v0.0.12

func NewConsoleRequest(method string, url string, body RequestBody) (*QfRequest, error)

创建一个用于管控类请求的 Request

func NewIAMBearerTokenRequest added in v0.0.13

func NewIAMBearerTokenRequest(method string, url string, body RequestBody) (*QfRequest, error)

创建一个使用Bearer Token鉴权的 Request

func NewModelRequest added in v0.0.12

func NewModelRequest(method string, url string, body RequestBody) (*QfRequest, error)

创建一个用于模型类请求的 Request

type QfResponse

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

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

type RawModelResponseStream added in v0.0.12

type RawModelResponseStream struct {
	*ModelResponseStream
}

func (RawModelResponseStream) Close added in v0.0.12

func (si RawModelResponseStream) Close()

关闭流

func (*RawModelResponseStream) Recv added in v0.0.12

type RawRequest added in v0.0.12

type RawRequest map[string]any

func (RawRequest) GetExtra added in v0.0.12

func (r RawRequest) GetExtra() map[string]any

func (RawRequest) SetExtra added in v0.0.12

func (r RawRequest) SetExtra(extra map[string]any)

type RawResponse added in v0.0.12

type RawResponse struct {
	ModelAPIError `json:",omitempty"`
	// contains filtered or unexported fields
}

func (*RawResponse) GetResponse added in v0.0.12

func (r *RawResponse) GetResponse() *http.Response

func (*RawResponse) SetResponse added in v0.0.12

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

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

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 ResponseFormat added in v0.0.14

type ResponseFormat struct {
	FormatType string `mapstructure:"type" json:"type,omitempty"`
	JsonSchema any    `mapstructure:"json_schema" json:"json_schema,omitempty"`
}

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 Service added in v0.0.4

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

func NewService added in v0.0.4

func NewService(optionList ...Option) *Service

func (*Service) List added in v0.0.4

func (service *Service) List(ctx context.Context, request *ServiceListRequest) (*ServiceListResponse, error)

type ServiceListItem added in v0.0.4

type ServiceListItem struct {
	ServiceID    string                   `json:"serviceId"`
	ServiceUUID  string                   `json:"serviceUuid"`
	Name         string                   `json:"name"`
	URL          string                   `json:"url"`
	APIType      string                   `json:"apiType"`
	ChargeStatus string                   `json:"chargeStatus"`
	VersionList  []ServiceListItemVersion `json:"versionList"`
}

type ServiceListItemVersion added in v0.0.4

type ServiceListItemVersion struct {
	AIModelID        string `json:"aiModelId,omitempty"`
	AIModelVersionID string `json:"aiModelVersionId,omitempty"`
	TrainType        string `json:"trainType"`
	ServiceStatus    string `json:"serviceStatus"`
}

type ServiceListRequest added in v0.0.4

type ServiceListRequest struct {
	BaseRequestBody `mapstructure:"-"`
	APITypeFilter   *[]string `mapstructure:"apiTypeFilter,omitempty"`
}

type ServiceListResponse added in v0.0.4

type ServiceListResponse struct {
	Result ServiceListResponseResult `json:"result"`
	ConsoleResponse
}

func (*ServiceListResponse) GetResponse added in v0.0.4

func (r *ServiceListResponse) GetResponse() *http.Response

func (*ServiceListResponse) SetResponse added in v0.0.4

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

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

type ServiceListResponseResult added in v0.0.4

type ServiceListResponseResult struct {
	Common []ServiceListItem `json:"common"`
	Custom []ServiceListItem `json:"custom"`
}

type StreamOptions added in v0.0.14

type StreamOptions struct {
	IncludeUsage bool `mapstructure:"include_usage,omitempty" json:"include_usage,omitempty"` //流式响应是否输出usage
}

type Text2Image added in v0.0.5

type Text2Image struct {
	BaseModel
}

用于 Text2Image 相关操作的结构体

func NewText2Image added in v0.0.5

func NewText2Image(optionList ...Option) *Text2Image

创建 Text2Image 实例

func (*Text2Image) Do added in v0.0.5

发送 Text2Image 请求

func (*Text2Image) ModelList added in v0.0.5

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

获取 Text2Image 支持的模型列表

type Text2ImageData added in v0.0.5

type Text2ImageData struct {
	Object      string `json:"object"`    // 固定值"image"
	Base64Image string `json:"b64_image"` // 图片base64编码内容
	Index       int    `json:"index"`     // 序号
}

具体的 Text2Image 信息

type Text2ImageRequest added in v0.0.5

type Text2ImageRequest struct {
	BaseRequestBody `mapstructure:"-"`
	Prompt          string  `mapstructure:"prompt"`                    // 输入的提示词
	NegativePrompt  string  `mapstructure:"negative_prompt,omitempty"` // 反向提示词
	Size            string  `mapstructure:"size,omitempty"`            // 图片尺寸
	N               int     `mapstructure:"n,omitempty"`               // 生成图片的个数
	Steps           int     `mapstructure:"steps,omitempty"`           // 迭代论述
	SamplerIndex    string  `mapstructure:"sampler_index,omitempty"`   // 采样方式
	Seed            int     `mapstructure:"seed,omitempty"`            // 随机种子
	CfgScale        float64 `mapstructure:"cfg_scale,omitempty"`       // 提示词相关性
	Style           string  `mapstructure:"style,omitempty"`           // 风格
	UserID          string  `mapstructure:"user_id,omitempty"`         // 用户ID
}

Text2Image 请求

type Text2ImageResponse added in v0.0.5

type Text2ImageResponse struct {
	Id            string           `json:"id"`      // 请求的id
	Object        string           `json:"object"`  // 回包类型,固定值“image”
	Created       int              `json:"created"` // 创建时间
	Usage         ModelUsage       `json:"usage"`   // 生成图片结果
	Data          []Text2ImageData `json:"data"`    // Text2Image 数据
	ModelAPIError                  // API 错误信息
	// contains filtered or unexported fields
}

返回的 Text2Image 数据

func (*Text2ImageResponse) GetResponse added in v0.0.5

func (r *Text2ImageResponse) GetResponse() *http.Response

func (*Text2ImageResponse) SetResponse added in v0.0.5

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

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

type Tokenizer added in v0.0.7

type Tokenizer struct {
	BaseModel
}

Tokenizer 结构体

func NewTokenizer added in v0.0.7

func NewTokenizer() *Tokenizer

NewTokenizer 创建 Tokenizer 实例

func (*Tokenizer) CountTokens added in v0.0.7

func (t *Tokenizer) CountTokens(text string, mode TokenizerMode, model string, additionalArguments map[string]interface{}) (int, error)

CountTokens 计算给定文本中的 token 数量

type TokenizerMode added in v0.0.7

type TokenizerMode string

type Tool added in v0.0.14

type Tool struct {
	ToolType string     `mapstructure:"type" json:"type,omitempty"`
	Function FunctionV2 `mapstructure:"function" json:"function,omitempty"`
}

type ToolCall added in v0.0.14

type ToolCall struct {
	Id       string         `mapstructure:"id" json:"id,omitempty"`
	ToolType string         `mapstructure:"type" json:"type,omitempty"`
	Function FunctionCallV2 `mapstructure:"function" json:"function,omitempty"`
}

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