examples_test

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: AGPL-3.0 Imports: 0 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package examples demonstrates how to use the dracory/llm library.

Each example is a runnable Go test function. Run them with:

go test ./examples/ -v -run "Example"
Example (ContextCancellation)

Example_contextCancellation shows how to pass a context with a timeout to cancel an in-flight LLM request. Set LlmOptions.Context on the per-call options to propagate the context to the provider.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.TextModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "should not see this if cancelled",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Create a context that times out after 1 second
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	// Pass the context via per-call options
	resp, err := engine.GenerateText("sys", "user", llm.LlmOptions{
		Context: ctx,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println("response:", resp)
}
Output:
response: should not see this if cancelled
Example (DisableResponseFormat)

Example_disableResponseFormat shows how to disable the response_format parameter. Some OpenRouter providers reject structured-output requests for certain models. Set DisableResponseFormat to omit it.

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	// In production with a model that doesn't support response_format:
	// engine, err := llm.JSONModel(llm.ProviderOpenRouter, llm.LlmOptions{
	//     ApiKey:              "sk-or-v1-...",
	//     Model:               "some-model-without-json-mode",
	//     DisableResponseFormat: true,
	// })

	// Demonstrating with mock
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse:          `{"result":"ok"}`,
		DisableResponseFormat: true,
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, _ := engine.GenerateJSON("sys", "user")
	fmt.Println(resp)
}
Output:
{"result":"ok"}
Example (MockBasic)

Example_mockBasic shows the simplest usage: create a mock LLM and get a canned response. No API key, no network — ideal for unit tests.

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.TextModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "Hello from the mock!",
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := engine.GenerateText("You are a helpful assistant.", "Say hello")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(resp)
}
Output:
Hello from the mock!
Example (MockCallRecording)

Example_mockCallRecording shows how to use MockInterface to inspect which calls were made. Type-assert the engine to MockInterface to get access to Calls() and Reset().

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.TextModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "ok",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Type-assert to MockInterface for introspection
	mock, ok := engine.(llm.MockInterface)
	if !ok {
		log.Fatal("engine does not implement MockInterface")
	}

	// Make some calls
	_, _ = mock.GenerateText("sys prompt A", "user message A")
	_, _ = mock.GenerateJSON("sys prompt B", "user message B")

	// Inspect recorded calls
	calls := mock.Calls()
	for i, c := range calls {
		fmt.Printf("call %d: method=%s system=%q user=%q\n", i, c.Method, c.SystemPrompt, c.UserPrompt)
	}

	// Clear history
	mock.Reset()
	fmt.Println("after reset:", len(mock.Calls()))
}
Output:
call 0: method=Generate system="sys prompt A" user="user message A"
call 1: method=Generate system="sys prompt B" user="user message B"
after reset: 0
Example (MockError)

Example_mockError shows how to simulate an API failure using MockError. This is useful for testing retry/failure paths without a real API.

package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockError: errors.New("rate limit exceeded"),
	})
	if err != nil {
		log.Fatal(err)
	}

	_, err = engine.GenerateJSON("system", "user")
	fmt.Println(err)
}
Output:
rate limit exceeded
Example (MockJSON)

Example_mockJSON shows how to use GenerateJSON with a mock that returns a JSON string. This is the pattern used for structured-output tasks like classification or extraction.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: `{"risk_tier":"low","domain":"general","reasoning":"safe content"}`,
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := engine.GenerateJSON(
		"You are a risk classifier. Respond with JSON only.",
		"This is a simple blog post about cooking.",
	)
	if err != nil {
		log.Fatal(err)
	}

	var result struct {
		RiskTier  string `json:"risk_tier"`
		Domain    string `json:"domain"`
		Reasoning string `json:"reasoning"`
	}
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("tier=%s domain=%s\n", result.RiskTier, result.Domain)
}
Output:
tier=low domain=general
Example (MockPerCallOverride)

Example_mockPerCallOverride shows how per-call options override the client-level options. Here the client returns "default" but a per-call MockResponse changes the output for that single call.

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	engine, err := llm.TextModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "default response",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Without override — uses client-level MockResponse
	r1, _ := engine.GenerateText("sys", "user")
	fmt.Println("default:", r1)

	// With per-call override
	r2, _ := engine.GenerateText("sys", "user", llm.LlmOptions{
		MockResponse: "per-call override",
	})
	fmt.Println("override:", r2)
}
Output:
default: default response
override: per-call override
Example (ModelSelection)

