forza

package module
v0.0.0-...-362af3a Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

Forza

Agents framework for Golang

Build AI agents with multiple LLM providers using a unified, idiomatic Go API.

Supported providers:

Provider Models Status
OpenAI GPT-4o, GPT-4o-mini, GPT-4, GPT-5, O1 Stable
Azure OpenAI Same as OpenAI Stable
Anthropic Claude 4 Opus, Claude 4 Sonnet, Claude 3.7/3.5 Sonnet, Claude 3 Haiku Stable
Google Gemini Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 2.0 Flash Stable
Ollama (local) Llama 3, Mistral, Mixtral, Phi3, Gemma2, any custom model Stable

Features:

  • LLM agents with Role, Backstory, and Goal
  • Task pipelines: concurrent, sequential, and chained execution
  • Function calling / tool use (all providers)
  • Built-in web scraper tool
  • Proper error handling (no panics)
  • 87%+ test coverage

Installation

go get github.com/vitoraguila/forza

Requires Go 1.21 or later.

Environment Variables

OpenAI

OPENAI_API_KEY=sk-...

Azure OpenAI

AZURE_OPEN_AI_API_KEY=...
AZURE_OPEN_AI_ENDPOINT=https://your-resource.openai.azure.com/

Anthropic

ANTHROPIC_API_KEY=sk-ant-...

Google Gemini

GEMINI_API_KEY=...

Ollama

No API key needed. Just run ollama serve locally.

Quick Start

OpenAI

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/vitoraguila/forza"
)

