go-llm-pipeline

module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT

README

go-llm-pipeline

An idiomatic, dependency-free Go toolkit for local-first, deterministic LLM orchestration and structured data extraction.

Overview

go-llm-pipeline provides statically typed pipelines for high-throughput, batch LLM workloads. It favors deterministic, VCR-style testing over live API calls, routes natively to local inference engines (Ollama) as well as hosted providers (OpenAI, Gemini), and processes generic assets through concurrent worker pools. It is a Go library with no server component and a light dependency footprint.

Installation

go get github.com/vmontagh/go-llm-pipeline

The module targets Go 1.26 (see go.mod).

Quick start

pkg/pipeline provides a generic worker-pool consumer. Consume starts a pool of workers that read from a channel, honor context cancellation, and run your process function for each item:

package main

import (
	"context"
	"fmt"
	"sync"

	"github.com/vmontagh/go-llm-pipeline/pkg/pipeline"
)

func main() {
	ctx := context.Background()

	input := make(chan int)
	go func() {
		defer close(input)
		for i := 0; i < 5; i++ {
			input <- i
		}
	}()

	var wg sync.WaitGroup
	pipeline.Consume(ctx, input, 3, &wg, func(ctx context.Context, n int) {
		fmt.Println("processed", n)
	})
	wg.Wait()
}

Consume also accepts options such as WithPauseGate to pause and resume processing at runtime.

Doctor diagnostics

pkg/doctor checks local environment readiness before batch jobs. It is exposed as a library API — not a repo-level binary — so consumer applications wire it into their own command surface (for example a doctor subcommand or a --dry-run preflight). A Runner executes a fixed set of checks and returns a Report of pass/warn/fail/skip Results; the doctor package never reads environment variables itself, so callers stay in control of credentials.

Checks:

  • OS file-descriptor soft limit against configurable floors.
  • Network latency/reachability to the OpenAI and Gemini hosted APIs.
  • OpenAI and Gemini API key validity.
  • Local Ollama reachability and installed-model listing, with an optional context-window preflight when a specific model is requested.
cfg := doctor.DefaultConfig()
cfg.OpenAIAPIKey = os.Getenv("OPENAI_API_KEY")
cfg.GeminiAPIKey = cmp.Or(os.Getenv("GEMINI_API_KEY"), os.Getenv("GOOGLE_API_KEY"))
cfg.OllamaHost = cmp.Or(os.Getenv("OLLAMA_HOST"), cfg.OllamaHost)

report := doctor.NewRunner(&cfg).Run(ctx)
report.Log(ctx, logger)   // pass/skip at INFO, warn at WARN, fail at ERROR
fmt.Print(report.String()) // or render a plain-text summary for a CLI

if report.HasFailure() {
	os.Exit(1) // hard failures should block batch jobs; warnings do not
}

Inject a custom *http.Client with doctor.WithHTTPClient (used in tests to avoid live network calls) and a doctor.FileLimitReader with doctor.WithFileLimitReader. Warnings never mark the report as failed, so borderline conditions surface without blocking automation.

Package map

Package Description
pkg/analyzer Template Method and Builder contracts for LLM analysis (Event/Analyzer, domain-agnostic Asset, sentinel errors).
pkg/pipeline Concurrency utilities: generic worker-pool Consume, PauseGate, and a dead-letter queue.
pkg/provider Concurrency-safe KeyPool of API credentials with per-key cooldown and rotation.
pkg/provider/openai Transport half of the analyzer Template Method for OpenAI.
pkg/provider/gemini Transport half of the analyzer Template Method for Gemini.
pkg/provider/ollama Transport half of the analyzer Template Method for local Ollama, plus a local Embedder (/api/embed) that returns []float64 for pkg/vectorstore.
pkg/strategy Ensemble generation and judge-synthesis strategies (Generator/Judge).
pkg/policy Provider-agnostic retry/error taxonomy (tiers, RetryPolicy, error classification).
pkg/scrub Regexp-based text scrubbing to redact sensitive patterns and PII.
pkg/vcrpatch Patch and rewrite VCR cassettes (match requests, apply actions).
pkg/llmvcr Standalone VCR record/replay for provider http.Clients; auto-redacts secrets (via pkg/scrub) before writing cassettes; fail-fast on miss.
pkg/llmtest Mock provider response/interaction fixtures for deterministic tests.
pkg/observ Observability HTTP server (pprof) bound to a loopback address.
pkg/trace runtime/trace-based Tracer plus a no-op implementation.
pkg/httputil Small protocol-level HTTP helpers, independent of business logic.
pkg/logger Helpers for creating *slog.Logger instances.
pkg/vectorstore Optional, dependency-free local vector store: in-memory nearest-neighbor search, deduplication, and threshold clustering over caller-supplied embeddings.
pkg/doctor Environment-readiness diagnostics (file descriptors, hosted-API latency and key validity, local Ollama) exposed as a library API.

