Docs/Ecosystem/AI Kit: Modular Go AI SDK

AI Kit: Modular Go AI SDK

Build AI features in Go with AI Kit: 13 modules covering five providers, streaming, tools, stateful agents, stdlib MCP, chat bots, testing, and evals.

github.com/fletchhq/aikit

aikitpkg.go.devaikit/agentpkg.go.devaikit/mcppkg.go.devaikit/evalpkg.go.dev

Updated 2026-12-06 fletch docs show aikit/ai 11 min read

On this page

AI Kit (github.com/fletchhq/aikit) is a 13-module Go AI SDK for text and structured object generation, streaming, tool calling, stateful agents, MCP servers and clients, chat-platform bots, observability, testing, and evals. Everything builds pure Go with CGO_ENABLED=0 and zero Node.

Introduction

Most AI libraries pull every vendor SDK, tracing dependency, and web framework into one monolithic package. AI Kit separates the core contracts from provider drivers, persistence, observability, and UI so your binary links only the parts you call.

Core aikit and aikit/mcp depend only on the Go standard library, and their exported APIs are frozen by TestAPIFreeze. AI Kit ships no baked-in model catalog or pricing table; pass model IDs and keys from your own app config so switching models never waits on a library release.

Installation and module layout

Install the root module and the provider or runtime modules you need:

go get github.com/fletchhq/aikit@v0.1.0
go get github.com/fletchhq/aikit/openai@v0.1.0

AI Kit ships as 13 Go modules. Several helper packages (schema, stream/vercel, stream/agui, aitest, airec, eval) live inside the root aikit module with zero external dependencies.

Module Dependencies Purpose
github.com/fletchhq/aikit Go stdlib Core Model contract, generation, streaming, tools, failover, middleware, vectors, plus schema, stream/vercel, stream/agui, aitest, airec, eval
github.com/fletchhq/aikit/mcp Go stdlib MCP server and client over stdio and Streamable HTTP, plus mcptest
github.com/fletchhq/aikit/mcp/conformance aikit/mcp + official Go MCP SDK Test-only wire-format conformance suite (never imported by apps)
github.com/fletchhq/aikit/openai aikit OpenAI Responses and Chat Completions, compatible endpoints, Azure OpenAI, embeddings, images, speech, transcription
github.com/fletchhq/aikit/anthropic aikit Anthropic Messages API, prompt caching, extended thinking, hosted tools
github.com/fletchhq/aikit/gemini aikit Gemini Generative Language API, responseSchema, Google Search grounding, embeddings
github.com/fletchhq/aikit/bedrock aikit, AWS SDK v2 Amazon Bedrock Runtime Converse and ConverseStream with SigV4
github.com/fletchhq/aikit/vertex aikit, aikit/gemini, x/oauth2 Gemini on Google Vertex AI over Application Default Credentials
github.com/fletchhq/aikit/obs aikit, OpenTelemetry OpenTelemetry GenAI spans, Prometheus metrics, PHI redaction
github.com/fletchhq/aikit/agent aikit + Fletch stdlib leaves Stateful agents, durable threads, approvals, Quiver turns, PubSub fan-out, CLI REPL, and agent/web
github.com/fletchhq/aikit/nock aikit/agent, nock SQLite and Postgres stores for agent threads, converse links, and vectors (ainock)
github.com/fletchhq/aikit/live aikit/agent, live, crest Zero-Node Crest and Live chat UI under strict CSP (ailive)
github.com/fletchhq/aikit/converse aikit/agent, quiver, router Slack, GitHub, Telegram, and web chat bots, plus conversetest

Generation, streaming, and structured output

Use aikit.GenerateText for buffered responses, aikit.StreamText for incremental iter.Seq2[aikit.Event, error] streams, and aikit.GenerateObject[T] for schema-validated Go structs. Build prompts with aikit.System, aikit.User, aikit.Assistant, aikit.ToolMessage, and aikit.Messages (supporting Text, Reasoning, Image, Audio, File, ToolCall, and ToolResult parts).

client := openai.New(cfg.AI.OpenAIKey)
model := client.Model(cfg.AI.Model)

res, err := aikit.GenerateText(ctx, model,
	aikit.Messages{
		aikit.System("Answer in plain English in under three sentences."),
		aikit.User("What does CGO_ENABLED=0 guarantee?"),
	},
	aikit.WithMaxTokens(256),
	aikit.WithTemperature(0.2),
)
if err != nil {
	return err
}
fmt.Println(res.Text())

