agent

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 16 Imported by: 0

README

tracklogic-agent

tracklogic-agent 是一个用于构建模型驱动 Agent、工具调用、记忆、Team 和 Workflow 的纯 Go Harness 库。根包 agent 提供常用入口;modelmemorytoolengineorchestratorsecuritytypes 包提供可替换的扩展接口。

项目同时保留《智能体 Harness 工程指南》的 13 章配套教程和一个可运行的 JD 智能客服示例。

环境

  • Go 1.26 或更高版本
  • 使用真实模型时需要相应供应商的 API 地址、模型 ID 和 API Key
  • 无 API Key 时可以使用内置 Mock 模型完成本地测试

安装

go get github.com/apexracing/tracklogic-agent

快速开始

package main

import (
    "context"
    "fmt"
    "log"

    agent "github.com/apexracing/tracklogic-agent"
)

func main() {
    cfg := agent.DefaultConfig()
    cfg.DefaultModel.APIFormat = "mock"
    cfg.DefaultModel.ModelID = "local-demo"

    harness, err := agent.New(cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer harness.Close()

    assistant := harness.NewAgent("assistant", "你是一个简洁、可靠的助手。")
    result := assistant.Run(context.Background(), "你好",
        agent.WithMaxLoops(5),
        agent.WithTemperature(0.2),
    )
    if !result.Success {
        log.Fatal(result.Error)
    }
    fmt.Println(result.Content)
}

扩展接口

应用可以实现并注入自己的 model.Modelmemory.Memorytool.Tool。例如注册自定义工具:

registry := tool.NewRegistry()
err := registry.Register(myTool)

runtimeAgent := agent.NewAgent(agent.AgentConfig{
    Name:         "custom-agent",
    Model:        myModel,
    Memory:       myMemory,
    ToolRegistry: registry,
})

根包同时导出 Team、Workflow、Node 和常用构造函数;复杂编排也可以直接使用 orchestrator 包。

模型配置

vendor 只用于供应商标识和日志;api_format 独立决定 HTTP 协议实现。支持:

  • openai_response
  • openai_chat_completions
  • anthropic_message
  • mock

base_urlapi_keymodel_id 均由调用方显式配置,不会根据 vendor 推断。

JD 智能客服示例

示例固定读取仓库根目录下的 examples/config.example.json。默认示例不保存 API Key;Key 为空时自动回退到 Mock 模型。

真实模型测试时通过进程环境传入 Key,避免修改公开示例:

$env:TRACKLOGIC_AGENT_API_KEY="<your-api-key>"
go run ./examples/cmd/jd-cs-service
go run ./examples/cmd/jd-cs-service

目录结构

agent.go, harness.go, config.go   package agent 根公共 API
engine/                           Agent 运行循环与流式处理
model/                            模型接口及协议实现
memory/                           记忆接口与 BufferMemory
tool/, tool/builtin/              工具接口、注册表与内置工具
orchestrator/                     Team、Workflow 与 Node
security/, types/                 安全、权限和共享基础类型
internal/mcpclient/               内部 MCP 客户端实现
examples/                         JD 智能客服示例
docs/                             13 章 Harness 教程

教程

教程从架构、运行时、工具、记忆和模型集成开始,继续覆盖输出治理、编排、MCP、生产可靠性、安全以及完整业务示例。阅读入口为 docs/01-introduction.md

测试

go test ./...
go vet ./...

许可

项目使用 MIT License,详见 LICENSE

Documentation

Overview

Package agent provides a Go harness for building model-backed agents, registering tools, managing memory, and composing teams and workflows.

Start with New and Harness.NewAgent for the common path. The model, memory, tool, engine, orchestrator, security, and types subpackages expose extension points for applications that need custom implementations.

Index

Constants

View Source
const (
	ModeSequential     = orchestrator.ModeSequential
	ModeParallel       = orchestrator.ModeParallel
	ModeLeaderFollower = orchestrator.ModeLeaderFollower
)
View Source
const (
	PermReadFile  = security.PermReadFile
	PermWriteFile = security.PermWriteFile
	PermExec      = security.PermExec
	PermNetAccess = security.PermNetAccess
	PermReadDB    = security.PermReadDB
	PermWriteDB   = security.PermWriteDB
	PermSendEmail = security.PermSendEmail
)
View Source
const (
	NodeTypeStep      = orchestrator.NodeTypeStep
	NodeTypeCondition = orchestrator.NodeTypeCondition
	NodeTypeLoop      = orchestrator.NodeTypeLoop
	NodeTypeParallel  = orchestrator.NodeTypeParallel
)

Variables

This section is empty.

Functions

func ResolveModelDefaults

func ResolveModelDefaults(cfg *ModelConfig)

ResolveModelDefaults normalizes vendor/api_format and timeout. BaseURL is never inferred from vendor ? configure it explicitly (vendor and api_format are independent).

Types

type Agent

type Agent = engine.Agent

Agent is the runtime agent implementation exposed by the root package.

func NewAgent

func NewAgent(cfg AgentConfig) *Agent

NewAgent creates a standalone Agent. Most applications can instead use Harness.NewAgent, which shares the Harness model and tool registry.

type AgentConfig

type AgentConfig = engine.AgentConfig

AgentConfig configures a standalone Agent.

type ConditionNode

type ConditionNode = orchestrator.ConditionNode

func NewConditionNode

func NewConditionNode(id string, condition func(input string, state map[string]any) (bool, error), trueNode, falseNode Node) *ConditionNode

type Config

type Config struct {
	Version        string            `json:"version"`
	Name           string            `json:"name"`
	LogLevel       string            `json:"log_level"`
	DefaultModel   ModelConfig       `json:"default_model"`
	AllowedTools   []string          `json:"allowed_tools"`
	MemoryConfig   MemoryConfig      `json:"memory"`
	PermissionMode string            `json:"permission_mode"` // strict, permissive
	MCPClients     []MCPClientConfig `json:"mcp_clients,omitempty"`
	Security       SecurityConfig    `json:"security"`
}

func DefaultConfig

func DefaultConfig() Config

func LoadConfig

func LoadConfig(path string) (Config, error)

type Harness

type Harness struct {
	Config       Config
	Model        model.Model
	ToolRegistry *tool.Registry
	Memory       memory.Memory

	PermissionMgr   *security.PermissionManager
	InputValidator  *security.InputValidator
	OutputValidator *security.OutputValidator
	Sanitizer       *security.Sanitizer

	Agents    map[string]*engine.Agent
	Teams     map[string]*orchestrator.Team
	Workflows map[string]*orchestrator.Workflow
	// contains filtered or unexported fields
}

func New

func New(cfg Config) (*Harness, error)

func (*Harness) AllowPermissions

func (h *Harness) AllowPermissions(permissions ...security.Permission)

func (*Harness) CheckPermission

func (h *Harness) CheckPermission(perm security.Permission) error

func (*Harness) Close

func (h *Harness) Close() error

func (*Harness) DenyPermissions

func (h *Harness) DenyPermissions(permissions ...security.Permission)

func (*Harness) InitMCPClients

func (h *Harness) InitMCPClients(ctx context.Context) error

func (*Harness) NewAgent

func (h *Harness) NewAgent(name, systemPrompt string) *engine.Agent

func (*Harness) NewTeam

func (h *Harness) NewTeam(cfg orchestrator.TeamConfig) *orchestrator.Team

func (*Harness) NewWorkflow

func (*Harness) RegisterTeam

func (h *Harness) RegisterTeam(team *orchestrator.Team) error

func (*Harness) RegisterTool

func (h *Harness) RegisterTool(t tool.Tool) error

func (*Harness) RegisterWorkflow

func (h *Harness) RegisterWorkflow(workflow *orchestrator.Workflow) error

func (*Harness) RunAgent

func (h *Harness) RunAgent(ctx context.Context, name, input string, opts ...engine.RunOption) *engine.RunOutput

func (*Harness) RunTeam

func (h *Harness) RunTeam(ctx context.Context, name, input string) *orchestrator.TeamOutput

func (*Harness) RunWorkflow

func (h *Harness) RunWorkflow(ctx context.Context, name, input string) *orchestrator.WorkflowResult

func (*Harness) Sanitize

func (h *Harness) Sanitize(input string) string

func (*Harness) ValidateInput

func (h *Harness) ValidateInput(input string) error

func (*Harness) ValidateOutput

func (h *Harness) ValidateOutput(output string) error

type LoopNode

type LoopNode = orchestrator.LoopNode

func NewLoopNode

func NewLoopNode(id string, body Node, condition func(iteration int, input string, state map[string]any) (bool, error), maxIterations int) *LoopNode

type MCPClientConfig

type MCPClientConfig struct {
	Name    string `json:"name"`
	BaseURL string `json:"base_url"`
	Timeout int    `json:"timeout_seconds"`
}

type MemoryConfig

type MemoryConfig struct {
	Type     string `json:"type"` // buffer, summary
	Capacity int    `json:"capacity"`
}

type ModelConfig

type ModelConfig struct {
	Vendor    string `json:"vendor"`     // deepseek / openai / anthropic / custom (logging / identity)
	APIFormat string `json:"api_format"` // openai_response / openai_chat_completions / anthropic_message / mock
	BaseURL   string `json:"base_url,omitempty"`
	APIKey    string `json:"api_key,omitempty"`
	ModelID   string `json:"model_id"`
	Timeout   int    `json:"timeout_seconds"`
}

ModelConfig describes which vendor and API protocol to use. Vendor and APIFormat are independent: BuildModel selects the client by APIFormat only; BaseURL/APIKey/ModelID come from config as-is.

func (ModelConfig) BuildModel

func (c ModelConfig) BuildModel() (model.Model, error)

type Node

type Node = orchestrator.Node

type NodeType

type NodeType = orchestrator.NodeType

type ParallelNode

type ParallelNode = orchestrator.ParallelNode

func NewParallelNode

func NewParallelNode(id string, nodes ...Node) *ParallelNode

type Permission

type Permission = security.Permission

type RunOption

type RunOption = engine.RunOption

RunOption customizes an individual Agent run.

func WithMaxLoops

func WithMaxLoops(n int) RunOption

func WithMaxTokens

func WithMaxTokens(n int) RunOption

func WithStream

func WithStream(fn func(string)) RunOption

func WithTemperature

func WithTemperature(value float64) RunOption

type RunOutput

type RunOutput = engine.RunOutput

RunOutput is the result of an Agent run.

type SecurityConfig

type SecurityConfig struct {
	MaxInputLength       int  `json:"max_input_length"`
	MaxOutputLength      int  `json:"max_output_length"`
	EnableInjectionCheck bool `json:"enable_injection_check"`
	SanitizePII          bool `json:"sanitize_pii"`
}

type StepLog

type StepLog = orchestrator.StepLog

type StepNode

type StepNode = orchestrator.StepNode

func NewStepNode

func NewStepNode(id string, runtimeAgent *Agent, after ...func(input, output string, state map[string]any)) *StepNode

type Team

type Team = orchestrator.Team

func NewTeam

func NewTeam(cfg TeamConfig) *Team

type TeamConfig

type TeamConfig = orchestrator.TeamConfig

type TeamMode

type TeamMode = orchestrator.TeamMode

type TeamOutput

type TeamOutput = orchestrator.TeamOutput

type Workflow

type Workflow = orchestrator.Workflow

func NewWorkflow

func NewWorkflow(cfg WorkflowConfig) *Workflow

type WorkflowConfig

type WorkflowConfig = orchestrator.WorkflowConfig

type WorkflowResult

type WorkflowResult = orchestrator.WorkflowResult

Directories

Path Synopsis
examples
internal

Jump to

Keyboard shortcuts

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