Determinism and testing

Deterministic, zero-cost CI is a first-class goal. The determinism toolkit is centered on pkg/llmvcr, with supporting packages for cassette patching, redaction rules, and fixtures:

  • pkg/llmvcr is the productized record/replay package. It returns a standard *http.Client that records provider HTTP interactions to YAML cassettes and replays them offline, failing fast with llmvcr.ErrCassetteMiss on a cassette miss instead of making a live call. It works with any client that accepts an *http.Client, including the OpenAI provider (openai.WithHTTPClient) and the Gemini genai.Client (option.WithHTTPClient). Sensitive headers, query parameters, and body tokens (bearer tokens, sk- and AIza keys) are redacted via pkg/scrub before any cassette is written.
  • pkg/vcrpatch patches and rewrites recorded cassettes for scenario testing.
  • pkg/scrub provides the regexp redaction rules reused by pkg/llmvcr (and usable for logs).
  • pkg/llmtest provides mock provider response and interaction fixtures for tests.
rec, err := llmvcr.New("testdata/openai_success", llmvcr.ModeReplayOnly)
if err != nil {
    // handle error
}
defer func() {
    if err := rec.Stop(); err != nil {
        log.Printf("stopping recorder: %v", err)
    }
}()
provider := openai.NewProvider(apiKeys, openai.WithHTTPClient(rec.HTTPClient()))
Differential fuzzing of the schema layer

pkg/analyzer derives a JSON schema from a Go type (SchemaOf), then later validates a model's response against it (Validate). Those two paths and encoding/json are three independent sources of truth that must agree, and past regressions were subtle drifts between them. differential_test.go pins two invariants with Go's native fuzzing framework:

  • Property A — Validate(SchemaOf(T), json.Marshal(v)) never rejects a value the model could legitimately produce.
  • Property B — anything Validate accepts also decodes into T (the validator is never more permissive than the decoder).

Both targets seed a generated corpus covering a catalog of tricky types, so make test exercises the properties deterministically with no extra step. For deeper, coverage-guided exploration, run a target directly:

go test ./pkg/analyzer -run '^$' -fuzz 'FuzzValidateImpliesDecode$' -fuzztime 2m

Any failing input the engine finds is written under pkg/analyzer/testdata/fuzz/ and replays as a permanent regression seed on the next go test.

Development

Common make targets:

Target Description
make build Compile all packages.
make test Run the full test suite with the race detector.
make test-unit-cover Run tests with a coverage profile.
make lint Run golangci-lint.
make lint-arch Run the architecture linter (go-arch-lint).
make fmt Format the code with gofmt.
make vet Run go vet.
make tidy Run go mod tidy.
make clean Remove generated artifacts.

Roadmap

The product roadmap and positioning notes have moved to docs/ROADMAP.md.

License

Released under the MIT License.

Directories

