ai_sdk

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2024 License: AGPL-3.0 Imports: 13 Imported by: 2

README

go-ai-sdk

go-ai-sdk 是一个使用 Go 语言编写的 SDK,旨在管理基于 AI 的多会话交互,如聊天机器人或自动化客服系统。该包支持并发会话管理、消息历史处理和基于 AI 的响应生成。

功能特点

  • 多会话管理:创建并管理多个具有唯一会话 ID 的聊天会话。

  • 消息历史处理:存储和管理聊天历史,并支持可配置的历史记录限制。

  • AI 响应生成:与 AI 客户端接口,基于聊天历史生成智能响应。

安装

在安装 go-ai-sdk 包之前,请确保你已经安装了 Go 1.21。然后运行以下命令来安装该包:

go get github.com/Clov614/go-ai-sdk

使用方法

基本示例
package main

import (
	"fmt"
	ai_sdk "github.com/Clov614/go-ai-sdk"
)

func main() {
	sessionID := "example-session"
	content := "你好,你能帮我做什么?"

	// 获取一个会话或创建一个新会话
	session := ai_sdk.DefaultSession.GetSession(sessionID)

	// 发起对话
	response, err := session.Talk(content)
	if err != nil {
		fmt.Printf("错误: %v\n", err)
		return
	}

	fmt.Println("AI 响应:", response)
}
使用插件扩展 AI 功能

以下代码展示了如何使用函数注册器将自定义功能(如查询天气)注册到 SDK 中:

package ai

import (
	"encoding/json"
	ai_sdk "github.com/Clov614/go-ai-sdk"
	"github.com/Clov614/go-ai-sdk/example_func_call/weather"
	"github.com/Clov614/go-ai-sdk/global"
	"wechat-demo/rikkabot/config"
	"wechat-demo/rikkabot/logging"
)

type weatherCfg struct {
	Key string `json:"key"`
}

func init() {
	// 注册对话插件
	cfg := config.GetConfig()
	wCfgInterface, ok := cfg.GetCustomPluginCfg("weather_ai")
	if !ok {
		cfg.SetCustomPluginCfg("weather_ai", weatherCfg{Key: ""})
		_ = cfg.Update() // 更新设置
		logging.Fatal("weather_ai plugin config loaded empty. Please write the weather API key in config.yaml", 12)
	}
	bytes, _ := json.Marshal(wCfgInterface)
	var wcfg weatherCfg
	json.Unmarshal(bytes, &wcfg)
	w := weather.NewWeather(wcfg.Key)
	funcCallInfo := ai_sdk.FuncCallInfo{
		Function: ai_sdk.Function{
			Name:        "get_weather_by_city",
			Description: "根据地址获取城市代码 cityAddress: 城市地址,如: 泉州市永春县 isMultiDay: 是否获取多日天气",
			Parameters: ai_sdk.FunctionParameter{
				Type: global.ObjType,
				Properties: ai_sdk.Properties{
					"city_addr": ai_sdk.Property{
						Type:        global.StringType,
						Description: "地址,如:国家,城市,县、区地址",
					},
					"is_multi": ai_sdk.Property{
						Type:        global.BoolType,
						Description: "是否获取多日天气",
					},
				},
				Required: []string{"city_addr", "is_multi"},
			},
			Strict: false,
		},
		CallFunc: w,
	}
	ai_sdk.FuncRegister.Register(&funcCallInfo, []string{"天气", "weather"})
}

在上述代码中,关键词如“天气”或“weather”会自动触发工具函数调用,为 AI 提供额外的能力。

配置

该项目使用配置文件来管理各种设置,包括会话超时时间和历史记录长度。你可以在 config.yaml 文件中自定义这些设置:

# 默认: application/json
content_type: application/json
# 使用的模型ID 默认: gpt-4o-mini
model: gpt-4o-mini
# 请求节点 默认: /v1/chat/completions
end_point: /v1/chat/completions
# API 配置列表
configs:
  - # api地址 默认: https://api.openai.com/v1/chat/completions
    api_url: https://api.openai.com/v1/chat/completions
    # OPEN-API-KEY api密钥列表 (必填)
    authorization_list:
      - sk-xxxxxx
      - sk-xxxxxx
# 请求超时时间,单位秒,默认 10s
timeout: 30
# 最大上下文长度 默认: 10
history_num: 10
# 对话会话超时时间 单位: 分钟 默认: 2 minute
session_time_out: 2

