claude

package module
v0.1.24 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 23 Imported by: 18

README

Claude Model

A Claude model implementation for Eino that implements the ToolCallingChatModel interface. This enables seamless integration with Eino's LLM capabilities for enhanced natural language processing and generation.

Features

  • Implements github.com/cloudwego/eino/components/model.Model
  • Easy integration with Eino's model system
  • Configurable model parameters
  • Support for chat completion
  • Support for streaming responses
  • Custom response parsing support
  • Flexible model configuration

Installation

go get github.com/cloudwego/eino-ext/components/model/claude@latest

Quick Start

Here's a quick example of how to use the Claude model:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/cloudwego/eino/schema"

	"github.com/cloudwego/eino-ext/components/model/claude"
)

func main() {
	ctx := context.Background()
	apiKey := os.Getenv("CLAUDE_API_KEY")
	modelName := os.Getenv("CLAUDE_MODEL")
	baseURL := os.Getenv("CLAUDE_BASE_URL")
	if apiKey == "" {
		log.Fatal("CLAUDE_API_KEY environment variable is not set")
	}

	var baseURLPtr *string = nil
	if len(baseURL) > 0 {
		baseURLPtr = &baseURL
	}

	// Create a Claude model
	cm, err := claude.NewChatModel(ctx, &claude.Config{
		// if you want to use Aws Bedrock Service, set these four field.
		// ByBedrock:       true,
		// AccessKey:       "",
		// SecretAccessKey: "",
		// Region:          "us-west-2",

		// if you want to use Google Vertex AI, set ByVertex: true.
		// Pass raw service account JSON via VertexServiceAccountJSON for explicit credentials.
		// ByVertex:                 true,
		// VertexProjectID:          "my-gcp-project",
		// VertexRegion:             "us-east5",
		// VertexServiceAccountJSON: serviceAccountJSON,
		APIKey: apiKey,
		// Model:     "claude-3-5-sonnet-20240620",
		BaseURL:   baseURLPtr,
		Model:     modelName,
		MaxTokens: 3000,
	})
	if err != nil {
		log.Fatalf("NewChatModel of claude failed, err=%v", err)
	}

	messages := []*schema.Message{
		{
			Role:    schema.System,
			Content: "You are a helpful AI assistant. Be concise in your responses.",
		},
		{
			Role:    schema.User,
			Content: "What is the capital of France?",
		},
	}

	resp, err := cm.Generate(ctx, messages, claude.WithThinkingConfig(&anthropic.ThinkingConfigParamUnion{
		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{
			Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized,
		},
	}))
	if err != nil {
		log.Printf("Generate error: %v", err)
		return
	}

	thinking, ok := claude.GetThinking(resp)
	fmt.Printf("Thinking(have: %v): %s\n", ok, thinking)
	fmt.Printf("Assistant: %s\n", resp.Content)
	if resp.ResponseMeta != nil && resp.ResponseMeta.Usage != nil {
		fmt.Printf("Tokens used: %d (prompt) + %d (completion) = %d (total)\n",
			resp.ResponseMeta.Usage.PromptTokens,
			resp.ResponseMeta.Usage.CompletionTokens,
			resp.ResponseMeta.Usage.TotalTokens)
	}
}

Configuration

The model can be configured using the claude.ChatModelConfig struct:

type Config struct {
    // ByBedrock indicates whether to use Bedrock Service
    // Required for Bedrock
    ByBedrock bool
    
    // AccessKey is your Bedrock API Access key
    // Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
    // Optional for Bedrock
    AccessKey string
    
    // SecretAccessKey is your Bedrock API Secret Access key
    // Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
    // Optional for Bedrock
    SecretAccessKey string
    
    // SessionToken is your Bedrock API Session Token
    // Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
    // Optional for Bedrock
    SessionToken string
    
    // Profile is your Bedrock API AWS profile
    // This parameter is ignored if AccessKey and SecretAccessKey are provided
    // Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
    // Optional for Bedrock
    Profile string
    
    // Region is your Bedrock API region
    // Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
    // Optional for Bedrock
    Region string

    // ByVertex indicates whether to use Google Vertex AI
    ByVertex bool

    // VertexProjectID is your Google Cloud project ID.
    // If not set, auto-detected from ANTHROPIC_VERTEX_PROJECT_ID, GOOGLE_CLOUD_PROJECT, or GCLOUD_PROJECT
    VertexProjectID string

    // VertexRegion is the Vertex AI region (e.g., "us-east5").
    // If not set, auto-detected from CLOUD_ML_REGION environment variable.
    VertexRegion string

    // VertexServiceAccountJSON is raw GCP service account JSON for Vertex.
    // When non-empty, credentials are built in-memory and passed to vertex.WithCredentials.
    // When empty and ByVertex is true, vertex.WithGoogleAuth (ADC) is used instead.
    VertexServiceAccountJSON []byte
    
    // BaseURL is the custom API endpoint URL
    // Use this to specify a different API endpoint, e.g., for proxies or enterprise setups
    // Optional. Example: "https://custom-claude-api.example.com"
    BaseURL *string
    
    // APIKey is your Anthropic API key for direct Anthropic API access.
    // Obtain from: https://console.anthropic.com/account/keys
    // Optional when AuthToken is set.
    APIKey string

    // AuthToken is your Anthropic auth token for direct Anthropic API access.
    // Optional when APIKey is set.
    AuthToken string

    // Model specifies which Claude model to use
    // Required
    Model string
    
    // MaxTokens limits the maximum number of tokens in the response
    // Range: 1 to model's context length
    // Required. Example: 2000 for a medium-length response
    MaxTokens int
    
    // Temperature controls randomness in responses
    // Range: [0.0, 1.0], where 0.0 is more focused and 1.0 is more creative
    // Optional. Example: float32(0.7)
    Temperature *float32
    
    // TopP controls diversity via nucleus sampling
    // Range: [0.0, 1.0], where 1.0 disables nucleus sampling
    // Optional. Example: float32(0.95)
    TopP *float32
    
    // TopK controls diversity by limiting the top K tokens to sample from
    // Optional. Example: int32(40)
    TopK *int32
    
    // StopSequences specifies custom stop sequences
    // The model will stop generating when it encounters any of these sequences
    // Optional. Example: []string{"\n\nHuman:", "\n\nAssistant:"}
    StopSequences []string
    
    // Deprecated: Use ThinkingConfig instead.
    Thinking *Thinking

    // ThinkingConfig configures Claude thinking using Anthropic SDK's native union.
    ThinkingConfig *anthropic.ThinkingConfigParamUnion

    // HTTPClient specifies the client to send HTTP requests.
    HTTPClient *http.Client `json:"http_client"`

    // RequestTimeout specifies the timeout for each API request.
    // Optional.
    RequestTimeout time.Duration `json:"request_timeout"`
    
    DisableParallelToolUse *bool `json:"disable_parallel_tool_use"`
}

For direct Anthropic API access, authentication resolution works as follows:

  • If Config.APIKey or Config.AuthToken is set, Config takes precedence and environment auth settings are ignored.
  • Otherwise, it falls back to environment variables.
  • Within the chosen source, APIKey and AuthToken can both be set and will both be passed through as-is.
  • If neither source provides auth, client creation still succeeds and auth errors surface later when requests are sent.

For Google Vertex AI, authentication resolution works as follows:

  • Set ByVertex: true and provide VertexProjectID / VertexRegion, or rely on the environment variables documented on Config.
  • When VertexServiceAccountJSON is set, credentials are built in-memory via google.CredentialsFromJSON and passed to vertex.WithCredentials (no ADC or env vars required for auth).
  • When VertexServiceAccountJSON is empty, vertex.WithGoogleAuth (Application Default Credentials) is used.

Structured Output

Use ResponseFormat to get JSON responses conforming to a schema:

import (
	"github.com/cloudwego/eino-ext/components/model/claude"
	"github.com/eino-contrib/jsonschema"
)

type ContactInfo struct {
	Name         string `json:"name" jsonschema:"description=Full name"`
	Email        string `json:"email" jsonschema:"description=Email address"`
	PlanInterest string `json:"plan_interest" jsonschema:"description=Plan type"`
}

r := jsonschema.Reflector{AllowAdditionalProperties: false, DoNotReference: true}
s := r.Reflect(&ContactInfo{})

cm, err := claude.NewChatModel(ctx, &claude.Config{
	APIKey:    "your-api-key",
	Model:     "claude-sonnet-4-6-20250514",
	MaxTokens: 1024,
	ResponseFormat: &claude.ResponseFormat{
		Schema: s,
	},
})

You can also use Eino's utils.GoStruct2ParamsOneOf to derive the schema from a Go struct:

import (
	"github.com/cloudwego/eino-ext/components/model/claude"
	"github.com/cloudwego/eino/components/tool/utils"
)

type ContactInfo struct {
	Name         string `json:"name" jsonschema:"description=Full name"`
	Email        string `json:"email" jsonschema:"description=Email address"`
	PlanInterest string `json:"plan_interest" jsonschema:"description=Plan type"`
}

params, _ := utils.GoStruct2ParamsOneOf[ContactInfo]()
s, _ := params.ToJSONSchema()

cm, err := claude.NewChatModel(ctx, &claude.Config{
	APIKey:    "your-api-key",
	Model:     "claude-sonnet-4-6-20250514",
	MaxTokens: 1024,
	ResponseFormat: &claude.ResponseFormat{
		Schema: s,
	},
})

The response format can also be set per-request using WithResponseFormat:

resp, err := cm.Generate(ctx, messages, claude.WithResponseFormat(&claude.ResponseFormat{
	Schema: s,
}))

Examples

See the following examples for more usage:

For More Details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetThinking

func GetThinking(msg *schema.Message) (string, bool)

func SetMessageBreakpoint deprecated

func SetMessageBreakpoint(msg *schema.Message) *schema.Message

Deprecated: Use SetMessageCacheControl instead.

func SetMessageCacheControl

func SetMessageCacheControl(msg *schema.Message, ctrl *CacheControl) *schema.Message

SetMessageCacheControl sets a cache breakpoint on the message with the given cache control settings. A nil CacheControl or zero-value TTL means the SDK default (5 minutes) is used.

func SetToolInfoBreakpoint deprecated

func SetToolInfoBreakpoint(toolInfo *schema.ToolInfo) *schema.ToolInfo

Deprecated: Use SetToolInfoCacheControl instead.

func SetToolInfoCacheControl

func SetToolInfoCacheControl(toolInfo *schema.ToolInfo, ctrl *CacheControl) *schema.ToolInfo

SetToolInfoCacheControl sets a cache breakpoint on the tool info with the given cache control settings. A nil CacheControl or zero-value TTL means the SDK default (5 minutes) is used.

func WithAutoCacheControl

func WithAutoCacheControl(ctrl *CacheControl) model.Option

WithAutoCacheControl sets the CacheControl for automatically placed cache breakpoints. The caching strategy sets separate breakpoints for tool and system messages. Additionally, a breakpoint is set on the last input message of each turn to cache the session. A non-nil ctrl enables auto cache; nil disables it.

func WithCustomHeaders added in v0.1.23

func WithCustomHeaders(headers map[string]string) model.Option

WithCustomHeaders specifies custom HTTP headers to include in API requests.

func WithDisableParallelToolUse

func WithDisableParallelToolUse() model.Option

func WithEnableAutoCache deprecated

func WithEnableAutoCache(enabled bool) model.Option

Deprecated: Use WithAutoCacheControl instead. WithEnableAutoCache enables automatic caching in a multi-turn conversation. The caching strategy sets separate breakpoints for tool and system messages. Additionally, a breakpoint is set on the last input message of each turn to cache the session.

func WithRequestTimeout added in v0.1.23

func WithRequestTimeout(d time.Duration) model.Option

WithRequestTimeout sets the timeout for each API request. This overrides the RequestTimeout set in Config for a single call.

func WithResponseFormat added in v0.1.21

func WithResponseFormat(rf *ResponseFormat) model.Option

WithResponseFormat sets the response format for structured JSON output.

func WithThinking deprecated

func WithThinking(t *Thinking) model.Option

Deprecated: Use WithThinkingConfig instead.

func WithThinkingConfig added in v0.1.21

func WithThinkingConfig(t *anthropic.ThinkingConfigParamUnion) model.Option

WithThinkingConfig sets Claude thinking using Anthropic SDK's native union.

func WithTopK

func WithTopK(k int32) model.Option

Types

type CacheControl

type CacheControl struct {
	TTL CacheTTL
}

CacheControl configures cache control behavior for manual cache breakpoints. A nil CacheControl or zero-value TTL means the SDK default (5 minutes) is used.

type CacheTTL

CacheTTL is a type alias for the Anthropic SDK's cache control TTL. Supported values: CacheTTL5m ("5m", default) and CacheTTL1h ("1h").