Example_modelSelection shows the range of model constants available. Pick based on price/performance trade-offs for your use case.

package main

import (
	"fmt"

	"github.com/dracory/llm"
)

func main() {
	models := []struct {
		name      string
		slug      string
		inputCost string
	}{
		{"Ling 3.0 Flash", llm.OPENROUTER_MODEL_LING_3_0_FLASH, "$0.021/M"},
		{"DeepSeek V4 Flash 0731", llm.OPENROUTER_MODEL_DEEPSEEK_V4_FLASH_0731, "$0.05/M"},
		{"GLM 5.3 Flash", llm.OPENROUTER_MODEL_GLM_5_3_FLASH, "$0.075/M"},
		{"Qwen3.8 Flash", llm.OPENROUTER_MODEL_QWEN_3_8_FLASH, "$0.15/M"},
		{"Gemini 3.5 Flash Lite", llm.OPENROUTER_MODEL_GEMINI_3_5_FLASH_LITE, "$0.30/M"},
		{"GPT-OSS-120B", llm.OPENROUTER_MODEL_GPT_OSS_120B, "$0.072/M"},
	}

	fmt.Println("Cheapest text models on OpenRouter:")
	for _, m := range models {
		fmt.Printf("  %-25s %s  (%s)\n", m.name, m.slug, m.inputCost)
	}
}
Example (OpenRouterBasic)

Example_openRouterBasic shows the basic setup for OpenRouter. You need an API key from https://openrouter.ai/keys.

This example uses the mock to avoid a real API call — in production swap ProviderMock for ProviderOpenRouter and set ApiKey.

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	// --- Production setup (uncomment and set your key) ---
	// engine, err := llm.JSONModel(llm.ProviderOpenRouter, llm.LlmOptions{
	//     ApiKey:   "sk-or-v1-...",
	//     Model:    llm.OPENROUTER_MODEL_LING_3_0_FLASH,
	//     MaxTokens: 2000,
	// })

	// --- Test setup (no network) ---
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: `{"sentiment":"positive","confidence":0.95}`,
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := engine.GenerateJSON(
		"You are a sentiment classifier. Respond with JSON: {sentiment, confidence}",
		"I love this product, it works great!",
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(resp)
}
Output:
{"sentiment":"positive","confidence":0.95}
Example (OpenRouterCustomBaseURL)

Example_openRouterCustomBaseURL shows how to override the OpenRouter base URL via ProviderOptions. This is useful for proxies, gateways, or local test servers.

package main

import (
	"fmt"
	"log"

	"github.com/dracory/llm"
)

func main() {
	// In production with a proxy:
	// engine, err := llm.JSONModel(llm.ProviderOpenRouter, llm.LlmOptions{
	//     ApiKey: "sk-or-v1-...",
	//     Model:  llm.OPENROUTER_MODEL_GPT_OSS_120B,
	//     ProviderOptions: map[string]any{
	//         "base_url": "https://my-proxy.example.com/v1",
	//     },
	// })

	// Demonstrating with mock (no network)
	engine, err := llm.TextModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "routed via custom base URL",
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, _ := engine.GenerateText("sys", "user")
	fmt.Println(resp)
}
Output:
routed via custom base URL
Example (TriageInvalidJSON)

Example_triageInvalidJSON shows how to test the invalid-JSON path. The mock returns a non-JSON string, causing json.Unmarshal to fail.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

// triageResult is the structured output we expect from the LLM.
type triageResult struct {
	RiskTier  string   `json:"risk_tier"`
	Domain    string   `json:"domain"`
	Claims    []string `json:"claims"`
	Reasoning string   `json:"reasoning"`
}

