aihub

package module
v0.0.0-...-cad9cba Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2025 License: MIT Imports: 26 Imported by: 0

README

AIHub

AIHub 是一个强大的 AI 工具仓库,提供基础 LLM(大型语言模型)接入和 Agent 能力,帮助开发者快速构建和部署 AI 应用。

功能特性

  • LLM 集成:支持接入多种大型语言模型,提供统一的接口
  • Agent 能力:实现智能体功能,可以执行复杂的任务和工具调用
  • 工具管理:通过 ToolHub 管理和使用各种工具
  • MCP 服务:通过 Model Context Protocol 扩展模型能力
  • 中间件支持:提供中间件机制,支持自定义处理逻辑
  • 会话管理:维护用户会话和消息历史
  • 流式响应:支持 SSE 流式响应,提供实时交互体验

安装

go get github.com/mvptianyu/aihub

快速开始

使用 LLM
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/mvptianyu/aihub"
)

func main() {
    // 创建 LLM 配置
    llmConfig := &aihub.LLMConfig{
        Provider:  "openai",
        APIKey:    "your-api-key",
        ModelName: "gpt-3.5-turbo",
    }

    // 创建 LLM 实例
    llm, err := aihub.NewLLM(llmConfig)
    if err != nil {
        log.Fatalf("Failed to create LLM: %v", err)
    }

    // 创建聊天完成
    resp, err := llm.CreateChatCompletion(context.Background(), []aihub.Message{
        {
            Role:    "user",
            Content: "Hello, how are you?",
        },
    })
    if err != nil {
        log.Fatalf("Failed to create chat completion: %v", err)
    }

    fmt.Println(resp.Choices[0].Message.Content)
}
使用 Agent 和工具
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/mvptianyu/aihub"
)

func main() {
    // 创建 Agent 配置
    agentConfig := &aihub.AgentConfig{
        LLMConfig: &aihub.LLMConfig{
            Provider:  "openai",
            APIKey:    "your-api-key",
            ModelName: "gpt-3.5-turbo",
        },
        Tools: []aihub.Tool{
            {
                Name:        "calculator",
                Description: "A calculator tool",
                Function: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
                    // 实现计算逻辑
                    return nil, nil
                },
            },
        },
    }

    // 创建 Agent 实例
    agent, err := aihub.NewAgent(agentConfig)
    if err != nil {
        log.Fatalf("Failed to create agent: %v", err)
    }

    // 运行 Agent
    resp, err := agent.Run(context.Background(), "Calculate 2 + 2")
    if err != nil {
        log.Fatalf("Failed to run agent: %v", err)
    }

    fmt.Println(resp)
}

示例

项目包含多个示例,展示了不同的使用场景:

  • agent_sql:SQL 智能体示例,展示如何使用 Agent 执行 SQL 查询
  • agent_with_tools:带工具的智能体示例,展示如何为 Agent 配置和使用工具
  • llm:LLM 使用示例,展示如何直接使用 LLM 进行对话
  • manus:配置文件示例,展示如何使用 YAML 配置文件配置 Agent 和 AgentHub
使用 Manus 和 AgentHub
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/mvptianyu/aihub"
)

func main() {
    // 创建 AgentHub 实例
    hub := aihub.NewAgentHub()

    // 从配置文件创建 Manus
    manus, err := aihub.NewManusFromFile("config.yaml")
    if err != nil {
        log.Fatalf("Failed to create manus: %v", err)
    }

    // 注册 Agent 到 Hub
    for _, agent := range manus.Agents {
        hub.RegisterAgent(agent.Name, agent)
    }

    // 使用 Hub 调用特定 Agent
    resp, err := hub.Run(context.Background(), "weather", "What's the weather in Beijing?")
    if err != nil {
        log.Fatalf("Failed to run agent: %v", err)
    }

    fmt.Println(resp)
}

配置

AIHub 支持通过代码或配置文件进行配置。

基本配置示例
llm:
  provider: openai
  api_key: your-api-key
  model_name: gpt-3.5-turbo

tools:
  - name: calculator
    description: A calculator tool
    schema:
      type: object
      properties:
        expression:
          type: string
          description: The expression to calculate
      required:
        - expression

middleware:
  - name: approver
    config:
      auto_approve: true
Manus 配置示例