Range over aikit.StreamText to handle incremental events (aikit.TextDelta, aikit.ReasoningDelta, aikit.ToolCallStart, aikit.ToolCallDelta, aikit.ToolCallEnd, aikit.ToolCallError, aikit.Finish), or drain the stream into an *aikit.Response with aikit.Collect(events). Breaking out of the range loop cancels the run.

Core options and multimodal helpers

Option Behavior
WithSystem, WithMaxTokens, WithTemperature Sets system instruction, token cap, and sampling temperature
WithReasoning Configures reasoning / extended thinking via aikit.ReasoningOptions{Effort, BudgetTokens}
WithCache Marks prompt-cache breakpoints (CacheSystem, CacheTools, CacheHistory, combined with |)
WithTools, WithToolChoice, WithMaxSteps Registers tools, controls selection, and caps tool-loop iterations
WithMiddleware, WithObserver, WithApprover Attaches middleware (Budget, Guard, Redact, RouteModel), observers, and tool approvers
WithRepair Retries invalid structured output by sending the validation error back to the model
WithContentCapture Opts into sending prompt and answer text to observers (off by default)
WithDimensions, WithEmbedTask Configures embedding vector size and task type (EmbedOption)
WithVoice, WithAudioFormat, WithSpeechInstructions Configures speech synthesis (SpeechOption)
WithLanguage, WithFilename Configures audio transcription (TranscribeOption)

Match errors with errors.Is (aikit.ErrRateLimited, aikit.ErrInvalidRequest) and errors.As (*aikit.ProviderError, *aikit.SchemaError, *aikit.GuardrailError, *aikit.StatusError). Wrap backup models with aikit.Failover(primary, fallbacks...), which switches only on aikit.Failoverable(err) and never after content has streamed.

Tools and JSON Schema (aikit/schema)

Define typed tools with aikit.NewTool[In, Out] and mark them with aikit.ReadOnly(), aikit.Destructive(), or aikit.RequireApproval() (pair RequireApproval() with aikit.WithApprover).

github.com/fletchhq/aikit/schema generates and caches strict JSON Schemas from Go struct tags (json, validate with min/max/oneof/required, and desc) using the same validation rules as fletch gen openapi:

  • schema.For[T]() and schema.Of(reflect.Type) return a cached strict *schema.Schema (all properties required, optional fields nullable, additionalProperties: false).
  • schema.New(name, rawJSON) wraps a hand-written JSON Schema.
  • schema.Generate(t, schema.Options{Strict: bool}) builds a schema map directly, handling recursive types under $defs.

Provider drivers

The OpenAI, Anthropic, and Gemini drivers talk directly over Go's net/http with zero third-party SDKs. Bedrock and Vertex integrate with AWS and Google Cloud auth.

m := openai.New(cfg.AI.OpenAIKey).Model(cfg.AI.Model)
m := anthropic.New(cfg.AI.AnthropicKey).Model(cfg.AI.Model)
m := gemini.New(cfg.AI.GeminiKey).Model(cfg.AI.Model)
awsCfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
	return err
}
m := bedrock.New(bedrockruntime.NewFromConfig(awsCfg)).Model(cfg.AI.Model)
vc, err := vertex.New(ctx, cfg.GCP.Project, cfg.GCP.Location)
if err != nil {
	return err
}
m := vc.Model(cfg.AI.Model)
  • aikit/bedrock calls Bedrock Runtime Converse and ConverseStream with SigV4 signing (bedrock.Provider = "bedrock", bedrock.DefaultMaxTokens = 4096).
  • aikit/vertex reuses aikit/gemini wire codecs over Google Application Default Credentials (vertex.Scope = "https://www.googleapis.com/auth/cloud-platform"). It keeps provider name "gemini" so Request.Provider["gemini"] options and Gemini hosted tools work unchanged. For custom tokens or endpoints, use vertex.NewWithTokenSource, vertex.WithBaseURL, vertex.WithTransport, and vertex.BaseURL.

Frontend streaming (stream/vercel and stream/agui)

Both browser stream encoders live in the stdlib-only root aikit module and consume iter.Seq2[aikit.Event, error] directly.

func streamHandler(w http.ResponseWriter, r *http.Request) {
	events := aikit.StreamText(r.Context(), model, aikit.User(prompt))
	if err := vercel.Encode(vercel.NewSink(w), events, vercel.WithMessageID(msgID)); err != nil {
		slog.Error("ai stream", "err", err)
	}
}
func aguiHandler(w http.ResponseWriter, r *http.Request) {
	events := aikit.StreamText(r.Context(), model, aikit.User(prompt))
	if err := agui.Encode(agui.NewSink(w), events, agui.WithRunID(runID), agui.WithThreadID(threadID)); err != nil {
		slog.Error("agui stream", "err", err)
	}
}