// runTriage is a realistic LLM-backed classifier function. It takes an
// engine (any llm.LlmInterface) and content, calls GenerateJSON, parses
// the response, and returns the structured result.
//
// In production you'd use llm.ProviderOpenRouter; in tests you use
// llm.ProviderMock with a canned JSON response or MockError.
func runTriage(engine llm.LlmInterface, content string) (*triageResult, error) {
	if engine == nil {
		return nil, errors.New("no LLM engine configured")
	}

	systemPrompt := `You are a content risk classifier for an expert verification platform.
Classify the given content and respond with JSON only:
{
  "risk_tier": "low" | "medium" | "high" | "critical",
  "domain": "general" | "medical" | "legal" | "financial" | "technical",
  "claims": ["list of specific factual claims that need verification"],
  "reasoning": "brief explanation of the classification"
}`

	resp, err := engine.GenerateJSON(systemPrompt, content)
	if err != nil {
		return nil, fmt.Errorf("LLM call failed: %w", err)
	}

	var result triageResult
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		return nil, fmt.Errorf("invalid JSON from LLM: %w", err)
	}

	return &result, nil
}

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: "This is not JSON, just plain text.",
	})
	if err != nil {
		log.Fatal(err)
	}

	_, err = runTriage(engine, "some content")
	fmt.Println(err)
}
Output:
invalid JSON from LLM: invalid character 'T' looking for beginning of value
Example (TriageLLMError)

Example_triageLLMError shows how to test the error path using MockError. The mock returns the configured error instead of making a real API call.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

// triageResult is the structured output we expect from the LLM.
type triageResult struct {
	RiskTier  string   `json:"risk_tier"`
	Domain    string   `json:"domain"`
	Claims    []string `json:"claims"`
	Reasoning string   `json:"reasoning"`
}

// runTriage is a realistic LLM-backed classifier function. It takes an
// engine (any llm.LlmInterface) and content, calls GenerateJSON, parses
// the response, and returns the structured result.
//
// In production you'd use llm.ProviderOpenRouter; in tests you use
// llm.ProviderMock with a canned JSON response or MockError.
func runTriage(engine llm.LlmInterface, content string) (*triageResult, error) {
	if engine == nil {
		return nil, errors.New("no LLM engine configured")
	}

	systemPrompt := `You are a content risk classifier for an expert verification platform.
Classify the given content and respond with JSON only:
{
  "risk_tier": "low" | "medium" | "high" | "critical",
  "domain": "general" | "medical" | "legal" | "financial" | "technical",
  "claims": ["list of specific factual claims that need verification"],
  "reasoning": "brief explanation of the classification"
}`

	resp, err := engine.GenerateJSON(systemPrompt, content)
	if err != nil {
		return nil, fmt.Errorf("LLM call failed: %w", err)
	}

	var result triageResult
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		return nil, fmt.Errorf("invalid JSON from LLM: %w", err)
	}

	return &result, nil
}

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockError: errors.New("openrouter 503 service unavailable"),
	})
	if err != nil {
		log.Fatal(err)
	}

	_, err = runTriage(engine, "some content")
	fmt.Println(err)
}
Output:
LLM call failed: openrouter 503 service unavailable
Example (TriageNoEngine)

Example_triageNoEngine shows the nil-engine guard.

package main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/dracory/llm"
)

// triageResult is the structured output we expect from the LLM.
type triageResult struct {
	RiskTier  string   `json:"risk_tier"`
	Domain    string   `json:"domain"`
	Claims    []string `json:"claims"`
	Reasoning string   `json:"reasoning"`
}

// runTriage is a realistic LLM-backed classifier function. It takes an
// engine (any llm.LlmInterface) and content, calls GenerateJSON, parses
// the response, and returns the structured result.
//
// In production you'd use llm.ProviderOpenRouter; in tests you use
// llm.ProviderMock with a canned JSON response or MockError.
func runTriage(engine llm.LlmInterface, content string) (*triageResult, error) {
	if engine == nil {
		return nil, errors.New("no LLM engine configured")
	}

	systemPrompt := `You are a content risk classifier for an expert verification platform.
Classify the given content and respond with JSON only:
{
  "risk_tier": "low" | "medium" | "high" | "critical",
  "domain": "general" | "medical" | "legal" | "financial" | "technical",
  "claims": ["list of specific factual claims that need verification"],
  "reasoning": "brief explanation of the classification"
}`

	resp, err := engine.GenerateJSON(systemPrompt, content)
	if err != nil {
		return nil, fmt.Errorf("LLM call failed: %w", err)
	}

	var result triageResult
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		return nil, fmt.Errorf("invalid JSON from LLM: %w", err)
	}

	return &result, nil
}

func main() {
	_, err := runTriage(nil, "some content")
	fmt.Println(err)
}
Output:
no LLM engine configured
Example (TriageSuccess)

Example_triageSuccess shows a successful triage classification using the mock provider with a canned JSON response.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