Manus 允许通过 YAML 配置文件定义多个 Agent 及其工具:

agents:
  - name: weather
    description: "Weather agent that can provide weather information"
    llm:
      provider: openai
      api_key: ${OPENAI_API_KEY}
      model_name: gpt-3.5-turbo
    tools:
      - name: get_weather
        description: "Get weather information for a location"
        schema:
          type: object
          properties:
            location:
              type: string
              description: "The location to get weather for"
          required:
            - location

  - name: song
    description: "Song agent that can provide song recommendations"
    llm:
      provider: openai
      api_key: ${OPENAI_API_KEY}
      model_name: gpt-3.5-turbo
    tools:
      - name: search_songs
        description: "Search for songs by artist or genre"
        schema:
          type: object
          properties:
            artist:
              type: string
              description: "The artist name"
            genre:
              type: string
              description: "The music genre"

核心概念

Agent

Agent 是 AIHub 的核心组件,它封装了 LLM 的能力,并可以配置工具和中间件。Agent 可以处理用户输入,生成响应,并在需要时调用工具。

Tool

Tool 是 Agent 可以使用的工具,它可以执行特定的任务,如计算、查询数据库、调用 API 等。Tool 由名称、描述和 JSON Schema 定义。

Manus

Manus 是一个配置管理器,它可以从 YAML 配置文件中加载和创建多个 Agent。Manus 使得通过配置文件管理多个 Agent 变得简单。

AgentHub

AgentHub 是一个 Agent 管理器,它可以注册和管理多个 Agent,并根据需要调用特定的 Agent。AgentHub 使得在一个应用中使用多个专门的 Agent 变得简单。

高级用法

使用 AgentHub 管理多个 Agent
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/mvptianyu/aihub"
)

func main() {
    // 创建 AgentHub 实例
    hub := aihub.NewAgentHub()

    // 创建并注册第一个 Agent
    weatherAgent, err := aihub.NewAgent(&aihub.AgentConfig{
        LLMConfig: &aihub.LLMConfig{
            Provider:  "openai",
            APIKey:    "your-api-key",
            ModelName: "gpt-3.5-turbo",
        },
    })
    if err != nil {
        log.Fatalf("Failed to create weather agent: %v", err)
    }
    hub.RegisterAgent("weather", weatherAgent)

    // 创建并注册第二个 Agent
    songAgent, err := aihub.NewAgent(&aihub.AgentConfig{
        LLMConfig: &aihub.LLMConfig{
            Provider:  "openai",
            APIKey:    "your-api-key",
            ModelName: "gpt-3.5-turbo",
        },
    })
    if err != nil {
        log.Fatalf("Failed to create song agent: %v", err)
    }
    hub.RegisterAgent("song", songAgent)

    // 使用特定的 Agent
    weatherResp, err := hub.Run(context.Background(), "weather", "What's the weather in Beijing?")
    if err != nil {
        log.Fatalf("Failed to run weather agent: %v", err)
    }
    fmt.Println("Weather response:", weatherResp)

    songResp, err := hub.Run(context.Background(), "song", "Recommend me some rock songs")
    if err != nil {
        log.Fatalf("Failed to run song agent: %v", err)
    }
    fmt.Println("Song response:", songResp)
}

贡献

欢迎贡献代码、报告问题或提出新功能建议。请遵循以下步骤:

  1. Fork 项目
  2. 创建功能分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

许可证

本项目采用 MIT 许可证 - 详见 LICENSE 文件

Documentation

Overview

@Project: mvptianyu @Module: manus @File : manus.go

@Project: mvptianyu @Module: aihub @File : response.go

@Project: aihub @Module: aihub @File : session.go

Index

Constants

View Source
const (
	ToolArgumentsRawInputKey   = "INPUT_"
	ToolArgumentsRawSessionKey = "SESSION_"
)
View Source
const AgentCallFuncName = "AgentCall"

=======AgentCall注册==========

View Source
const ContextAIHubSessionKey = "AIHUB_SESSION"
View Source
const DefaultHTTPSessionID = "DEFAULT_HTTP_SESSION_ID"
View Source
const (
	ToolTypeFunction = "function"
)

Variables