const (
	// CacheTTL5m sets the cache TTL to 5 minutes (default).
	CacheTTL5m CacheTTL = anthropic.CacheControlEphemeralTTLTTL5m
	// CacheTTL1h sets the cache TTL to 1 hour.
	CacheTTL1h CacheTTL = anthropic.CacheControlEphemeralTTLTTL1h
)

type ChatModel

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

func NewChatModel

func NewChatModel(ctx context.Context, config *Config) (*ChatModel, error)

NewChatModel creates a new Claude chat model instance

Parameters:

  • ctx: The context for the operation
  • conf: Configuration for the Claude model

Returns:

  • model.ChatModel: A chat model interface implementation
  • error: Any error that occurred during creation

Example:

model, err := claude.NewChatModel(ctx, &claude.Config{
    APIKey: "your-api-key",
    Model:  "claude-3-opus-20240229",
    MaxTokens: 2000,
})

func (*ChatModel) BindForcedTools

func (cm *ChatModel) BindForcedTools(tools []*schema.ToolInfo) error

func (*ChatModel) BindTools

func (cm *ChatModel) BindTools(tools []*schema.ToolInfo) error

func (*ChatModel) Generate

func (cm *ChatModel) Generate(ctx context.Context, input []*schema.Message, opts ...model.Option) (message *schema.Message, err error)

func (*ChatModel) GetType

func (cm *ChatModel) GetType() string

func (*ChatModel) IsCallbacksEnabled

func (cm *ChatModel) IsCallbacksEnabled() bool

func (*ChatModel) Stream

func (cm *ChatModel) Stream(ctx context.Context, input []*schema.Message, opts ...model.Option) (result *schema.StreamReader[*schema.Message], err error)

func (*ChatModel) WithTools

func (cm *ChatModel) WithTools(tools []*schema.ToolInfo) (model.ToolCallingChatModel, error)

type Config

type Config struct {
	// ByBedrock indicates whether to use Bedrock Service
	// Required for Bedrock
	ByBedrock bool

	// AccessKey is your Bedrock API Access key
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional for Bedrock
	AccessKey string

	// SecretAccessKey is your Bedrock API Secret Access key
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional for Bedrock
	SecretAccessKey string

	// SessionToken is your Bedrock API Session Token
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional for Bedrock
	SessionToken string

	// Profile is your Bedrock API AWS profile
	// This parameter is ignored if AccessKey and SecretAccessKey are provided
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional for Bedrock
	Profile string

	// Region is your Bedrock API region
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional for Bedrock
	Region string

	// ByVertex indicates whether to use Google Vertex AI
	ByVertex bool

	// VertexProjectID is your Google Cloud project ID.
	// If not set, auto-detected from environment variables:
	// ANTHROPIC_VERTEX_PROJECT_ID, GOOGLE_CLOUD_PROJECT, or GCLOUD_PROJECT
	VertexProjectID string

	// VertexRegion is the Vertex AI region (e.g., "us-east5").
	// If not set, auto-detected from CLOUD_ML_REGION environment variable.
	// See: https://claude.ai/docs/en/google-vertex-ai
	VertexRegion string

	// VertexServiceAccountJSON is raw GCP service account JSON for Vertex.
	// When non-empty, credentials are built in-memory and passed to vertex.WithCredentials.
	// When empty and ByVertex is true, vertex.WithGoogleAuth (ADC) is used instead.
	// Optional for Vertex.
	VertexServiceAccountJSON []byte

	// BaseURL is the custom API endpoint URL
	// Use this to specify a different API endpoint, e.g., for proxies or enterprise setups
	// Optional. Example: "https://custom-claude-api.example.com"
	BaseURL *string

	// APIKey is your Anthropic API key for direct Anthropic API access.
	// Obtain from: https://console.anthropic.com/account/keys
	// Optional when AuthToken is set.
	APIKey string

	// AuthToken is your Anthropic auth token for direct Anthropic API access.
	// Optional when APIKey is set.
	AuthToken string

	// Model specifies which Claude model to use.
	// If not set, auto-detected from ANTHROPIC_MODEL environment variable.
	Model string

	// MaxTokens limits the maximum number of tokens in the response
	// Range: 1 to model's context length
	// Required. Example: 2000 for a medium-length response
	MaxTokens int

	// Temperature controls randomness in responses
	// Range: [0.0, 1.0], where 0.0 is more focused and 1.0 is more creative
	// Optional. Example: float32(0.7)
	Temperature *float32

	// TopP controls diversity via nucleus sampling
	// Range: [0.0, 1.0], where 1.0 disables nucleus sampling
	// Optional. Example: float32(0.95)
	TopP *float32

	// TopK controls diversity by limiting the top K tokens to sample from
	// Optional. Example: int32(40)
	TopK *int32

	// StopSequences specifies custom stop sequences
	// The model will stop generating when it encounters any of these sequences
	// Optional. Example: []string{"\n\nHuman:", "\n\nAssistant:"}
	StopSequences []string

	// Deprecated: Use ThinkingConfig instead.
	Thinking *Thinking

	// ThinkingConfig configures Claude thinking using Anthropic SDK's native union.
	ThinkingConfig *anthropic.ThinkingConfigParamUnion

	// HTTPClient specifies the client to send HTTP requests.
	HTTPClient *http.Client `json:"http_client"`

	// RequestTimeout specifies the timeout for each API request.
	// Optional.
	RequestTimeout time.Duration `json:"request_timeout"`

	DisableParallelToolUse *bool `json:"disable_parallel_tool_use"`

	// ToolSearchAlgorithm specifies the server-side tool search algorithm.
	// "bm25" or "regex". Default "bm25" when WithDeferredTools is used.
	ToolSearchAlgorithm ToolSearchAlgorithm `json:"tool_search_algorithm"`

	// ResponseFormat specifies the format of the model's response
	// Optional. Use for structured outputs
	ResponseFormat *ResponseFormat `json:"response_format,omitempty"`

	// Additional fields to set in the HTTP request header.
	AdditionalHeaderFields map[string]string `json:"additional_header_fields"`

	// Additional fields to set in the API request.
	// The values of the map must be JSON serializable.
	AdditionalRequestFields map[string]any `json:"additional_request_fields"`
}