// triageResult is the structured output we expect from the LLM.
type triageResult struct {
	RiskTier  string   `json:"risk_tier"`
	Domain    string   `json:"domain"`
	Claims    []string `json:"claims"`
	Reasoning string   `json:"reasoning"`
}

// runTriage is a realistic LLM-backed classifier function. It takes an
// engine (any llm.LlmInterface) and content, calls GenerateJSON, parses
// the response, and returns the structured result.
//
// In production you'd use llm.ProviderOpenRouter; in tests you use
// llm.ProviderMock with a canned JSON response or MockError.
func runTriage(engine llm.LlmInterface, content string) (*triageResult, error) {
	if engine == nil {
		return nil, errors.New("no LLM engine configured")
	}

	systemPrompt := `You are a content risk classifier for an expert verification platform.
Classify the given content and respond with JSON only:
{
  "risk_tier": "low" | "medium" | "high" | "critical",
  "domain": "general" | "medical" | "legal" | "financial" | "technical",
  "claims": ["list of specific factual claims that need verification"],
  "reasoning": "brief explanation of the classification"
}`

	resp, err := engine.GenerateJSON(systemPrompt, content)
	if err != nil {
		return nil, fmt.Errorf("LLM call failed: %w", err)
	}

	var result triageResult
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		return nil, fmt.Errorf("invalid JSON from LLM: %w", err)
	}

	return &result, nil
}

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: `{
			"risk_tier": "high",
			"domain": "medical",
			"claims": ["Drug X cures cancer", "FDA approved in 2024"],
			"reasoning": "Medical claims about drug efficacy require expert verification"
		}`,
	})
	if err != nil {
		log.Fatal(err)
	}

	result, err := runTriage(engine, "New study shows Drug X cures cancer, FDA approved 2024.")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("tier=%s domain=%s claims=%v\n", result.RiskTier, result.Domain, result.Claims)
}
Output:
tier=high domain=medical claims=[Drug X cures cancer FDA approved in 2024]
Example (TriageWithCallRecording)

Example_triageWithCallRecording shows how to verify that the LLM was called with the correct prompts using MockInterface.Calls().

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	"github.com/dracory/llm"
)

// triageResult is the structured output we expect from the LLM.
type triageResult struct {
	RiskTier  string   `json:"risk_tier"`
	Domain    string   `json:"domain"`
	Claims    []string `json:"claims"`
	Reasoning string   `json:"reasoning"`
}

// runTriage is a realistic LLM-backed classifier function. It takes an
// engine (any llm.LlmInterface) and content, calls GenerateJSON, parses
// the response, and returns the structured result.
//
// In production you'd use llm.ProviderOpenRouter; in tests you use
// llm.ProviderMock with a canned JSON response or MockError.
func runTriage(engine llm.LlmInterface, content string) (*triageResult, error) {
	if engine == nil {
		return nil, errors.New("no LLM engine configured")
	}

	systemPrompt := `You are a content risk classifier for an expert verification platform.
Classify the given content and respond with JSON only:
{
  "risk_tier": "low" | "medium" | "high" | "critical",
  "domain": "general" | "medical" | "legal" | "financial" | "technical",
  "claims": ["list of specific factual claims that need verification"],
  "reasoning": "brief explanation of the classification"
}`

	resp, err := engine.GenerateJSON(systemPrompt, content)
	if err != nil {
		return nil, fmt.Errorf("LLM call failed: %w", err)
	}

	var result triageResult
	if err := json.Unmarshal([]byte(resp), &result); err != nil {
		return nil, fmt.Errorf("invalid JSON from LLM: %w", err)
	}

	return &result, nil
}

func main() {
	engine, err := llm.JSONModel(llm.ProviderMock, llm.LlmOptions{
		MockResponse: `{"risk_tier":"low","domain":"general","claims":[],"reasoning":"ok"}`,
	})
	if err != nil {
		log.Fatal(err)
	}

	content := "A simple recipe for chocolate cake."
	_, _ = runTriage(engine, content)

	// Verify the LLM was called with the right content
	mock, ok := engine.(llm.MockInterface)
	if !ok {
		log.Fatal("engine does not implement MockInterface")
	}

	calls := mock.Calls()
	if len(calls) != 1 {
		log.Fatalf("expected 1 call, got %d", len(calls))
	}

	// The user prompt should contain our content
	fmt.Println("LLM was called with content:", calls[0].UserPrompt)
}
Output:
LLM was called with content: A simple recipe for chocolate cake.

Jump to

Keyboard shortcuts

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