View Source
var (
	ErrUnknown                     = errors.New("unknown error")
	ErrConfiguration               = errors.New("invalid agent or llm configuration")
	ErrToolRegisterRepeat          = errors.New("tool function name register repeated")
	ErrProviderRateLimit           = errors.New("llm trigger rate limit")
	ErrAgentRunTimeout             = errors.New("agent run timeout")
	ErrCallNameNotMatch            = errors.New("not found matched call name with mcp/tool entry")
	ErrMCPResponseEmpty            = errors.New("mcp call response empty")
	ErrChatCompletionOverMaxStep   = errors.New("chat request over max step quit")
	ErrMessageContentFieldsMisused = errors.New("message content fields are missing")
	ErrHTTPRequestURLInvalid       = errors.New("http request url invalid")
	ErrHTTPRequestBodyInvalid      = errors.New("http request body invalid")
	ErrHTTPRequestTimeout          = errors.New("http request timeout")
	ErrToolCallResponseEmpty       = errors.New("tool call response empty")
)

Functions

func AgentCall

func AgentCall(ctx context.Context, input *AgentCallReq, output *Message) (err error)

func ContextWithSession

func ContextWithSession(ctx context.Context, session *Session) context.Context

func HTTPCall

func HTTPCall(surl string, method string, req interface{}, reqHeader *http.Header, options ...HTTPOption) (rsp *http.Response, err error)

HTTPCall 统一发送http请求方法入口

Examples:

httpcli.Call( ctx, "http://www.xxx.com/", "GET", "aa=2", HTTPWithTimeOut(3) )

func HasMarkdownSyntax

func HasMarkdownSyntax(s string) bool

HasMarkdownSyntax 函数用于检查输入的字符串是否包含 Markdown 语法

Types

type AgentCallReq

type AgentCallReq struct {
	ToolInputBase
	RunStep `yaml:",inline"`
}

type AgentConfig

type AgentConfig struct {
	BriefInfo       `yaml:",inline"` // yaml解析inline结构
	AgentRuntimeCfg `yaml:",inline"` // yaml解析inline结构

	Tools       []string               `json:"tools,omitempty" yaml:"tools,omitempty"`               // 用到的工具名
	Mcps        []string               `json:"mcps,omitempty" yaml:"mcps,omitempty"`                 // 用到的MCP服务
	Middlewares []string               `json:"middlewares,omitempty" yaml:"middlewares,omitempty"`   // 用到的Middleware
	SessionData map[string]interface{} `json:"session_data,omitempty" yaml:"session_data,omitempty"` // 用到的Session数据
}

AgentConfig agent配置结构

func YamlDataToAgentConfig

func YamlDataToAgentConfig(yamlData []byte) (*AgentConfig, error)

func (*AgentConfig) AutoFix

func (cfg *AgentConfig) AutoFix() error

type AgentRuntimeCfg

type AgentRuntimeCfg struct {
	MemoryTimeout    int64   `json:"memory_timeout,omitempty" yaml:"memory_timeout,omitempty"`       // 历史消息缓存过期时间秒数
	MaxStoreMemory   int     `json:"max_store_memory,omitempty" yaml:"max_store_memory,omitempty"`   // 限制总体缓存会话记忆条数
	MaxUseMemory     int     `json:"max_use_memory,omitempty" yaml:"max_use_memory,omitempty"`       // 限制请求时使用的消息条数,避免输入token泛滥
	MaxStepQuit      int     `json:"max_step_quit,omitempty" yaml:"max_step_quit,omitempty"`         // 限制单次会话的最大执行步数,避免AI死循环
	MaxTokens        int     `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`               // 限制最大token数
	FrequencyPenalty float64 `json:"frequency_penalty,omitempty" yaml:"frequency_penalty,omitempty"` // 频率惩罚[-2.0~2.0],值越大,模型越倾向于避免重复已经生成过的词
	PresencePenalty  float64 `json:"presence_penalty,omitempty" yaml:"presence_penalty,omitempty"`   // 存在惩罚[-2.0~2.0],值越大,模型生成的文本中重复出现的词就越少
	Temperature      float64 `json:"temperature,omitempty" yaml:"temperature,omitempty"`             // 温度[0.0~2.0],值越大,模型生成的文本灵活性更高

	LLM          string `json:"llm,omitempty" yaml:"llm,omitempty"`                     // LLM提供商配置
	SystemPrompt string `json:"system_prompt,omitempty" yaml:"system_prompt,omitempty"` // 系统提示词
	StopWords    string `json:"stop_words,omitempty" yaml:"stop_words,omitempty"`       // 结束退出词
	RunTimeout   int64  `json:"run_timeout,omitempty" yaml:"run_timeout,omitempty"`     // 执行超时秒数
	Claim        string `json:"claim,omitempty" yaml:"claim,omitempty"`                 // 宣称文案,例如:本次返回由xxx提供
	Debug        bool   `json:"debug,omitempty" yaml:"debug,omitempty"`                 // debug输出标志,开启则输出具体工具调用过程信息
}