vercel.NewSink(w) applies vercel.Headers and writes the final [DONE] marker. agui.NewSink(w) applies agui.Headers and streams AG-UI SSE events.

Stateful agents, persistence, and chat UI

AI Kit splits stateful agent execution into four composable pieces: aikit/agent, aikit/nock, aikit/agent/web, and aikit/live.

Defining and running an agent (aikit/agent)

Construct an *agent.Agent once with agent.New(name, model, opts...). It is immutable and safe to share across goroutines.

store := ainock.Store(db)

assistant, err := agent.New("support", model,
	agent.WithInstructions("Answer billing questions and check order status."),
	agent.WithTools(lookupOrder, refundCharge),
	agent.WithStore(store),
	agent.WithApprovals(agent.RequireApprovalFor("refund_charge")),
	agent.WithAudit(auditRecorder),
	agent.WithEvents(broker),
	agent.WithMaxSteps(10),
)
if err != nil {
	return err
}

Configuration options include WithInstructions, WithInstructionsFunc, WithTools, WithSubAgents, WithStore, WithMiddleware (including agent.Summarize(after, summaryModel) for thread compaction), WithBudget, WithGuardrails, WithApprovals (requires WithStore), WithAudit (tool.called, approval.requested, approval.resolved, guardrail.tripped, budget.stopped), WithEvents, WithMaxSteps (DefaultMaxSteps = 10), and WithObserver.

Agent turn methods cover synchronous, streaming, resumable, and queued execution:

Method Purpose
Run(ctx, threadID, in) Runs a turn synchronously to completion or an approval pause
Stream(ctx, threadID, in) Streams turn events live
Begin, Follow, Watch Starts a turn, tails recorded events, and watches live turn updates
Resume, ResumeStream, ResumeJob Continues a paused turn after approvals are resolved (sync, streaming, or inside a worker)
Enqueue, EnqueueTx, EnqueueResume Runs or resumes turns asynchronously on a Quiver queue (register workers with agent.Register(q, a), using agent.RunJob)

Approvals and CLI REPL

Human-in-the-loop approvals pause a turn before gated tools run and survive process restarts:

  1. Gate tools with agent.RequireApprovalFor(names...) or a custom agent.ApprovalPolicyFunc.
  2. Compute the ID with agent.ApprovalID(turn, callID).
  3. Resolve with agent.Resolve(ctx, store, approvalID, decision) using agent.Approve(), agent.Reject(reason), or agent.Edit(args) (tagged with Decision.By).
  4. Check agent.Ready(ctx, store, turn), then resume via a.Resume, a.ResumeStream, or a.EnqueueResume.

Attach agent.Commands(agents...) to your app CLI to get an interactive ai chat [agent] REPL supporting streaming deltas, y/n/e approval prompts, and --thread resumption.

Persistence and vectors (aikit/nock)

github.com/fletchhq/aikit/nock (package ainock) backs ThreadStore and EventLog on SQLite and Postgres across five tables (ai_threads, ai_messages, ai_turns, ai_turn_events, ai_approvals), with agent.MemoryStore() available for tests. Include ainock.Tables (or ainock.SchemaSource) in your Nock schema, emit DDL with ainock.SQL(dialect), or call ainock.CreateTables(ctx, db).

For retrieval and RAG, core aikit defines VectorStore (Upsert, Query, Delete), VectorDoc, VectorHit, and aikit.SimilaritySearch(store, embedder, ns, k) (a read-only aikit.Tool). ainock.Vectors(db, dim) stores vectors in ai_vectors using Postgres pgvector HNSW indexes (ColumnDef.Vector(dim) + TableDef.IndexUsing) or exact cosine scans on SQLite (ainock.VectorTable, ainock.VectorSQL, ainock.CreateVectorTable).

HTTP endpoints (aikit/agent/web) and Live UI (aikit/live)

Expose an agent over HTTP and SSE (defaulting to web.Vercel, with web.AGUI also supported) via web.Handler(a, opts...):

r.Mount("/api/chat", http.StripPrefix("/api/chat", web.Handler(
	assistant,
	web.WithAuthorize(canApprove),
)))
chatHandler := live.New(
	ailive.New(assistant, ailive.WithAuthorize(canApprove)),
	live.WithNonce(nonce),
)