测试

你可以运行项目中提供的测试用例,前提是配置好OPEN-API-KEY

go test ./...

贡献

欢迎贡献!请 fork 此仓库,进行修改后提交 pull request。

许可证

此项目基于 AGPL-3.0 许可证进行授权 - 详细信息请参阅 LICENSE 文件。

联系方式

如果你有任何问题或建议,欢迎联系我。

Documentation

Overview

Package ai_sdk @Author Clover @Data 2024/8/12 下午4:13:00 @Desc 返回错误类

Package ai_sdk @Author Clover @Data 2024/8/11 下午10:34:00 @Desc openapi 客户端

Package ai_sdk @Author Clover @Data 2024/8/12 下午4:33:00 @Desc 自定义错误

Package ai_sdk @Author Clover @Data 2024/8/11 下午10:34:00 @Desc 多会话管理器

Package ai_sdk @Author Clover @Data 2024/8/12 下午4:00:00 @Desc 函数调用注册 todo 设计函数调用外部注册

Package ai_sdk @Author Clover @Data 2024/8/11 下午10:48:00 @Desc gpt实体类 request

Package ai_sdk @Author Clover @Data 2024/8/11 下午10:48:00 @Desc

Index

Constants

View Source
const (
	ToolsCallFinishReason = "tool_calls" // 方法调用
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AIClient

type AIClient struct {
	ContentType string
	Model       string
	ApiCfgList  []config.APIConfig

	EndPoint string
	// contains filtered or unexported fields
}

func NewAIClient

func NewAIClient(apiCfgList []config.APIConfig, model string, endPoint string, timeout int) *AIClient

NewAIClient 创建一个自定义请求客户端

func (AIClient) Send

func (a AIClient) Send(req Request) (resp Response[DefalutResponse], err error)

func (AIClient) SendByFuncCall

func (a AIClient) SendByFuncCall(req Request) (resp Response[FunctionCallResponse], err error)

SendByFuncCall 使用 Send默认调用就可以支持 Function_Call deprecated

type BaseResponse

type BaseResponse struct {
	Ret
	ErrMsg string `json:"err_msg"`
}

func (BaseResponse) Err

func (b BaseResponse) Err() error

func (BaseResponse) Ok

func (b BaseResponse) Ok() bool

type CallFunc added in v0.3.0

type CallFunc interface {
	Call(params string) (jsonStr string, err error) // 调用外部函数,返回json
}

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model      string    `json:"model"`
	Messages   []Message `json:"messages"`
	Tools      *[]Tool   `json:"tools,omitempty"`       // 可选
	ToolChoice string    `json:"tool_choice,omitempty"` // 默认 auto
}

type Choice

type Choice struct {
	Index        int         `json:"index"`
	Message      Message     `json:"message"`
	Logprobs     interface{} `json:"logprobs,omitempty"` // 可以是nil
	FinishReason string      `json:"finish_reason"`
}

type DefalutResponse

type DefalutResponse struct {
	Choices []Choice `json:"choices"`
	Usage   *Usage   `json:"usage,omitempty"`
}

type Delta

type Delta struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

type FuncCallInfo added in v0.3.0

type FuncCallInfo struct {
	Function      // 方法信息
	CallFunc      // 外部函数
	CustomTrigger func(content string) bool
}

func (*FuncCallInfo) Call added in v0.3.0

func (fc *FuncCallInfo) Call(callId string, params string) (Message, error)

Call 调用方法

func (*FuncCallInfo) IsCall added in v0.3.0

func (fc *FuncCallInfo) IsCall(content string) bool

type FuncCallRegister added in v0.3.0

type FuncCallRegister struct {
	Name2Info map[string]*FuncCallInfo
	// contains filtered or unexported fields
}
var FuncRegister FuncCallRegister

func (*FuncCallRegister) GetCallInfo added in v0.3.0

func (fc *FuncCallRegister) GetCallInfo(name string) *FuncCallInfo

GetCallInfo 根据方法名获取方法调用信息

func (*FuncCallRegister) GetToolsByContent added in v0.3.0

func (fc *FuncCallRegister) GetToolsByContent(content string) *[]Tool

GetToolsByContent 根据触发条件返回调用方法信息

func (*FuncCallRegister) Register added in v0.3.0

func (fc *FuncCallRegister) Register(finfo *FuncCallInfo, triggerWords []string)