func main() {
	config := forza.NewLLMConfig().
		WithProvider(forza.ProviderOpenAi).
		WithModel(forza.OpenAIModels.GPT4oMini).
		WithOpenAiCredentials(os.Getenv("OPENAI_API_KEY"))

	agent := forza.NewAgent().
		WithRole("You are famous writer").
		WithBackstory("you know how to captivate your audience with your words").
		WithGoal("building a compelling narrative")

	task, err := agent.NewLLMTask(config)
	if err != nil {
		log.Fatal(err)
	}
	task.WithUserPrompt("Write a story about Hercules and the Hydra")

	result, err := task.Completion()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

Anthropic (Claude)

config := forza.NewLLMConfig().
	WithProvider(forza.ProviderAnthropic).
	WithModel(forza.AnthropicModels.Claude4Sonnet).
	WithAnthropicCredentials(os.Getenv("ANTHROPIC_API_KEY"))

Google Gemini

config := forza.NewLLMConfig().
	WithProvider(forza.ProviderGemini).
	WithModel(forza.GeminiModels.Gemini25Flash).
	WithGeminiCredentials(os.Getenv("GEMINI_API_KEY"))

Ollama (Local LLMs)

config := forza.NewLLMConfig().
	WithProvider(forza.ProviderOllama).
	WithModel(forza.OllamaModels.Llama31).
	WithOllamaCredentials("http://localhost:11434/v1")

Usage

Running tasks concurrently

pipeline := forza.NewPipeline()
pipeline.AddTasks(task1.Completion, task2.Completion)

results, err := pipeline.RunConcurrently()
if err != nil {
	log.Fatal(err)
}
fmt.Println("Task 1:", results[0])
fmt.Println("Task 2:", results[1])

Chaining tasks

Each task receives the previous task's output as context:

pipeline := forza.NewPipeline()
chain := pipeline.CreateChain(researchTask.Completion, writerTask.Completion)

result, err := chain()
if err != nil {
	log.Fatal(err)
}
fmt.Println(result)

Running tasks sequentially

pipeline := forza.NewPipeline()
pipeline.AddTasks(task1.Completion, task2.Completion, task3.Completion)

results, err := pipeline.RunSequentially()
if err != nil {
	log.Fatal(err)
}

Function calling / Tool use

// Built-in scraper tool
scraper, _ := scraper.NewScraper()
task.WithTools(scraper)

// Custom tools
params := forza.NewFunction(
	forza.WithProperty("city", "city name", true),
)
task.AddCustomTools("get_weather", "get weather for a city", params, func(input string) (string, error) {
	// your logic here
	return "Sunny, 22C", nil
})

Configuration options

config := forza.NewLLMConfig().
	WithProvider(forza.ProviderOpenAi).
	WithModel(forza.OpenAIModels.GPT4oMini).
	WithTemperature(0.7).      // 0.0 - 2.0 (default: 0.3)
	WithMaxTokens(2048).       // max response tokens (default: 4096)
	WithOpenAiCredentials(key)

Available Models

OpenAI

Constant Model
OpenAIModels.GPT4oMini gpt-4o-mini (recommended)
OpenAIModels.GPT4o gpt-4o
OpenAIModels.GPT4 gpt-4
OpenAIModels.GPT4Turbo gpt-4-turbo
OpenAIModels.GPT5 gpt-5
OpenAIModels.O1 o1
OpenAIModels.O1Mini o1-mini
OpenAIModels.GPT35Turbo gpt-3.5-turbo (deprecated)

Anthropic

Constant Model
AnthropicModels.Claude4Opus claude-opus-4-20250514
AnthropicModels.Claude4Sonnet claude-sonnet-4-20250514
AnthropicModels.Claude37Sonnet claude-3-7-sonnet-latest
AnthropicModels.Claude35Sonnet claude-3-5-sonnet-latest
AnthropicModels.Claude3Haiku claude-3-haiku-20240307

Google Gemini

Constant Model
GeminiModels.Gemini25Pro gemini-2.5-pro
GeminiModels.Gemini25Flash gemini-2.5-flash
GeminiModels.Gemini20Flash gemini-2.0-flash

Ollama

Constant Model
OllamaModels.Llama31 llama3.1
OllamaModels.Llama3 llama3
OllamaModels.Mistral mistral
OllamaModels.Mixtral mixtral
OllamaModels.Phi3 phi3
OllamaModels.Gemma2 gemma2

Ollama also accepts any custom model string.

Architecture

forza/
├── agent.go        # Agent + provider factory
├── llm.go          # LLMAgent interface + LLMConfig
├── common.go       # Provider constants + model registry
├── errors.go       # Error types
├── functions.go    # Function calling parameter builder
├── forza.go        # Pipeline: concurrent, sequential, chain
├── openai.go       # OpenAI / Azure provider
├── anthropic.go    # Anthropic (Claude) provider
├── gemini.go       # Google Gemini provider
├── ollama.go       # Ollama (local LLMs) provider
├── tools/
│   ├── tool.go     # Tool interface
│   └── scraper/    # Web scraper tool
└── examples/       # Usage examples per provider

Development

make test       # Run tests
make cover      # Run tests with coverage
make lint       # Run golangci-lint
make build      # Build all packages
make check      # Run vet + lint + test

Contributing

Contributions, suggestions, and feature requests are welcome.

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new functionality
  4. Ensure make check passes
  5. Submit a pull request

License

MIT

Documentation

Index

Constants

View Source
const (
	ProviderOpenAi    = "openai"
	ProviderAzure     = "openai-azure"
	ProviderAnthropic = "anthropic"
	ProviderGemini    = "gemini"
	ProviderOllama    = "ollama"
)

Provider constants.

Variables

View Source
var (
	ErrProviderNotFound      = errors.New("provider does not exist")
	ErrModelNotFound         = errors.New("model does not exist for the selected provider")
	ErrMissingRole           = errors.New("agent Role is required (use WithRole())")
	ErrMissingBackstory      = errors.New("agent Backstory is required (use WithBackstory())")
	ErrMissingGoal           = errors.New("agent Goal is required (use WithGoal())")
	ErrMissingPrompt         = errors.New("user prompt is required (use WithUserPrompt())")
	ErrMissingAPIKey         = errors.New("API key not provided")
	ErrMissingEndpoint       = errors.New("endpoint not provided")
	ErrTooManyArgs           = errors.New("too many arguments: only one optional context argument is allowed")
	ErrNilTask               = errors.New("task function is nil")
	ErrCompletionFailed      = errors.New("completion request failed")
	ErrToolCallFailed        = errors.New("tool call execution failed")
	ErrChainInterrupted      = errors.New("chain interrupted by task error")
	ErrMaxToolRoundsExceeded = errors.New("maximum tool call rounds exceeded")
	ErrInvalidConfig         = errors.New("invalid LLM configuration")
	ErrResponseTooLarge      = errors.New("response body exceeds maximum allowed size")
)
View Source
var AnthropicModels = AnthropicModelList{
	Claude3Haiku:   "claude-3-haiku-20240307",
	Claude35Sonnet: "claude-3-5-sonnet-latest",
	Claude37Sonnet: "claude-3-7-sonnet-latest",
	Claude4Sonnet:  "claude-sonnet-4-20250514",
	Claude4Opus:    "claude-opus-4-20250514",
	Claude45Sonnet: "claude-sonnet-4-5-20250620",
	Claude45Opus:   "claude-opus-4-5-20250620",
	Claude46Sonnet: "claude-sonnet-4-6-20250827",
	Claude46Opus:   "claude-opus-4-6-20250827",
}

AnthropicModels contains the predefined Anthropic model strings.

View Source
var GeminiModels = GeminiModelList{
	Gemini20Flash:    "gemini-2.0-flash",
	Gemini20FlashExp: "gemini-2.0-flash-exp",
	Gemini25Pro:      "gemini-2.5-pro",
	Gemini25Flash:    "gemini-2.5-flash",
	Gemini3Flash:     "gemini-3.0-flash",
	Gemini3Pro:       "gemini-3.0-pro",
}

GeminiModels contains the predefined Gemini model strings.

View Source
var OllamaModels = OllamaModelList{
	Llama3:  "llama3",
	Llama31: "llama3.1",
	Mistral: "mistral",
	Mixtral: "mixtral",
	Phi3:    "phi3",
	Gemma2:  "gemma2",
}

OllamaModels contains common Ollama model strings. Users can also pass any custom model name string that is available on their Ollama instance.

View Source
var OpenAIModels = OpenAIModelList{
	GPT35Turbo: "gpt-3.5-turbo",
	GPT4:       "gpt-4",
	GPT4o:      "gpt-4o",
	GPT4Turbo:  "gpt-4-turbo",
	GPT4oMini:  "gpt-4o-mini",
	O1Mini:     "o1-mini",
	O1:         "o1",
	GPT5:       "gpt-5",
	Codex52:    "codex-5.2",
}

OpenAIModels contains the predefined OpenAI model strings.

Functions

func WithProperty

func WithProperty(name, description string, required bool) func(FunctionShape)

WithProperty returns an option that adds a parameter definition to a FunctionShape.

Types

type Agent

type Agent struct {
	Role      string
	Backstory string
	Goal      string
}

Agent represents an AI agent with a role, backstory, and goal.

func NewAgent

func NewAgent() *Agent

NewAgent creates a new empty Agent.

func (*Agent) NewLLMTask

func (a *Agent) NewLLMTask(c *LLMConfig) (LLMAgent, error)

NewLLMTask creates an LLMAgent for this agent using the provided configuration. Returns an error if the agent is incomplete or the provider/model is invalid.

func (*Agent) WithBackstory

func (a *Agent) WithBackstory(backstory string) *Agent

WithBackstory sets the agent's backstory.

func (*Agent) WithGoal

func (a *Agent) WithGoal(goal string) *Agent

WithGoal sets the agent's goal.

func (*Agent) WithRole

func (a *Agent) WithRole(role string) *Agent

WithRole sets the agent's role.

type AnthropicModelList

type AnthropicModelList struct {
	Claude3Haiku   string
	Claude35Sonnet string
	Claude37Sonnet string
	Claude4Sonnet  string
	Claude4Opus    string
	Claude45Sonnet string
	Claude45Opus   string
	Claude46Sonnet string
	Claude46Opus   string
}

AnthropicModelList holds available Anthropic model identifiers.

func (AnthropicModelList) ListModels

func (m AnthropicModelList) ListModels() []string

type FunctionProps

type FunctionProps struct {
	Description string
	Required    bool
}

FunctionProps defines properties for a function parameter.

type FunctionShape

type FunctionShape map[string]FunctionProps

FunctionShape maps parameter names to their properties.

func NewFunction

func NewFunction(properties ...func(FunctionShape)) FunctionShape

NewFunction creates a new FunctionShape with the given property options.

type GeminiModelList

type GeminiModelList struct {
	Gemini20Flash    string
	Gemini20FlashExp string
	Gemini25Pro      string
	Gemini25Flash    string
	Gemini3Flash     string
	Gemini3Pro       string
}

GeminiModelList holds available Google Gemini model identifiers.

func (GeminiModelList) ListModels

func (m GeminiModelList) ListModels() []string

type LLMAgent

type LLMAgent interface {
	// Completion sends the prompt to the LLM and returns the response.
	// An optional context string can be passed (used in chains).
	Completion(ctx context.Context, params ...string) (string, error)

	// AddCustomTools registers a custom function-calling tool.
	AddCustomTools(name string, description string, params FunctionShape, fn func(param string) (string, error))

	// WithUserPrompt sets the user prompt for the next completion.
	WithUserPrompt(prompt string)

	// WithTools registers pre-built tools (e.g. scraper).
	WithTools(tools ...tools.Tool)
}

LLMAgent is the interface that all LLM provider implementations must satisfy.

type LLMConfig

type LLMConfig struct {
	// contains filtered or unexported fields
}

LLMConfig holds the configuration for an LLM provider.

func NewLLMConfig

func NewLLMConfig() *LLMConfig

NewLLMConfig creates a new LLMConfig with sensible defaults.

func (*LLMConfig) Validate

func (c *LLMConfig) Validate() error

Validate checks that the configuration is valid.

func (*LLMConfig) WithAnthropicCredentials

func (c *LLMConfig) WithAnthropicCredentials(apiKey string) *LLMConfig

WithAnthropicCredentials sets Anthropic API credentials.

func (*LLMConfig) WithAzureOpenAiCredentials

func (c *LLMConfig) WithAzureOpenAiCredentials(azureApiKey, azureEndpoint string) *LLMConfig

WithAzureOpenAiCredentials sets Azure OpenAI credentials.

func (*LLMConfig) WithGeminiCredentials

func (c *LLMConfig) WithGeminiCredentials(apiKey string) *LLMConfig

WithGeminiCredentials sets Google Gemini API credentials.

func (*LLMConfig) WithMaxRetries

func (c *LLMConfig) WithMaxRetries(n int) *LLMConfig

WithMaxRetries sets the maximum number of retry attempts for transient errors.

func (*LLMConfig) WithMaxTokens

func (c *LLMConfig) WithMaxTokens(maxTokens int) *LLMConfig

WithMaxTokens sets the maximum number of tokens in the response.

func (*LLMConfig) WithModel

func (c *LLMConfig) WithModel(model string) *LLMConfig

WithModel sets the model identifier.

func (*LLMConfig) WithOllamaCredentials

func (c *LLMConfig) WithOllamaCredentials(endpoint string) *LLMConfig

WithOllamaCredentials sets the Ollama endpoint (default: http://localhost:11434).

func (*LLMConfig) WithOpenAiCredentials

func (c *LLMConfig) WithOpenAiCredentials(openAiApiKey string) *LLMConfig

WithOpenAiCredentials sets OpenAI API credentials.

func (*LLMConfig) WithProvider

func (c *LLMConfig) WithProvider(provider string) *LLMConfig

WithProvider sets the LLM provider (e.g. ProviderOpenAi, ProviderAnthropic).

func (*LLMConfig) WithTemperature

func (c *LLMConfig) WithTemperature(temperature float64) *LLMConfig

WithTemperature sets the sampling temperature (0.0 - 2.0).

func (*LLMConfig) WithTimeout

func (c *LLMConfig) WithTimeout(d time.Duration) *LLMConfig

WithTimeout sets the HTTP client timeout for provider requests.

type Models

type Models interface {
	ListModels() []string
}

Models interface allows listing available models for a provider.

type OllamaModelList

type OllamaModelList struct {
	Llama3  string
	Llama31 string
	Mistral string
	Mixtral string
	Phi3    string
	Gemma2  string
}

OllamaModelList holds common Ollama model identifiers.

func (OllamaModelList) ListModels

func (m OllamaModelList) ListModels() []string

type OpenAIModelList

type OpenAIModelList struct {
	GPT35Turbo string // Deprecated: use GPT4oMini instead
	GPT4       string
	GPT4o      string
	GPT4Turbo  string
	GPT4oMini  string
	O1Mini     string
	O1         string
	GPT5       string
	Codex52    string
}

OpenAIModelList holds available OpenAI model identifiers.

func (OpenAIModelList) ListModels

func (m OpenAIModelList) ListModels() []string

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline orchestrates the execution of multiple LLM tasks.

func NewPipeline

func NewPipeline() *Pipeline

NewPipeline creates a new empty Pipeline.

func (*Pipeline) AddTasks

func (p *Pipeline) AddTasks(fn ...TaskChainFn)

AddTasks appends one or more task functions to the pipeline.

func (*Pipeline) CreateChain

func (p *Pipeline) CreateChain(tasks ...TaskChainFn) TaskFn

CreateChain returns a TaskFn that executes tasks sequentially, passing each task's result as context to the next task. If any task returns an error, the chain stops and the error is returned.

func (*Pipeline) RunConcurrently

func (p *Pipeline) RunConcurrently(ctx context.Context) ([]string, error)

RunConcurrently executes all added tasks concurrently and returns their results in the original order. If any task fails or panics, its error is collected and returned as a combined error after all tasks complete.

func (*Pipeline) RunSequentially

func (p *Pipeline) RunSequentially(ctx context.Context) ([]string, error)

RunSequentially executes all added tasks one after another. Each task receives no context arguments. If any task fails, execution stops and the error is returned.

func (*Pipeline) WithLogger

func (p *Pipeline) WithLogger(l *slog.Logger) *Pipeline

WithLogger sets an optional logger for the pipeline. If nil, no logging occurs.

type TaskChainFn

type TaskChainFn func(context.Context, ...string) (string, error)

TaskChainFn is a function that takes a context and optional context strings and returns a result or error.

type TaskFn

type TaskFn func(context.Context) (string, error)

TaskFn is a function that takes a context and returns a result or error.

Directories

Path Synopsis
examples
chains command
completion command
functionCalling command

Jump to

Keyboard shortcuts

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