agent

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 23 Imported by: 0

README

tracklogic-agent

tracklogic-agent 是一个用于构建模型驱动 Agent、工具调用、记忆、Team 和 Workflow 的纯 Go 公共库。根包 agent 提供 Harness 与配置入口;enginemodelmemorytoolsecuritytypesworkflowmcp 是职责独立的公共扩展包。

本库只负责通用 Harness。业务数据接入、业务逻辑、展示与持久化属于依赖本库的上层应用,通过自定义 Tool、MCP、Model 或 Workflow 组合实现,不在核心包中定义领域类型。

项目同时包含《智能体 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"
    "github.com/apexracing/tracklogic-agent/engine"
)

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, err := harness.CreateAgent("assistant", "你是一个简洁、可靠的助手。")
    if err != nil {
        log.Fatal(err)
    }
    result := assistant.Run(context.Background(), "你好",
        engine.WithMaxLoops(5),
        engine.WithTemperature(0.2),
    )
    if !result.Success {
        log.Fatal(result.Error)
    }
    fmt.Println(result.Content)
}

需要后台 Turn、实时事件和安全恢复时,使用 Task API;TaskID 和事件处理由调用方提供:

runtimeTask, err := harness.NewTask(task.Options{
    TaskID:    taskID,
    EventSink: sink,
})
if err != nil { return err }
defer runtimeTask.Close()

turn, err := runtimeTask.StartAgent(ctx, "assistant", input)
if err != nil { return err }
result, err := runtimeTask.WaitTurn(ctx, turn.ID)

Task 模式默认提供模型 5 次尝试、按 Model 实例断路器、Summary Memory、结构化询问和检查点事件。库不提供数据库、JSONL、HTTP/SSE/WebSocket 或默认存储目录;这些属于上层应用。原有 RunAgentRunTeamRunWorkflowAgent.Run 同步 API 行为保持不变。

公共扩展包

  • engine:Agent、执行循环、流式输出和运行选项。
  • model:Model 接口及 OpenAI、Chat Completions、Anthropic、Mock 实现。
  • memory:Memory 接口、BufferMemory 和 Task 使用的 SummaryMemory。
  • taskinteraction:Task/Turn/Item 事件协议、检查点和结构化用户询问。
  • tooltool/builtin:Tool、Registry 和内置工具。
  • security:可替换的权限、输入输出校验和脱敏接口。
  • types:Message、ToolCall、Usage、RunContext 和结构化错误等跨层协议。
  • workflow:Team、Workflow 和各种 Node。
  • mcp:可直接使用的公共 MCP 客户端。

创建完全自定义的 Agent:

registry := tool.NewRegistry()
if err := registry.Register(myTool); err != nil {
    return err
}

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

根包不重复导出这些类型;例如 Team 和 Workflow 使用 workflow.NewTeamworkflow.NewWorkflow 创建,再通过 Harness 注册和运行。

模型配置

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

  • openai_response
  • openai_chat_completions
  • anthropic_message
  • mock

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

agent.New 会自动归一化并校验配置。需要统一应用日志时,使用 agent.WithLogger 注入运行时依赖;库不会替换进程的 slog.Default

生产代码建议使用返回 error 的 CreateAgentCreateTeamCreateWorkflow,避免非法名称或同名注册被忽略。多个 Agent 共用 Registry 时,使用 CreateAgentWithTools 声明每个 Agent 的最小工具集合;白名单同时限制模型可见定义和实际执行。同一个有状态 Agent 的 Run 会串行执行,等待期间可被 Context 取消;不同会话应使用不同 Agent/Memory,才能并行且隔离上下文。

Model Provider 对普通响应设置 16 MiB 上限,对错误响应设置 8 KiB 上限;429、超时和取消会保留可识别错误码。RunOutputTeamOutputWorkflowResultErr 可用于 errors.As,字符串 Error 用于兼容序列化。需要企业代理、mTLS、自定义 Header 或应用层重试时,可预构造 Model 并通过 agent.WithModel 注入。

MCP Client 支持 Streamable HTTP、协议协商、Session、JSON/SSE 响应和完整 JSON Schema 保留。含认证 Header、mTLS 或代理的 Client 应通过 mcp.NewClient(...) 预构造,再用 agent.WithMCPClient 注入;远端工具仍需显式调用 InitMCPClients 才会注册。

内置文件工具使用 Go 的受限目录根 API,拒绝 .. 和越界符号链接,并限制单文件为 1 MiB;http_get 默认拒绝私网、回环和链路本地地址,限制重定向、超时和正文大小。需要访问内网服务时应显式构造带策略的 Tool,而不是放宽整个 Harness。

JD 智能客服示例

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

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

无真实 Key 时:

go run ./cmd/jd-cs-service

目录结构

agent.go, harness.go, config.go   package agent:Harness 与配置 façade
engine/                           Agent 运行循环与流式处理
model/                            模型接口及协议实现
memory/                           记忆接口与 BufferMemory
tool/, tool/builtin/              工具接口、注册表与内置工具
security/                         权限、校验与脱敏扩展
types/                            跨层稳定协议类型
workflow/                         Team、Workflow 与 Node
mcp/                              公共 MCP 客户端
examples/jdcs/                    JD 智能客服业务示例
cmd/jd-cs-service/                Demo 入口
docs/                             13 章 Harness 教程