Config contains the configuration options for the Claude model

type ResponseFormat added in v0.1.21

type ResponseFormat struct {
	// Schema is the JSON schema that the model's response must conform to.
	Schema *jsonschema.Schema `json:"schema"`
}

ResponseFormat configures structured JSON output using a JSON schema.

type Thinking deprecated

type Thinking struct {
	Enable       bool `json:"enable"`
	BudgetTokens int  `json:"budget_tokens"`
}

Deprecated: Use anthropic.ThinkingConfigParamUnion with Config.ThinkingConfig or WithThinkingConfig instead.

type ToolSearchAlgorithm

type ToolSearchAlgorithm string
const (
	ToolSearchAlgorithmBM25  ToolSearchAlgorithm = "bm25"
	ToolSearchAlgorithmRegex ToolSearchAlgorithm = "regex"
)

type ToolSearchEvent

type ToolSearchEvent struct {
	// Type is "server_tool_use" or "tool_search_tool_result".
	Type string

	// ID is the block ID, set when Type is "server_tool_use".
	ID string
	// Name is the server tool name (e.g. "tool_search_tool_bm25"), set when Type is "server_tool_use".
	Name string
	// Input is the server tool input as raw JSON, set when Type is "server_tool_use".
	Input json.RawMessage

	// ToolUseID references the server_tool_use block, set when Type is "tool_search_tool_result".
	ToolUseID string
	// Content holds the search result or error, set when Type is "tool_search_tool_result".
	Content *ToolSearchEventContent
}

ToolSearchEvent represents a tool search related event from the Claude API. It stores either a server_tool_use event (the model requesting a tool search) or a tool_search_tool_result event (the search results).

type ToolSearchEventContent

type ToolSearchEventContent struct {
	// Type is "tool_search_tool_search_result" or "tool_search_tool_result_error".
	Type string

	// ToolReferences lists matched tool names, set when Type is "tool_search_tool_search_result".
	ToolReferences []ToolSearchEventToolReference
	// ErrorCode is the error code, set when Type is "tool_search_tool_result_error".
	ErrorCode string
	// ErrorMessage is the error message, set when Type is "tool_search_tool_result_error".
	ErrorMessage string
}

ToolSearchEventContent represents the content of a tool_search_tool_result event.

type ToolSearchEventToolReference

type ToolSearchEventToolReference struct {
	ToolName string
}

ToolSearchEventToolReference represents a single tool reference in a search result.

Directories

Path Synopsis
examples
generate command
intent_tool command
stream command

Jump to

Keyboard shortcuts

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