AgentRuntimeCfg 运行时配置

func (*AgentRuntimeCfg) AutoFix

func (cfg *AgentRuntimeCfg) AutoFix() error

type BriefInfo

type BriefInfo struct {
	Name        string `json:"name" yaml:"name"`               // 名称
	Description string `json:"description" yaml:"description"` // 描述
}

BriefInfo 公共基础简介

type ChatCompletionRspChoice

type ChatCompletionRspChoice struct {
	Index        int                           `json:"index"`
	Message      *Message                      `json:"message,omitempty"` // stream = false时返回
	Delta        *Message                      `json:"delta,omitempty"`   // stream = true时返回
	Logprobs     interface{}                   `json:"logprobs"`
	FinishReason ChatCompletionRspFinishReason `json:"finish_reason"`
}

type ChatCompletionRspError

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

type ChatCompletionRspFinishReason

type ChatCompletionRspFinishReason string
const (
	ChatCompletionRspFinishReasonStop                ChatCompletionRspFinishReason = "stop"
	ChatCompletionRspFinishReasonLength              ChatCompletionRspFinishReason = "length"
	ChatCompletionRspFinishReasonToolCalls           ChatCompletionRspFinishReason = "tool_calls"
	ChatCompletionRspFinishReasonContentFilter       ChatCompletionRspFinishReason = "content_filter"
	ChatCompletionRspFinishReasonContentFunctionCall ChatCompletionRspFinishReason = "function_call"
)

type CreateChatCompletionReq

type CreateChatCompletionReq struct {
	Messages         []*Message `json:"messages"`
	Model            string     `json:"model"`
	FrequencyPenalty float64    `json:"frequency_penalty,omitempty"`
	MaxTokens        int        `json:"max_tokens,omitempty"`
	PresencePenalty  float64    `json:"presence_penalty,omitempty"`
	Stop             string     `json:"stop,omitempty"`
	Stream           bool       `json:"stream,omitempty"`
	Temperature      float64    `json:"temperature,omitempty"`
	TopP             int        `json:"top_p,omitempty"`
	Tools            []*Tool    `json:"tools,omitempty"`
}

CreateChatCompletionReq 参见https://platform.openai.com/docs/api-reference/chat/create

type CreateChatCompletionRsp

type CreateChatCompletionRsp struct {
	Id      string                     `json:"id,omitempty"`
	Object  string                     `json:"object,omitempty"`
	Created int                        `json:"created,omitempty"`
	Model   string                     `json:"model,omitempty"`
	Choices []*ChatCompletionRspChoice `json:"choices,omitempty"`
	Usage   struct {
		PromptTokens        int `json:"prompt_tokens"`
		CompletionTokens    int `json:"completion_tokens"`
		TotalTokens         int `json:"total_tokens"`
		PromptTokensDetails struct {
			CachedTokens int `json:"cached_tokens"`
			AudioTokens  int `json:"audio_tokens"`
		} `json:"prompt_tokens_details"`
		CompletionTokensDetails struct {
			ReasoningTokens          int `json:"reasoning_tokens"`
			AudioTokens              int `json:"audio_tokens"`
			AcceptedPredictionTokens int `json:"accepted_prediction_tokens"`
			RejectedPredictionTokens int `json:"rejected_prediction_tokens"`
		} `json:"completion_tokens_details"`
	} `json:"usage,omitempty"`
	ServiceTier       string                  `json:"service_tier,omitempty"`
	SystemFingerprint string                  `json:"system_fingerprint,omitempty"`
	Error             *ChatCompletionRspError `json:"error,omitempty"`
}

CreateChatCompletionRsp 参见https://platform.openai.com/docs/api-reference/chat/create

type HTTPOption