Register 注册调用方法

type FuncInfoNameList added in v0.3.0

type FuncInfoNameList []string

type Function

type Function struct {
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Parameters  FunctionParameter `json:"parameters"`
	Strict      bool              `json:"strict"` // 是否严格 JSON 输出
}

Function 定义函数结构

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"` // JSON格式的字符串
}

type FunctionCallResponse

type FunctionCallResponse struct {
	Choices []Choice `json:"choices"`
	Usage   Usage    `json:"usage,omitempty"`
}

type FunctionParameter

type FunctionParameter struct {
	Type       string `json:"type"`
	Properties `json:"properties"`
	Required   []string `json:"required"`
}

FunctionParameter 定义函数参数类型

type Message

type Message struct {
	Role       string     `json:"role"`
	Content    string     `json:"content,omitempty"`      // Content可能为null
	ToolCallID string     `json:"tool_call_id,omitempty"` // 用于关联工具调用
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
}

type Properties added in v0.3.0

type Properties map[string]Property

type Property

type Property struct {
	Type        string   `json:"type"`
	Description string   `json:"description"`
	Enum        []string `json:"enum,omitempty"` // 用于枚举类型的字段
}

Property 定义函数属性类型

type Request

type Request struct {
	Messages   []Message
	Tools      *[]Tool
	ToolChoice string
}

type RespError

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

type Response

type Response[T any | DefalutResponse | FunctionCallResponse] struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	Model   string `json:"model"`
	// contains filtered or unexported fields
}

func (Response[T]) GetData

func (r Response[T]) GetData() T

type Ret

type Ret int

func (Ret) Error

func (r Ret) Error() string

func (Ret) String

func (i Ret) String() string

type Session

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

Session 会话主体 (k-v 会话id-会话信息)

var DefaultSession *Session

func NewSession

func NewSession(systemSet string, persessionTimeOut int) *Session

func (*Session) AddPreset added in v0.3.4

func (s *Session) AddPreset(addedpreset string)

AddPreset 追加预设

func (*Session) GetSession

func (s *Session) GetSession(sessionId string, extraOp func() string) *sessionInfo

GetSession 获取唯一会话

func (*Session) IsExist added in v0.3.4

func (s *Session) IsExist(sessionId string) bool

IsExist 该对话是否存在

func (*Session) ResetPreset added in v0.3.4

func (s *Session) ResetPreset(preset string)

ResetPreset 重设预设

func (*Session) TalkById

func (s *Session) TalkById(sessionId string, content string) (string, error)

TalkById 根据会话id对话 新增会话来获取会话发起对话

func (*Session) TalkByIdEx added in v0.4.0

func (s *Session) TalkByIdEx(sessionId string, content string, extraOp func() string) (string, error)

TalkByIdEx 根据会话id对话 并且允许携带 Ex: 额外的预设信息(拼接入system预设)

type StreamOptions

type StreamOptions struct {
	IncludeUsage bool `json:"include_usage,omitempty"`
}

type Tool

type Tool struct {
	Type     string   `json:"type"` // 默认function
	Function Function `json:"function"`
}

Tool 定义函数类型的工具

type ToolCall

type ToolCall struct {
	ID       string       `json:"id"`
	Type     string       `json:"type"`
	Function FunctionCall `json:"function"`
}

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Directories

Path Synopsis
Package config @Author Clover @Data 2024/8/12 下午12:53:00 @Desc 配置项
Package config @Author Clover @Data 2024/8/12 下午12:53:00 @Desc 配置项
example_func_call
weather
Package weather @Author Clover @Data 2024/8/15 下午5:16:00 @Desc
Package weather @Author Clover @Data 2024/8/15 下午5:16:00 @Desc
Package global @Author Clover @Data 2024/8/15 下午7:06:00 @Desc 方法调用注册器公有字段
Package global @Author Clover @Data 2024/8/15 下午7:06:00 @Desc 方法调用注册器公有字段
Package logging @Author Clover @Data 2024/7/18 上午10:24:00 @Desc 日志输出
Package logging @Author Clover @Data 2024/7/18 上午10:24:00 @Desc 日志输出
utils
configutil
Package configutil @Author Clover @Data 2024/7/6 下午3:51:00 @Desc
Package configutil @Author Clover @Data 2024/7/6 下午3:51:00 @Desc

Jump to

Keyboard shortcuts

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