教程与测试

建议先阅读 学习路线与设计决策总览,建立“概率模型 + 确定性 Harness”的整体心智模型,再从 第 1 章 开始按章学习。

go test ./...
go test -race ./...
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, workflow, security, types, and mcp subpackages expose extension points for applications that need custom implementations or direct access.

Index

Constants

This section is empty.

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 because vendor and api_format are independent.

Types

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)

func (Config) Validate added in v0.3.0

func (c Config) Validate() error

Validate rejects ambiguous or unsupported production configuration before the Harness starts accepting work.

type Harness

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

func New

func New(cfg Config, options ...Option) (*Harness, error)

func (*Harness) Agent added in v0.2.0

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

func (*Harness) AllowPermissions

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

func (*Harness) CheckPermission

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

func (*Harness) Close

func (h *Harness) Close() error

func (*Harness) Config

func (h *Harness) Config() Config

func (*Harness) CreateAgent added in v0.3.0

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

CreateAgent constructs and atomically registers an Agent. Production code should prefer this method over NewAgent so invalid or duplicate names cannot fail silently.

func (*Harness) CreateAgentWithTools added in v0.3.0

func (h *Harness) CreateAgentWithTools(name, systemPrompt string, toolNames ...string) (*engine.Agent, error)

CreateAgentWithTools constructs and atomically registers an Agent whose visible and executable Tool set is restricted to the supplied names. An empty list creates an Agent with no tools.

func (*Harness) CreateTeam added in v0.3.0

func (h *Harness) CreateTeam(cfg workflow.TeamConfig) (*workflow.Team, error)

CreateTeam validates, constructs, and atomically registers a Team.

func (*Harness) CreateWorkflow added in v0.3.0

func (h *Harness) CreateWorkflow(cfg workflow.WorkflowConfig) (*workflow.Workflow, error)

CreateWorkflow validates, constructs, and atomically registers a Workflow.

func (*Harness) DenyPermissions

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

func (*Harness) InitMCPClients

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

func (*Harness) Model

func (h *Harness) Model() model.Model

func (*Harness) NewAgent

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

NewAgent is the compatibility convenience constructor. It returns nil and logs when validation or registration fails. Production code should prefer CreateAgent and handle its error.

func (*Harness) NewTask added in v0.3.0

func (h *Harness) NewTask(options taskpkg.Options) (*Task, error)

NewTask creates an in-memory task runtime. TaskID must be stable and supplied by the caller so its own records can correlate events and checkpoints.

func (*Harness) NewTeam

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

NewTeam is the compatibility convenience constructor. Production code should prefer CreateTeam and handle its error.

func (*Harness) NewWorkflow

func (h *Harness) NewWorkflow(cfg workflow.WorkflowConfig) *workflow.Workflow

NewWorkflow is the compatibility convenience constructor. Production code should prefer CreateWorkflow and handle its error.

func (*Harness) RegisterAgent added in v0.2.0

func (h *Harness) RegisterAgent(runtimeAgent *engine.Agent) error

func (*Harness) RegisterTeam

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

func (*Harness) RegisterTool

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

func (*Harness) RegisterWorkflow

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

func (*Harness) RestoreTask added in v0.3.0

func (h *Harness) RestoreTask(input taskpkg.RestoreInput, sink taskpkg.EventSink) (*Task, error)

RestoreTask recreates an in-memory task from a checkpoint previously handled by the caller. It never reads caller storage itself.

func (*Harness) RunAgent

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

func (*Harness) RunTeam

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

func (*Harness) RunWorkflow

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

func (*Harness) Sanitize

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

func (*Harness) Team added in v0.2.0

func (h *Harness) Team(name string) (*workflow.Team, bool)

func (*Harness) ToolRegistry

func (h *Harness) ToolRegistry() *tool.Registry

func (*Harness) ValidateInput

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

func (*Harness) ValidateOutput

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

func (*Harness) Workflow added in v0.2.0

func (h *Harness) Workflow(name string) (*workflow.Workflow, bool)

type MCPClientConfig

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

type MemoryConfig

type MemoryConfig struct {
	Type     string `json:"type"` // buffer; reserved for future memory implementations
	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)

func (ModelConfig) BuildModelWithLogger added in v0.3.1

func (c ModelConfig) BuildModelWithLogger(logger *slog.Logger) (model.Model, error)

BuildModelWithLogger builds a model using the application-owned logger. The same logger is propagated to the protocol adapter and the model I/O wrapper, so dynamically selected models use the same logging pipeline as Harness, Agent, tools and MCP clients.

type Option added in v0.2.0

type Option func(*harnessOptions)

Option customizes Harness dependencies without changing the serializable Config format.

func WithInputValidator added in v0.2.0

func WithInputValidator(validator security.InputValidator) Option

func WithLogger added in v0.3.0

func WithLogger(logger *slog.Logger) Option