type HTTPOption func(c *HTTPOptions)

func HTTPWithRetry

func HTTPWithRetry(retry int) HTTPOption

func HTTPWithRetryWait

func HTTPWithRetryWait(retrywait time.Duration) HTTPOption

func HTTPWithTimeOut

func HTTPWithTimeOut(timeout int64) HTTPOption

type HTTPOptions

type HTTPOptions struct {
	Header    http.Header   // header头设定
	TimeOut   time.Duration // 超时设定
	Retry     int           // 重试次数设定
	RetryWait time.Duration // 重试间隔设定,退火策略
}

HTTPOptions http请求选项设置

type IAgent

type IAgent interface {
	IBriefInfo

	// Run 执行Agent请求
	Run(ctx context.Context, input string, opts ...RunOptionFunc) *Response
	// RunStream 执行Agent请求,支持流式返回
	RunStream(ctx context.Context, input string, opts ...RunOptionFunc) (stream *ssestream.StreamReader[Response])
	// ResetMemory 重置会话记忆
	ResetMemory(ctx context.Context, opts ...RunOptionFunc) error
	// GetToolFunctions 获取工具配置
	GetToolFunctions() []ToolFunction
	// InvokeToolCall 调度指定工具命令
	InvokeToolCall(ctx context.Context, name string, args string, output *Message) (err error)
}

IAgent 智能体

func GetManus

func GetManus() IAgent

type IAgentHub

type IAgentHub interface {
	GetAllNameList() []string
	GetAgentList(names ...string) []IAgent
	GetAgent(name string) IAgent
	DelAgent(name string) error
	SetAgent(cfg *AgentConfig) (IAgent, error)
	SetAgentByYamlData(yamlData []byte) (IAgent, error)
	SetAgentByYamlFile(yamlFile string) (IAgent, error)
	GetMCPServer() IMCPServer
}

func GetAgentHub

func GetAgentHub() IAgentHub

type IBriefInfo

type IBriefInfo interface {
	GetBriefInfo() BriefInfo
}

type ILLM

type ILLM interface {
	IBriefInfo

	// CreateChatCompletion 创建Chat
	CreateChatCompletion(ctx context.Context, request *CreateChatCompletionReq) (response *CreateChatCompletionRsp, err error)
	// CreateChatCompletionStream 创建Chat以及stream返回
	CreateChatCompletionStream(ctx context.Context, request *CreateChatCompletionReq) (stream *ssestream.StreamReader[CreateChatCompletionRsp])
}

ILLM 模型相关能力

type ILLMHub

type ILLMHub interface {
	GetAllNameList() []string
	GetLLMList(names ...string) []ILLM
	GetLLM(name string) ILLM
	DelLLM(name string) error
	SetLLM(cfg *LLMConfig) (ILLM, error)
	SetLLMByYamlData(yamlData []byte) (ILLM, error)
	SetLLMByYamlFile(yamlFile string) (ILLM, error)
	GetMCPServer() IMCPServer
}

func GetLLMHub

func GetLLMHub() ILLMHub

type IMCPHub

type IMCPHub interface {
	GetAllNameList() []string
	GetClient(addrs ...string) []*client.SSEMCPClient
	DelClient(addrs ...string) error
	SetClient(addrs ...string) error
	ProxyCall(ctx context.Context, name string, input string, output *Message) (err error)
	GetToolFunctions(addrs []string, names []string) []ToolFunction
	ConvertToOPENAPIConfig() string
}

func GetMCPHub

func GetMCPHub() IMCPHub

type IMCPServer

