Help us shape the future of Go! Take the 2026 Go Developer Survey

gogentic

module
v0.21.168 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0

README

gogentic

Agentic LLM applications in Go.

gogentic is a library for building LLM agents: assistants that call tools, hand work to other assistants, produce typed results, and run against any of a dozen providers behind one interface. It is used in production and its API is stable.

It began as a fork of langchaingo, and has since diverged around stronger tool/assistant abstractions, schema generation, Agent Skills, MCP, and multi-tenant model routing.

go get github.com/effective-security/gogentic

What it gives you

Capability Package Details
Agent loop with parallel tool calling, limits and retries assistants Assistants
Typed, schema-validated results encoding, pkg/schema Structured Output
Tools with generated JSON Schema parameters tools Tools
Multi-agent delegation (an assistant is a tool) assistants Orchestration
One config for OpenAI, Anthropic, Azure, Bedrock, Google AI, OpenRouter, Perplexity, Cloudflare pkg/llmfactory, pkg/llms LLM Factory, LLM Providers
Per-assistant and per-organization model routing, capability filtering, quota hooks pkg/llmfactory Model resolution
Agent Skills (SKILL.md) with progressive disclosure skills Skills
MCP server and client, with stdio / HTTP / SSE / in-process transports mcp MCP
Chat history in memory or Redis, multi-tenant store, chatmodel Memory
Prompt templates: Go template, Jinja2, f-string, few-shot pkg/prompts Prompts
Callbacks, per-run transcripts and stats, Prometheus-ready metrics callbacks, pkg/metricskey Observability
Provider-native prompt caching and Batch APIs pkg/llms Prompt caching, Batch

Quick start

1. Describe your providers in llm.yaml:

default_provider: OPENAI
providers:
  - name: OPENAI
    token: env://OPENAI_API_KEY
    default_model: gpt-5.1
    available_models: [gpt-5.1, gpt-5.1-mini]
    open_ai:
      api_type: OPENAI
assistant_models:
  default: [OPENAI/gpt-5.1]
  researcher: [OPENAI/gpt-5.1]

2. Define the shape of the answer and run an assistant:

package main

import (
    "context"
    "fmt"

    "github.com/effective-security/gogentic/assistants"
    "github.com/effective-security/gogentic/chatmodel"
    "github.com/effective-security/gogentic/pkg/llmfactory"
    "github.com/effective-security/gogentic/pkg/llmutils"
    "github.com/effective-security/gogentic/pkg/prompts"
    "github.com/effective-security/gogentic/store"
)

// The output type: jsonschema tags are the model's instructions.
type Answer struct {
    Text    string   `json:"text"    jsonschema:"required,title=Text,description=The answer."`
    Sources []string `json:"sources" jsonschema:"title=Sources,description=URLs backing the answer."`
}

func (a Answer) GetContent() string { return llmutils.ToJSON(a) }

func main() {
    fac, err := llmfactory.Load("llm.yaml")
    if err != nil {
        panic(err)
    }

    agent := assistants.NewAssistant[Answer](fac,
        prompts.NewPromptTemplate("You are a concise research assistant.", nil),
        assistants.WithMessageStore(store.NewMemoryStore()),
    ).
        WithName("researcher"). // binds to assistant_models.researcher
        WithDescription("Answers factual questions and cites sources.")

    // Every run needs a ChatContext: user/org/chat/run identity.
    chatCtx := chatmodel.NewChatContext("user-123", "", nil)
    ctx := chatmodel.WithChatContext(context.Background(), chatCtx)

    var out Answer
    resp, err := agent.Run(ctx, &assistants.CallInput{
        Input: "What is the capital of the largest country in Europe?",
    }, &out)
    if err != nil {
        panic(err)
    }

    fmt.Println(out.Text)
    fmt.Println("tokens:", resp.Usage.ModelUsage)
}

Add a tool

A tool is a name, a description, a JSON Schema, and a string → string call. Keep the real logic in a typed Run and let Call adapt the model's JSON:

type Request struct {
    City string `json:"city" jsonschema:"required,title=City,description=City name."`
}

type Result struct {
    TempC float64 `json:"temp_c"`
}

func (r *Result) GetContent() string { return llmutils.ToJSON(r) }

type Tool struct{ params *jsonschema.Schema }

func New() (*Tool, error) {
    sc, err := schema.New(reflect.TypeOf(Request{}))
    if err != nil {
        return nil, errors.Wrap(err, "failed to create schema")
    }
    return &Tool{params: sc.Parameters}, nil
}

func (t *Tool) Name() string                   { return "get_weather" }
func (t *Tool) Description() string            { return "Current temperature for a city." }
func (t *Tool) Parameters() *jsonschema.Schema { return t.params }

func (t *Tool) Run(ctx context.Context, req *Request) (*Result, error) {
    return &Result{TempC: 21.5}, nil
}

func (t *Tool) Call(ctx context.Context, input string) (string, error) {
    var req Request
    if err := json.Unmarshal(llmutils.CleanJSON([]byte(input)), &req); err != nil {
        return "", errors.WithStack(chatmodel.ErrFailedUnmarshalInput)
    }
    out, err := t.Run(ctx, &req)
    if err != nil {
        return "", err
    }
    return out.GetContent(), nil
}
agent = agent.WithTools(weatherTool)

Tools requested in the same LLM turn run concurrently, and a tool error is handed back to the model rather than aborting the run. See Tools.

Orchestrate several agents

Wrap an assistant as a tool and give it to a supervisor. Context, callbacks and call options flow down; token usage rolls up.

researchTool, err := assistants.NewAssistantTool[chatmodel.InputRequest](researcher)
if err != nil {
    return err
}

supervisor := assistants.NewAssistant[chatmodel.OutputResult](fac, supervisorPrompt,
    assistants.WithCallback(callbacks.NewScratchpad(callbacks.ModeVerbose)),
    assistants.WithMaxToolCalls(8),
).
    WithName("supervisor").
    WithTools(researchTool, coderTool)

See Orchestration.

Expose it over MCP

tr := stdio.NewStdioServerTransport()
srv := mcp.NewServer(tr, mcp.WithName("my-agents"), mcp.WithVersion("1.0.0"))

if err := srv.Serve(); err != nil {
    return err
}
if err := researcher.RegisterMCP(srv); err != nil { // as an MCP prompt
    return err
}
if err := weatherTool.RegisterMCP(srv); err != nil { // as an MCP tool
    return err
}
if err := tr.Start(ctx); err != nil {
    return err
}

See MCP.

Load skills from disk

Drop SKILL.md files in a directory; only their names and descriptions enter the prompt, and the model loads full instructions on demand via activate_skill.

skills:
  enable_default_skills: true
  paths: [./skills]
agent = agent.WithSkills(fac.Skills("researcher"))

See Skills.

Documentation

Full documentation is in Documentation/:

Package-level godoc is available for every package: go doc github.com/effective-security/gogentic/assistants.

Contributing

make generate   # regenerate mocks for changed interfaces
make test       # run the suite
make lint       # final check

Read AGENTS.md for error handling, testing and documentation conventions, and Documentation/codemap.md for the invariants the agent loop depends on.

See ROADMAP.md for planned work.

License

Apache 2.0

Directories