web.Handler serves POST / (start and stream), GET /turns/{turn}/events (replay and follow with Last-Event-ID), and POST /turns/{turn}/approvals/{call} (resolve and stream resumed turn), with options WithAuthorize, WithThreadAccess, and WithShutdown.

ailive renders server-side Crest components (Chat, Message, ToolActivity, ApprovalCard) under strict CSP with zero Node, batching deltas into ~30 ms frames (ailive.DefaultFrame) and recovering in-progress turns across reloads (WithAuthorize, WithActor, WithThread, WithThreadAccess, WithFrame, WithStart, WithResume).

Model Context Protocol (aikit/mcp)

github.com/fletchhq/aikit/mcp implements MCP servers and clients using only the Go standard library (it does not even import root aikit). It targets mcp.LatestProtocol ("2026-07-28") and negotiates fallback revisions ("2025-11-25", "2025-06-18", "2025-03-26", listed by mcp.SupportedProtocols()).

Because mcp.ToolHandler has the exact same method set as aikit.Tool, tools move in both directions with zero adapters: aikit.NewTool[In, Out] passes straight to mcp.WithTools(...), and client.Tools(ctx) returns []*mcp.RemoteTool ready for aikit.WithTools(...).

srv := mcp.NewServer("billing", "1.0.0",
	mcp.WithTools(lookupInvoice),
	mcp.WithAllowedOrigins("https://app.example.com"),
	mcp.WithAuthenticator(verifyBearerToken),
	mcp.WithVisible(func(ctx context.Context, name string) bool {
		return canSeeTool(ctx, name)
	}),
)
r.Mount("/mcp", srv.Handler())
// Or serve stdio in a CLI command: srv.ServeStdio(ctx, os.Stdin, os.Stdout)
client, err := mcp.Dial(ctx, "https://mcp.example.com/mcp",
	mcp.WithBearer(fetchBearerToken),
	mcp.WithClientInfo("my-app", "1.0.0"),
)
if err != nil {
	return err
}
defer client.Close()

tools, err := client.Tools(ctx)
  • Server options & tool seams: WithTools, WithResources, WithResourceTemplates, WithPrompts, WithVisible, WithAllowedOrigins, WithAuthenticator, WithProtectedResource (paired with srv.ProtectedResourceHandler() at /.well-known/oauth-protected-resource). Tools may also implement ToolOutputSchema, ToolAnnotated, and ToolAuthorizer.
  • Client constructors & methods: mcp.Dial (Streamable HTTP), mcp.Exec (stdio subprocess), and mcp.Connect (existing io.Reader/io.Writer), with WithBearer, WithClientInfo, WithHTTPClient, WithProtocolVersion. Methods: Tools, CallTool, Resources, ResourceTemplates, ReadResource, Prompts, GetPrompt, Info, Close. Errors: ErrNotFound, *ToolError, *RPCError, *HTTPError, *InsufficientScopeError.
  • Testing & CLI inspection: aikit/mcp/mcptest tests servers in process (NewClient, Call, ReadResource, GetPrompt, Transcript with MCPTEST_UPDATE=1). Inspect any live HTTP or stdio server from your terminal with fletch mcp inspect <url> or fletch mcp inspect -- ./bin/my-mcp-server.

Chat-platform bots (aikit/converse)

github.com/fletchhq/aikit/converse wires an *agent.Agent to Slack, GitHub, Telegram, and web chat over HTTP webhooks. Incoming webhooks are verified, acknowledged immediately, and enqueued as converse.TurnJob on Quiver with 24-hour message deduplication (converse.DedupeWindow) and *converse.RateLimitError snoozing.

