models

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

Models Package

This package provides common utilities for implementing model providers in Agno-Go.

Common Utilities (common.go)

HTTPClient

A shared HTTP client for making API requests:

client := models.NewHTTPClient()

headers := map[string]string{
    "Authorization": "Bearer " + apiKey,
    "Custom-Header": "value",
}

body := map[string]interface{}{
    "prompt": "Hello",
    "max_tokens": 100,
}

resp, err := client.PostJSON(ctx, "https://api.example.com/chat", headers, body)
Response Handling
// For successful responses
var result MyResponseStruct
err := models.ReadJSONResponse(resp, &result)

// For error responses
err := models.ReadErrorResponse(resp)
Helper Functions

ConvertMessages: Convert types.Message to generic format

messages := []*types.Message{
    {Role: types.RoleUser, Content: "Hello"},
}
genericMessages := models.ConvertMessages(messages)

MergeConfig: Merge request-level and model-level configuration

temperature, maxTokens := models.MergeConfig(
    req.Temperature,    // request level
    model.Temperature,  // model level
    req.MaxTokens,      // request level
    model.MaxTokens,    // model level
)

BuildToolDefinitions: Convert tool definitions to generic format

tools := []models.ToolDefinition{...}
genericTools := models.BuildToolDefinitions(tools)

Usage in Model Providers

Example: Using HTTPClient
type MyModel struct {
    models.BaseModel
    httpClient *models.HTTPClient
    apiKey     string
}

func New(apiKey string) *MyModel {
    return &MyModel{
        BaseModel:  models.BaseModel{...},
        httpClient: models.NewHTTPClient(),
        apiKey:     apiKey,
    }
}

func (m *MyModel) Invoke(ctx context.Context, req *models.InvokeRequest) (*types.ModelResponse, error) {
    // Build request
    headers := map[string]string{
        "Authorization": "Bearer " + m.apiKey,
    }

    body := map[string]interface{}{
        "messages": models.ConvertMessages(req.Messages),
        "temperature": req.Temperature,
    }

    // Make API call
    resp, err := m.httpClient.PostJSON(ctx, m.baseURL, headers, body)
    if err != nil {
        return nil, err
    }

    // Parse response
    var apiResp MyAPIResponse
    if err := models.ReadJSONResponse(resp, &apiResp); err != nil {
        return nil, err
    }

    // Convert to ModelResponse
    return m.convertResponse(&apiResp), nil
}

Benefits

  1. Code Reuse: Reduces duplicate HTTP client code across providers
  2. Consistency: Standardized error handling and response parsing
  3. Maintainability: Changes to HTTP logic apply to all providers
  4. Testing: Easier to mock and test with shared utilities

Providers

Current Implementations
  • OpenAI (openai/openai.go): Uses official OpenAI Go SDK

    • Coverage: 44.6%
    • Features: GPT-4, GPT-3.5, function calling, streaming
  • Anthropic (anthropic/anthropic.go): Custom HTTP implementation

    • Coverage: 50.9%
    • Features: Claude 3 Opus, Sonnet, Haiku, streaming
    • Can benefit from HTTPClient refactoring
  • Gemini (gemini/gemini.go): Custom HTTP implementation with SSE streaming

    • Coverage: 77.0%
    • Features: Gemini Pro, Gemini Ultra, function calling, SSE streaming
    • Supports system instructions, tool calls, and function responses
    • Example: cmd/examples/gemini_agent/
  • DeepSeek (deepseek/deepseek.go): OpenAI-compatible SDK integration

    • Coverage: 81.6%
    • Features: DeepSeek-V3 (deepseek-chat), DeepSeek-R1 (deepseek-reasoner)
    • Full OpenAI API compatibility, function calling, streaming
    • Cost-effective with context caching
    • Example: cmd/examples/deepseek_agent/
  • ModelScope (modelscope/modelscope.go): OpenAI-compatible SDK via DashScope

    • Coverage: 78.9%
    • Features: Qwen models (qwen-plus, qwen-turbo, qwen-max), Chinese-optimized
    • Full OpenAI API compatibility through Alibaba Cloud DashScope
    • Excellent Chinese language support
    • Example: cmd/examples/modelscope_agent/
  • Ollama (ollama/ollama.go): Custom HTTP implementation

    • Coverage: 43.8%
    • Features: All Ollama models (Llama 2, Mistral, etc.), streaming
    • Can benefit from HTTPClient refactoring
