agent

package module
v0.2.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 公共库。根包 agent 提供 Harness 与配置入口;enginemodelmemorytoolsecuritytypesworkflowmcp 是职责独立的公共扩展包。

项目同时包含《智能体 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 := harness.NewAgent("assistant", "你是一个简洁、可靠的助手。")
    result := assistant.Run(context.Background(), "你好",
        engine.WithMaxLoops(5),
        engine.WithTemperature(0.2),
    )
    if !result.Success {
        log.Fatal(result.Error)
    }
    fmt.Println(result.Content)
}

公共扩展包

  • engine:Agent、执行循环、流式输出和运行选项。
  • model:Model 接口及 OpenAI、Chat Completions、Anthropic、Mock 实现。
  • memory:Memory 接口和并发安全的 BufferMemory。
  • 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 推断。

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 教程

教程与测试

教程入口为 docs/01-introduction.md

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 (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)

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) 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

func (*Harness) NewTeam

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

func (*Harness) NewWorkflow

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

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) 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"`
}

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 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 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"`
}

Directories

Path Synopsis
cmd
jd-cs-service command
Package engine implements Agent execution, tool-call loops, streaming, and per-run options.
Package engine implements Agent execution, tool-call loops, streaming, 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 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 tool defines executable Agent tools and a concurrent registry.
Package tool defines executable Agent tools and a concurrent registry.
builtin
Package builtin provides general-purpose tools for files, HTTP, JSON, calculation, directories, and time.
Package builtin provides 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 teams and stateful workflows.
Package workflow composes engine Agents into teams and stateful workflows.

Jump to

Keyboard shortcuts

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