bot, err := converse.New("support",
	converse.Agent(assistant),
	converse.Connect(
		web.New(userFunc),
		slack.New(slack.Config{ /* ... */ }),
	),
	converse.WithQueue(q),
	converse.WithStore(ainock.Links(db)),
)
if err != nil {
	return err
}
bot.Mount(r) // registers POST /converse/<connector>
  • Options: Agent, Select (dynamic agent selection per message), Connect, WithQueue, WithStore (MemoryLinks() or ainock.Links(db)), WithPrefix, Link, WithIdentity.
  • Connectors: converse/web (browser JSON POST + in-memory outbox), converse/slack (X-Slack-Signature, Block Kit approval buttons), converse/github (X-Hub-Signature-256, issue comments, /approve//reject//edit), and converse/telegram (secret_token, inline keyboard approvals). Optional connector capabilities: Editor, Reactor, Typing, FileReceiver (MaxFileSize = 10 MiB), Approvals.
  • Identity linking: converse.NewLinker(secret, baseURL, converse.LinkTTL(15*time.Minute)) (DefaultLinkTTL = 15m) issues signed URLs (linker.URL, linker.Handler) binding platform accounts to app users (unlinked approval attempts return converse.ErrNotLinked).
  • Testing: aikit/converse/conversetest drives the full webhook-to-Quiver loop offline (Fake, Deliver, Drain, Press, TextOnly, AssertSent).

Observability and dev recording (aikit/obs and aikit/airec)

Only github.com/fletchhq/aikit/obs imports OpenTelemetry. It emits GenAI semantic-convention spans (chat <model>, execute_tool <name> under obs.ScopeName) and Prometheus metrics:

metrics := obs.NewMetrics()
observer := obs.NewObserver(tracerProvider,
	obs.WithMetrics(metrics),
	obs.WithContentRedactor(obs.PHIRedactor()),
)
mux.Handle("/metrics", metrics)

Prompts and outputs stay out of traces unless a call opts in with aikit.WithContentCapture(), and every captured string passes through WithContentRedactor (defaulting to obs.PHIRedactor()). Use obs.WithErrorRedactor to scrub error text as well.

During local development, attach rec := airec.New(100) (github.com/fletchhq/aikit/airec, optional airec.WithPricing(p)) as an observer and register {ID: "ai", Title: "AI", Data: rec.Panel, Action: rec.Action} on Fletch's Dev Dashboard. rec.Approver() provides an interactive dev approver directly in the dashboard.

Testing and evals (aikit/aitest and aikit/eval)

Unit tests and cassettes (aikit/aitest)

Use aitest.NewModel(replies...) to script deterministic turns without hitting live APIs:

func TestOrderSupport(t *testing.T) {
	m := aitest.NewModel(
		aitest.CallTool("lookup_order", `{"order_id":"ord_123"}`),
		aitest.Text("Order ord_123 shipped yesterday."),
	)

	answer, err := runSupport(t.Context(), m, "Where is order ord_123?")
	if err != nil {
		t.Fatal(err)
	}
	if answer != "Order ord_123 shipped yesterday." {
		t.Fatalf("got %q", answer)
	}

	aitest.AssertToolCalled(t, m, "lookup_order", aitest.ArgsEqual(`{"order_id":"ord_123"}`))
	aitest.AssertPrompted(t, m, aitest.Contains("ord_123"))
}

Reply builders include aitest.Text, aitest.CallTool, aitest.Object, aitest.Error, aitest.Func, and aitest.Fail, with m.As(provider, id) for failover tests. For recorded HTTP fixtures, pass aitest.NewCassette(t, path).Client() to a provider's HTTP client option and run with AI_RECORD=1 to refresh fixtures. Verify custom aikit.Model implementations with aitest.ModelContract.

Evals (aikit/eval)

Put token-spending quality checks in *_eval_test.go behind //go:build eval:

//go:build eval

func TestRefundPolicy(t *testing.T) {
	eval.Run(t,
		eval.Model(assistant),
		eval.Cases{
			{
				Name:   "expired_window",
				Input:  "I want a refund for a 45-day-old order.",
				Expect: eval.Rubric("declines the refund and cites the 30-day policy"),
			},
		},
		eval.Judge(judgeModel),
		eval.Threshold(0.8),
		eval.Repeat(3),
	)
}

eval.Target wraps any model (eval.Model), agent, or function (eval.Func). Expectations (eval.Expectation) include eval.Rubric (graded by eval.Judge, returning eval.ErrNoJudge if omitted), eval.Contains, and custom eval.CheckFunc functions returning an eval.Score.

eval.Evaluate and eval.Run return a *eval.Report (rep.Passed(), Cases []eval.CaseResult, Attempts []eval.Attempt) using eval.DefaultThreshold (0.8). When eval.ReportDirEnv ("FLETCH_EVAL_REPORT_DIR") is set, eval.Run writes JSON reports there automatically.

Run evals and check regressions from the Fletch CLI, or scaffold new AI components directly:

fletch test --evals --tolerance 0.05
fletch new support-bot --template agent
fletch make agent Support --module assistant
fletch make tool LookupOrder --module assistant
fletch make eval RefundPolicy --module assistant
fletch make mcp-server Billing --module assistant