Adding a New Provider
  1. Create a new directory: pkg/agentgo/models/yourprovider/
  2. Implement the Model interface from base.go
  3. Use common utilities from common.go
  4. Add tests with >70% coverage
  5. Update this README

See CLAUDE.md for detailed instructions.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildToolDefinitions

func BuildToolDefinitions(tools []ToolDefinition) []map[string]interface{}

BuildToolDefinitions converts model tool definitions to a specific format This is a helper that can be customized per provider

func ConvertMessages

func ConvertMessages(messages []*types.Message) []map[string]interface{}

ConvertMessages converts types.Message to a generic message format This is useful for building request messages across different providers

func MergeConfig

func MergeConfig(reqTemp, modelTemp float64, reqTokens, modelTokens int) (float64, int)

MergeConfig merges request-level config with model-level config Request-level values take precedence over model-level values

func ReadErrorResponse

func ReadErrorResponse(resp *http.Response) error

ReadErrorResponse reads an error response and returns an error

func ReadJSONResponse

func ReadJSONResponse(resp *http.Response, target interface{}) error

ReadJSONResponse reads and decodes a JSON response

Types

type BaseModel

type BaseModel struct {
	ID       string
	Name     string
	Provider string
}

BaseModel provides common functionality for model implementations

func (*BaseModel) GetID

func (m *BaseModel) GetID() string

GetID returns the model ID

func (*BaseModel) GetName

func (m *BaseModel) GetName() string

GetName returns the model name

func (*BaseModel) GetProvider

func (m *BaseModel) GetProvider() string

GetProvider returns the model provider

type FunctionSchema

type FunctionSchema struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
}

FunctionSchema defines the schema of a callable function

type HTTPClient

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

HTTPClient provides common HTTP functionality for model providers

func NewHTTPClient

func NewHTTPClient() *HTTPClient

NewHTTPClient creates a new HTTP client

func (*HTTPClient) PostJSON

func (c *HTTPClient) PostJSON(ctx context.Context, url string, headers map[string]string, body interface{}) (*http.Response, error)

PostJSON makes a POST request with JSON body and returns the response

type InvokeRequest

type InvokeRequest struct {
	Messages       []*types.Message
	Tools          []ToolDefinition
	Temperature    float64
	MaxTokens      int
	Stream         bool
	Extra          map[string]interface{}
	ResponseFormat *ResponseFormat // Optional: structured output constraint
}

InvokeRequest contains parameters for model invocation

type Model

type Model interface {
	// Invoke calls the model synchronously
	Invoke(ctx context.Context, req *InvokeRequest) (*types.ModelResponse, error)

	// InvokeStream calls the model with streaming response
	InvokeStream(ctx context.Context, req *InvokeRequest) (<-chan types.ResponseChunk, error)

	// GetProvider returns the model provider name
	GetProvider() string

	// GetID returns the model identifier
	GetID() string

	// GetName returns the model name
	GetName() string
}

Model represents a language model interface

type ResponseFormat added in v1.4.0

type ResponseFormat struct {
	Type       string                 `json:"type"`                  // "json_object" or "json_schema"
	JSONSchema map[string]interface{} `json:"json_schema,omitempty"` // Schema when Type == "json_schema"
}

ResponseFormat specifies the format constraint for model output. Used to request structured JSON output from models that support it.

type ToolDefinition

type ToolDefinition struct {
	Type     string         `json:"type"` // "function"
	Function FunctionSchema `json:"function"`
}

ToolDefinition defines a tool that can be called by the model

Directories

Path Synopsis
evolink
Package fallback provides a Model implementation that chains multiple models together, falling back to the next model when one fails with a retryable error.
Package fallback provides a Model implementation that chains multiple models together, falling back to the next model when one fails with a retryable error.

Jump to

Keyboard shortcuts

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