WithLogger injects the application logger without changing slog.Default.

func WithMCPClient added in v0.3.0

func WithMCPClient(name string, client *mcp.Client) Option

WithMCPClient injects a preconfigured public MCP client. It is useful when authentication, custom TLS, proxies, or another HTTP transport must be configured programmatically instead of stored in JSON. An injected client replaces a configured client with the same name.

func WithModel added in v0.3.0

func WithModel(runtimeModel model.Model) Option

WithModel injects a preconfigured default Model. This is useful for custom HTTP transports, provider wrappers, tests, and application-owned retry policies. The serializable model configuration is still validated.

func WithOutputValidator added in v0.2.0

func WithOutputValidator(validator security.OutputValidator) Option

func WithPermissionManager added in v0.2.0

func WithPermissionManager(manager security.PermissionManager) Option

func WithSanitizer added in v0.2.0

func WithSanitizer(sanitizer security.Sanitizer) Option

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

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

Task is an in-memory runtime for one caller-owned task ID. It has no storage or network transport responsibility; applications provide those concerns by consuming EventSink events and returning required acknowledgements.

func (*Task) AnswerInteraction added in v0.3.0

func (t *Task) AnswerInteraction(ctx context.Context, requestID string, answers map[string][]string) error

AnswerInteraction acknowledges and delivers a response to a waiting turn.

func (*Task) CancelTurn added in v0.3.0

func (t *Task) CancelTurn(_ context.Context, turnID string) error

CancelTurn explicitly cancels a background turn.

func (*Task) Close added in v0.3.0

func (t *Task) Close()

Close cancels active turns and releases only in-memory task state.

func (*Task) StartAgent added in v0.3.0

func (t *Task) StartAgent(ctx context.Context, agentName, input string, options ...engine.RunOption) (*taskpkg.Turn, error)

StartAgent starts one Agent turn and returns immediately after the required start events have been acknowledged.

func (*Task) StartTeam added in v0.3.0

func (t *Task) StartTeam(ctx context.Context, teamName, input string) (*taskpkg.Turn, error)

StartTeam starts one Team turn asynchronously.

func (*Task) StartWorkflow added in v0.3.0

func (t *Task) StartWorkflow(ctx context.Context, workflowName, input string) (*taskpkg.Turn, error)

StartWorkflow starts one Workflow turn asynchronously.

func (*Task) TaskID added in v0.3.0

func (t *Task) TaskID() string

TaskID returns the caller-owned identifier of this runtime instance.

func (*Task) WaitTurn added in v0.3.0

func (t *Task) WaitTurn(ctx context.Context, turnID string) (*taskpkg.Result, error)

WaitTurn waits for one turn without affecting its lifecycle when the caller stops waiting.

Directories

Path Synopsis
cmd
jd-cs-service command
Package engine implements Agent execution, bounded tool-call loops, streaming, per-Agent Tool scopes, and per-run options.
Package engine implements Agent execution, bounded tool-call loops, streaming, per-Agent Tool scopes, and per-run options.
examples
jdcs
Package jdcs demonstrates a customer-service application built exclusively from tracklogic-agent's public packages.
Package jdcs demonstrates a customer-service application built exclusively from tracklogic-agent's public packages.
Package interaction defines provider-neutral requests and responses for pausing an Agent turn while an application collects user input.
Package interaction defines provider-neutral requests and responses for pausing an Agent turn while an application collects user input.
Package mcp implements a public Model Context Protocol client and converts remote MCP tools into tracklogic-agent model tool definitions.
Package mcp implements a public Model Context Protocol client and converts remote MCP tools into tracklogic-agent model tool definitions.
Package memory defines conversation memory and provides a concurrent buffer implementation.
Package memory defines conversation memory and provides a concurrent buffer implementation.
Package model defines the model abstraction and built-in OpenAI, Anthropic, Chat Completions, and mock implementations.
Package model defines the model abstraction and built-in OpenAI, Anthropic, Chat Completions, and mock implementations.
Package security defines replaceable permission, validation, and sanitizing components together with default in-memory implementations.
Package security defines replaceable permission, validation, and sanitizing components together with default in-memory implementations.
Package task defines the protocol-neutral Task, Turn, Item, event, and checkpoint contracts used by applications that host the Harness behind a desktop, web, IDE, or service boundary.
Package task defines the protocol-neutral Task, Turn, Item, event, and checkpoint contracts used by applications that host the Harness behind a desktop, web, IDE, or service boundary.
Package tool defines executable Agent tools and a concurrent registry.
Package tool defines executable Agent tools and a concurrent registry.
builtin
Package builtin provides bounded general-purpose tools for files, HTTP, JSON, calculation, directories, and time.
Package builtin provides bounded general-purpose tools for files, HTTP, JSON, calculation, directories, and time.
Package types contains stable protocol values shared across the model, memory, security, and engine layers.
Package types contains stable protocol values shared across the model, memory, security, and engine layers.
Package workflow composes engine Agents into validated teams and stateful workflows.
Package workflow composes engine Agents into validated teams and stateful workflows.

Jump to

Keyboard shortcuts

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