Path Synopsis
Package assistants provides the core agent loop: system prompt assembly, LLM invocation, parallel tool calling, structured output parsing, callbacks and message history.
Package assistants provides the core agent loop: system prompt assembly, LLM invocation, parallel tool calling, structured output parsing, callbacks and message history.
Package callbacks provides implementations of the assistant and tool callback interfaces for tracing, logging and per-run accounting.
Package callbacks provides implementations of the assistant and tool callback interfaces for tracing, logging and per-run accounting.
Package chatmodel defines common chat I/O types, context helpers, and parser interfaces used across the project.
Package chatmodel defines common chat I/O types, context helpers, and parser interfaces used across the project.
Package encoding provides a pluggable framework to describe, encode and decode structured data for agentic flows.
Package encoding provides a pluggable framework to describe, encode and decode structured data for agentic flows.
dummy
Package dummy encoder/decoder
Package dummy encoder/decoder
json
Package json json encoder/decoder
Package json json encoder/decoder
toml
Package toml encoder/decoder
Package toml encoder/decoder
yaml
Package yaml encoder/decoder
Package yaml encoder/decoder
mcp
Package mcp implements the Model Context Protocol client and server, with pluggable transports (stdio, HTTP, SSE, in-process).
Package mcp implements the Model Context Protocol client and server, with pluggable transports (stdio, HTTP, SSE, in-process).
internal/protocol
This file implements the core protocol layer for JSON-RPC communication in the MCP SDK.
This file implements the core protocol layer for JSON-RPC communication in the MCP SDK.
transport
Package transport defines the minimal interfaces and shared types for MCP transports used by the client and server.
Package transport defines the minimal interfaces and shared types for MCP transports used by the client and server.
transport/httptransport
Package httptransport implements stateless HTTP transports for MCP: a server transport that accepts JSON-RPC requests on an endpoint, and a client transport that posts them.
Package httptransport implements stateless HTTP transports for MCP: a server transport that accepts JSON-RPC requests on an endpoint, and a client transport that posts them.
transport/localtransport
Package localtransport implements local transport mechanisms for MCP, enabling efficient in-process and local communication for agentic flows.
Package localtransport implements local transport mechanisms for MCP, enabling efficient in-process and local communication for agentic flows.
transport/sse
Package sse implements Server-Sent Events (SSE) transport for MCP, enabling real-time, bidirectional communication for agentic flows over HTTP.
Package sse implements Server-Sent Events (SSE) transport for MCP, enabling real-time, bidirectional communication for agentic flows over HTTP.
transport/sse/internal/sse
Package sse provides the low-level implementation of Server-Sent Events (SSE) transport for MCP, handling connection management, message streaming, and protocol details.
Package sse provides the low-level implementation of Server-Sent Events (SSE) transport for MCP, handling connection management, message streaming, and protocol details.
transport/stdio
Package stdio implements the MCP stdio transport, used by servers that are launched as a subprocess by an MCP host and exchange newline-delimited JSON-RPC frames over standard input and output.
Package stdio implements the MCP stdio transport, used by servers that are launched as a subprocess by an MCP host and exchange newline-delimited JSON-RPC frames over standard input and output.
transport/stdio/internal/stdio
This file implements the stdio transport layer for JSON-RPC communication.
This file implements the stdio transport layer for JSON-RPC communication.
Package mocks provides mock implementations of assistants, tools, and LLMs for testing and development purposes.
Package mocks provides mock implementations of assistants, tools, and LLMs for testing and development purposes.
mockassitants
Package mockassitants is a generated GoMock package.
Package mockassitants is a generated GoMock package.
mockllmfactory
Package mockllmfactory is a generated GoMock package.
Package mockllmfactory is a generated GoMock package.
mockllms
Package mockllms is a generated GoMock package.
Package mockllms is a generated GoMock package.
mockrouter
Package mockrouter provides generated mocks for semantic selection tests.
Package mockrouter provides generated mocks for semantic selection tests.
mocktools
Package mocktools is a generated GoMock package.
Package mocktools is a generated GoMock package.
pkg
llmfactory
Package llmfactory constructs provider models from configuration, resolves assistant→model preferences (with optional per-organization overrides), and supports capability filtering and per-org model restrictions.
Package llmfactory constructs provider models from configuration, resolves assistant→model preferences (with optional per-organization overrides), and supports capability filtering and per-org model restrictions.
llms
Package llms provides unified support for interacting with different Language Models (LLMs) from various providers.
Package llms provides unified support for interacting with different Language Models (LLMs) from various providers.
llms/anthropic
Package anthropic implements the Anthropic (Claude) llms.Model with options for API key, model selection, and custom HTTP client or AWS config when used via Bedrock (see NewBedrock in this package).
Package anthropic implements the Anthropic (Claude) llms.Model with options for API key, model selection, and custom HTTP client or AWS config when used via Bedrock (see NewBedrock in this package).
llms/bedrock
Package bedrock implements an llms.Model backed by AWS Bedrock.
Package bedrock implements an llms.Model backed by AWS Bedrock.
llms/cloudflare
Package cloudflare implements an llms.Model for Cloudflare AI Gateway and compatible APIs.
Package cloudflare implements an llms.Model for Cloudflare AI Gateway and compatible APIs.
llms/googleai
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers.
Package googleai implements Google AI (Vertex/Gemini) llms.Model wrappers.
llms/googleai/internal/cmd command
Code generator for vertex.go from googleai.go nolint
Code generator for vertex.go from googleai.go nolint
llms/openai
Package openai provides an llms.Model implementation for OpenAI-compatible APIs, including OpenAI and Azure OpenAI endpoints.
Package openai provides an llms.Model implementation for OpenAI-compatible APIs, including OpenAI and Azure OpenAI endpoints.
llmutils
Package llmutils provides utilities for formatting prompts, cleaning model outputs, rendering data as JSON/YAML/markdown, and inspecting chat messages.
Package llmutils provides utilities for formatting prompts, cleaning model outputs, rendering data as JSON/YAML/markdown, and inspecting chat messages.
metricskey
Package metricskey declares the metric descriptors emitted by the assistant loop, for use with github.com/effective-security/metrics.
Package metricskey declares the metric descriptors emitted by the assistant loop, for use with github.com/effective-security/metrics.
prompts
Package prompts contains prompt templates and utilities for working with LLMs.
Package prompts contains prompt templates and utilities for working with LLMs.
prompts/internal/fstring
Package fstring contains template format with f-string.
Package fstring contains template format with f-string.
schema
Package schema provides helpers to generate JSON Schemas from Go types and shape those schemas for LLM prompting.
Package schema provides helpers to generate JSON Schemas from Go types and shape those schemas for LLM prompting.
Package router selects an authorized, compatible text model and performs one non-streaming inference.
Package router selects an authorized, compatible text model and performs one non-streaming inference.
dialect
Package dialect holds what the public API codecs share: decode and encode options, lenient/strict JSON object parsing with dialect-aware null handling, the sealed envelope for opaque reasoning state, and the mapping from router error kinds to HTTP status codes.
Package dialect holds what the public API codecs share: decode and encode options, lenient/strict JSON object parsing with dialect-aware null handling, the sealed envelope for opaque reasoning state, and the mapping from router error kinds to HTTP status codes.
dialect/anthropic
Package anthropic is the Anthropic Messages codec for the router.
Package anthropic is the Anthropic Messages codec for the router.
dialect/openai
Package openai translates the OpenAI Chat Completions and Responses request and response shapes to and from the portable router contract.
Package openai translates the OpenAI Chat Completions and Responses request and response shapes to and from the portable router contract.
Package skills implements the Agent Skills open standard (https://agentskills.io) for AI assistants.
Package skills implements the Agent Skills open standard (https://agentskills.io) for AI assistants.
Package store persists chat messages and chat metadata for agentic flows, with in-memory and Redis backends.
Package store persists chat messages and chat metadata for agentic flows, with in-memory and Redis backends.
Package tools defines the contract every tool implements so an LLM agent can call it: a name, a description injected into the prompt, a JSON Schema for the arguments, and a string-to-string call.
Package tools defines the contract every tool implements so an LLM agent can call it: a name, a description injected into the prompt, a JSON Schema for the arguments, and a string-to-string call.
tavily
Package tavily implements a web search tool backed by the Tavily API (https://docs.tavily.com), and serves as the reference implementation of the tools.ITool contract.
Package tavily implements a web search tool backed by the Tavily API (https://docs.tavily.com), and serves as the reference implementation of the tools.ITool contract.

Jump to

Keyboard shortcuts

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