Path Synopsis
examples
embeddings
Package embeddings shows how to wire the local Ollama embedder (github.com/vmontagh/go-llm-pipeline/pkg/provider/ollama.Embedder) into the dependency-free github.com/vmontagh/go-llm-pipeline/pkg/vectorstore for a fully local-first semantic search and deduplication loop.
Package embeddings shows how to wire the local Ollama embedder (github.com/vmontagh/go-llm-pipeline/pkg/provider/ollama.Embedder) into the dependency-free github.com/vmontagh/go-llm-pipeline/pkg/vectorstore for a fully local-first semantic search and deduplication loop.
pkg
analyzer
Package analyzer provides the Template Method and Builder patterns for LLM-based analysis.
Package analyzer provides the Template Method and Builder patterns for LLM-based analysis.
doctor
Package doctor provides a reusable diagnostic engine that checks local environment readiness before batch LLM jobs.
Package doctor provides a reusable diagnostic engine that checks local environment readiness before batch LLM jobs.
httputil
Package httputil contains small, protocol-level HTTP helpers that are independent of any business logic in this repository.
Package httputil contains small, protocol-level HTTP helpers that are independent of any business logic in this repository.
llmvcr
Package llmvcr provides a productized VCR (record/replay) workflow for the standard Go http.Client instances used by LLM provider SDKs.
Package llmvcr provides a productized VCR (record/replay) workflow for the standard Go http.Client instances used by LLM provider SDKs.
logger
Package logger provides helpers for creating *slog.Logger instances.
Package logger provides helpers for creating *slog.Logger instances.
observ
Package observ provides functionality for observ.
Package observ provides functionality for observ.
pipeline
Package pipeline provides foundational concurrency utilities used by the orchestrator: a generic worker-pool consumer and a dead-letter queue for failed pipeline events.
Package pipeline provides foundational concurrency utilities used by the orchestrator: a generic worker-pool consumer and a dead-letter queue for failed pipeline events.
policy
Package policy holds the foundational, provider-agnostic retry/error taxonomy shared by every layer that needs to make routing decisions on a failure: the analyzer adapters, the orchestrator/tagger pipeline and the CLI composition root.
Package policy holds the foundational, provider-agnostic retry/error taxonomy shared by every layer that needs to make routing decisions on a failure: the analyzer adapters, the orchestrator/tagger pipeline and the CLI composition root.
promptregistry
Package promptregistry treats LLM prompts as first-class, versioned, testable assets instead of inline string literals scattered across caller code.
Package promptregistry treats LLM prompts as first-class, versioned, testable assets instead of inline string literals scattered across caller code.
provider
Package provider — keypool.go implements KeyPool, the concurrency-safe pool of API credentials with per-key cooldown semantics that the per-backend analyzer providers (openai, gemini, ollama) use to rotate keys on quota / rate-limit errors.
Package provider — keypool.go implements KeyPool, the concurrency-safe pool of API credentials with per-key cooldown semantics that the per-backend analyzer providers (openai, gemini, ollama) use to rotate keys on quota / rate-limit errors.
provider/gemini
Package gemini implements the transport half of the analyzer Template Method using Google's Gemini models.
Package gemini implements the transport half of the analyzer Template Method using Google's Gemini models.
provider/ollama
Package ollama implements the transport half of the analyzer Template Method using a locally running Ollama instance with a vision-capable model.
Package ollama implements the transport half of the analyzer Template Method using a locally running Ollama instance with a vision-capable model.
provider/openai
Package openai implements the transport half of the analyzer Template Method for the OpenAI chat-completions API.
Package openai implements the transport half of the analyzer Template Method for the OpenAI chat-completions API.
scrub
Package scrub provides text scrubbing utilities for redacting sensitive patterns from strings.
Package scrub provides text scrubbing utilities for redacting sensitive patterns from strings.
semcache
Package semcache provides an optional, local-first semantic response cache that sits in front of provider calls and reuses prior responses for repeated or near-duplicate prompts.
Package semcache provides an optional, local-first semantic response cache that sits in front of provider calls and reuses prior responses for repeated or near-duplicate prompts.
trace
Package trace provides tracing functionality.
Package trace provides tracing functionality.
vcrtest
Package vcrtest provides a small testing.T-aware helper that backs a provider adapter's *http.Client with a named YAML cassette: recorded HTTP interactions are replayed offline by default, and recorded once against a real backend when a developer opts in.
Package vcrtest provides a small testing.T-aware helper that backs a provider adapter's *http.Client with a named YAML cassette: recorded HTTP interactions are replayed offline by default, and recorded once against a real backend when a developer opts in.
vectorstore
Package vectorstore provides an optional, local-first, dependency-free toolkit for semantic similarity, deduplication, and basic clustering over caller-supplied embedding vectors.
Package vectorstore provides an optional, local-first, dependency-free toolkit for semantic similarity, deduplication, and basic clustering over caller-supplied embedding vectors.
vectorstore/vectorstoretest
Package vectorstoretest provides a reusable conformance harness that verifies any Store implementation against the shared behavioral contract of the vectorstore package.
Package vectorstoretest provides a reusable conformance harness that verifies any Store implementation against the shared behavioral contract of the vectorstore package.

Jump to

Keyboard shortcuts

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