type IMCPServer interface {
	Start(listenAddr string) error
	Shutdown(ctx context.Context) error
	GetSSEPath() string
	GetMessagePath() string
	AddTools(tools ...server.ServerTool)
	DelTools(names ...string)
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

IMCPServer MCP服务定义

type IMemory

type IMemory interface {
	// Push 塞入会话消息记录
	Push(opts *RunOptions, msg ...*Message)
	// GetLatest 获取最近会话消息记录
	GetLatest(opts *RunOptions) []*Message
	// Clear 清理指定消息记录
	Clear(opts *RunOptions)
}

IMemory 会话记录

type IMiddleware

type IMiddleware interface {
	// BeforeProcessing 前处理
	BeforeProcessing(ctx context.Context, req *Message, rsp []*Message, opts *RunOptions) error
	// AfterProcessing 后处理
	AfterProcessing(ctx context.Context, req *Message, rsp []*Message, opts *RunOptions) error
}

IMiddleware 调用拦截器

type IMiddlewareHub

type IMiddlewareHub interface {
	GetAllNameList() []string
	GetMiddleware(names ...string) []IMiddleware
	DelMiddleware(names ...string) error
	SetMiddleware(middlewares ...IMiddleware) error
}

func GetMiddlewareHub

func GetMiddlewareHub() IMiddlewareHub

type ISession

type ISession interface {
	// SetSessionData 设置数据KV
	SetSessionData(key string, value interface{})
	// GetSessionData 获取数据KV
	GetSessionData(key string) interface{}
	// GetAllSessionData 获取所有数据KV
	GetAllSessionData() map[string]interface{}
	// GetSessionID 获取sessionid
	GetSessionID() string
}

ISession 会话session数据

type IToolHub

type IToolHub interface {
	GetAllNameList() []string
	GetToolFunctions(names ...string) []ToolFunction
	GetTool(names ...string) []ToolEntry
	DelTool(names ...string) error
	SetTool(objs ...ToolEntry) error
	ProxyCall(ctx context.Context, name string, input string, output *Message) (err error)
	ConvertToOPENAPIConfig() string
	GetMCPServer() IMCPServer
}

func GetToolHub

func GetToolHub() IToolHub

type IToolInput

type IToolInput interface {
	GetRawInput() string
	SetRawInput(str string)
	GetRawSession() string
	SetRawSession(str string)
}

IToolInput 工具入参格式定义

type LLMConfig

type LLMConfig struct {
	BriefInfo `yaml:",inline"` // yaml解析inline结构

	ModelType LLMType `json:"model_type" yaml:"model_type"`
	Provider  string  `json:"provider" yaml:"provider"` // 提供商名称,例如openai
	BaseURL   string  `json:"base_url" yaml:"base_url"`
	Version   string  `json:"version" yaml:"version"`
	APIKey    string  `json:"api_key" yaml:"api_key"`
	MaxTokens int     `json:"max_tokens" yaml:"max_tokens"` // 模型本身限制的最大token数
	RateLimit int     `json:"rate_limit" yaml:"rate_limit"`
}

LLMConfig provider配置结构

func YamlDataToLLMConfig

func YamlDataToLLMConfig(yamlData []byte) (*LLMConfig, error)

func (*LLMConfig) AutoFix

func (cfg *LLMConfig) AutoFix() error

type LLMType

type LLMType int
const (
	LLMType_Base   LLMType = iota // 基础模型,例GPT-3.5-turbo、LLM3.2等
	LLMType_Reason                // 推理模型,例GPT-4o、Deepseek R1等
	LLMType_Vision                // 视觉模型,例GPT-4o等
)

type Message

type Message struct {
	Content      string                `json:"-"`
	MultiContent []*MessageContentPart `json:"-"`
	Role         MessageRoleType       `json:"role"`
	Name         string                `json:"name,omitempty"`
	ToolCallID   string                `json:"tool_call_id,omitempty"` // Role=tool发出请求时携带之前由Role=assistant返回的ToolCallID
	ToolCalls    []*MessageToolCall    `json:"tool_calls,omitempty"`   // Role=assistant返回的Message所带的ToolCalls
	Refusal      string                `json:"refusal,omitempty"`

	CreateTime int64  `json:"-"`
	SessionID  string `json:"-"`
}

func (*Message) Copy

func (m *Message) Copy() *Message

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(bs []byte) error

type MessageContentAudio

type MessageContentAudio struct {
	Data   string                    `json:"data"`
	Format MessageContentAudioFormat `json:"format"` // mp3|wav
}

type MessageContentAudioFormat

type MessageContentAudioFormat string
const (
	MessageContentAudioFormatMP3 MessageContentAudioFormat = "mp3"
	MessageContentAudioFormatWAV MessageContentAudioFormat = "wav"
)

type MessageContentFile

type MessageContentFile struct {
	FileData string `json:"file_data"` // base64数据
	FileName string `json:"format"`    // 文件名
}

type MessageContentImage

type MessageContentImage struct {
	URL string `json:"url"` // 图片url或base64数据
}

type MessageContentPart

type MessageContentPart struct {
	Type       MessageContentType   `json:"type"`
	Text       string               `json:"text,omitempty"`
	ImageUrl   *MessageContentImage `json:"image_url,omitempty"`
	InputAudio *MessageContentAudio `json:"input_audio,omitempty"`
	File       *MessageContentFile  `json:"file,omitempty"`
}

type MessageContentType

type MessageContentType string
const (
	MessageContentTypeText  MessageContentType = "text"
	MessageContentTypeImage MessageContentType = "image_url"
	MessageContentTypeAudio MessageContentType = "input_audio"
	MessageContentTypeFile  MessageContentType = "file"
)

type MessageRoleType

type MessageRoleType string
const (
	MessageRoleUser      MessageRoleType = "user"
	MessageRoleAssistant MessageRoleType = "assistant"
	MessageRoleSystem    MessageRoleType = "system"
	MessageRoleTool      MessageRoleType = "tool"
)

type MessageToolCall

type MessageToolCall struct {
	Id       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

type OPENAPIConfig

type OPENAPIConfig struct {
	OpenAPI string                     `json:"openapi"`
	Info    OPENAPIInfo                `json:"info"`
	Paths   map[string]OPENAPIPathItem `json:"paths"`
	Tags    []OPENAPITag               `json:"tags"`
}

OPENAPIConfig 定义 OPENAPI 规范的根结构体

func (*OPENAPIConfig) AddToolFunction

func (cfg *OPENAPIConfig) AddToolFunction(toolFunctions []ToolFunction, server string)

AddToolFunction 将 ToolFunction 加入OPENAPIConfig 结构体

type OPENAPIInfo

type OPENAPIInfo struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Version     string `json:"version"`
}

OPENAPIInfo 定义 OPENAPIConfig 规范中的 info 部分

type OPENAPIOperation

type OPENAPIOperation struct {
	Summary     string                     `json:"summary"`
	Description string                     `json:"description"`
	RequestBody OPENAPIRequestBody         `json:"requestBody"`
	Responses   map[string]OPENAPIResponse `json:"responses"`
	Servers     []OPENAPIServer            `json:"servers,omitempty"`
	Tags        []string                   `json:"tags,omitempty"`
}

OPENAPIOperation 定义 OPENAPIConfig 规范中的 operation 部分

type OPENAPIPathItem

type OPENAPIPathItem struct {
	Post OPENAPIOperation `json:"post"`
}

OPENAPIPathItem 定义 OPENAPIConfig 规范中的 pathItem 部分

type OPENAPIRequestBody

type OPENAPIRequestBody struct {
	Required bool                   `json:"required"`
	Content  map[string]interface{} `json:"content"`
}

OPENAPIRequestBody 定义 OPENAPIConfig 规范中的 requestBody 部分

type OPENAPIResponse

type OPENAPIResponse struct {
	Description string `json:"description"`
}

OPENAPIResponse 定义 OPENAPIConfig 规范中的 response 部分

type OPENAPIServer

type OPENAPIServer struct {
	Url         string `json:"url"`
	Description string `json:"description"`
}

OPENAPIServer 定义 OPENAPIConfig 规范中的 servers 部分

type OPENAPITag

type OPENAPITag struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

type Response

type Response struct {
	Err error `json:"-"`
	// contains filtered or unexported fields
}

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() ([]byte, error)

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(bs []byte) error

type RunOptionFunc

type RunOptionFunc func(*RunOptions)

RunOptionFunc 运行时选项

func WithAgents

func WithAgents(agents []string) RunOptionFunc

func WithContext

func WithContext(context interface{}) RunOptionFunc

func WithDebug

func WithDebug(debug bool) RunOptionFunc

func WithRuntimeCfg

func WithRuntimeCfg(runtimeCfg AgentRuntimeCfg) RunOptionFunc

func WithSessionData

func WithSessionData(sessionData map[string]interface{}) RunOptionFunc

func WithSessionID

func WithSessionID(sessionID string) RunOptionFunc

func WithSystemPrompt

func WithSystemPrompt(systemPrompt string) RunOptionFunc

type RunOptions

type RunOptions struct {
	*Session
	RuntimeCfg AgentRuntimeCfg // 运行时配置
	Tools      []BriefInfo     // 用到的关联tool定义
	Agents     []BriefInfo     // 用到的关联Agent定义
	Context    interface{}     // 可选,上下文信息,例如知识库等
	// contains filtered or unexported fields
}

func (*RunOptions) AddStep

func (opts *RunOptions) AddStep(src *RunStep)

func (*RunOptions) CheckStepQuit

func (opts *RunOptions) CheckStepQuit() bool

func (*RunOptions) RenderFinalAnswer

func (opts *RunOptions) RenderFinalAnswer() string

func (*RunOptions) UpdateSystemPrompt

func (opts *RunOptions) UpdateSystemPrompt(content string) string

type RunState

type RunState int

RunState 表示当前状态

const (
	RunState_Idle RunState = iota
	RunState_Running
	RunState_Succeed
	RunState_Failed
	RunState_Error
)

func (RunState) String

func (s RunState) String() string

String 返回状态的字符串表示

type RunStep

type RunStep struct {
	Action string   `json:"_action_" yaml:"_action_" description:"该步骤名称" required:"true"` // 该步骤名称
	State  RunState ``                                                                    // 该步骤状态:0-初始化(默认),1-执行中,2-成功退出,3-失败退出,4-异常终止
	/* 165-byte string literal not displayed */
	Question string `` // 该步骤需要解决的问题
	/* 132-byte string literal not displayed */
	Think    string    `json:"_think_" yaml:"_think_" description:"该步骤结合用户请求和上下文的思考概述" required:"true"` // 该步骤的推理思考概要
	Result   string    `json:"_result_,omitempty" yaml:"_result_,omitempty" description:"该步骤运行结果文字内容"`  // 该步骤完成的输出结果
	EndTime  time.Time `json:",omitempty" yaml:",omitempty"`                                            // 该步骤完成时间
	StepType StepType  `json:",omitempty" yaml:",omitempty"`                                            // 该步骤类别
}

func (*RunStep) IsEmpty

func (r *RunStep) IsEmpty() bool

func (*RunStep) MergeWith

func (r *RunStep) MergeWith(src *RunStep)

type Session

type Session struct {
	SessionID   string                 `json:"session_id"`
	SessionData map[string]interface{} `json:"session_data"`
	// contains filtered or unexported fields
}

func SessionFromContext

func SessionFromContext(ctx context.Context) *Session

func (*Session) GetAllSessionData

func (s *Session) GetAllSessionData() map[string]interface{}

func (*Session) GetSessionData

func (s *Session) GetSessionData(key string) interface{}

func (*Session) GetSessionID

func (s *Session) GetSessionID() string

func (*Session) MergeSessionData

func (s *Session) MergeSessionData(data map[string]interface{})

func (*Session) SetSessionData

func (s *Session) SetSessionData(key string, value interface{})

type StepType

type StepType int

StepType 表示步骤类别

const (
	StepType_None StepType = iota
	StepType_Start
	StepType_End
	StepType_Tool
	StepType_Agent
)

func (StepType) String

func (s StepType) String() string

String 返回状态的字符串表示

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

type ToolEntry

type ToolEntry struct {
	Description string
	Function    interface{} // 方法入口
	// contains filtered or unexported fields
}

type ToolFunction

type ToolFunction struct {
	BriefInfo
	Parameters *jsonschema.Definition `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	Strict     bool                   `json:"strict,omitempty" yaml:"strict,omitempty"`
}

type ToolInputBase

type ToolInputBase struct {
	Session string `json:"SESSION_" description:"记录session的key名,默认为空,无需设置" required:"false"`
	// contains filtered or unexported fields
}

func (*ToolInputBase) GetRawInput

func (t *ToolInputBase) GetRawInput() string

func (*ToolInputBase) GetRawSession

func (t *ToolInputBase) GetRawSession() string

func (*ToolInputBase) SetRawInput

func (t *ToolInputBase) SetRawInput(str string)

func (*ToolInputBase) SetRawSession

func (t *ToolInputBase) SetRawSession(str string)

type ToolMethod

type ToolMethod func(ctx context.Context, input IToolInput, output *Message) (err error)

ToolMethod 工具方法入口签名,Input派生自ToolInputBase

Directories

Path Synopsis
examples
agent_sql command
llm command
manus command
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.

Jump to

Keyboard shortcuts

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