agenticclaude

package module
v0.1.3 Latest Latest
Warning

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

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

README

Claude Agentic Model

An Anthropic Claude model implementation for Eino that implements the AgenticModel component interface. This enables seamless integration with Eino's Agent capabilities for enhanced natural language processing and generation.

Features

  • Implements github.com/cloudwego/eino/components/model.AgenticModel
  • Easy integration with Eino's agent system
  • Configurable model parameters
  • Support for Anthropic Messages API
  • Support for streaming responses
  • Support for tool calling (Function Tools, Deferred Tools, Client Tool Search, Server Tools)
  • Support for prompt caching
  • Support for AWS Bedrock and Google Vertex AI

Installation

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

Quick Start

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

package main

import (
	"context"
	"log"
	"os"

	"github.com/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticclaude"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
	"github.com/eino-contrib/jsonschema"
	orderedmap "github.com/wk8/go-ordered-map/v2"
)

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

	am, err := agenticclaude.New(ctx, &agenticclaude.Config{
		BaseURL:   os.Getenv("CLAUDE_BASE_URL"),
		Model:     os.Getenv("CLAUDE_MODEL"),
		APIKey:    os.Getenv("CLAUDE_API_KEY"),
		MaxTokens: 4096,
	})
	if err != nil {
		log.Fatalf("failed to create agentic model, err: %v", err)
	}

	input := []*schema.AgenticMessage{
		schema.UserAgenticMessage("what is the weather like in Beijing"),
	}

	msg, err := am.Generate(ctx, input, model.WithTools([]*schema.ToolInfo{
		{
			Name: "get_weather",
			Desc: "get the weather in a city",
			ParamsOneOf: schema.NewParamsOneOfByJSONSchema(&jsonschema.Schema{
				Type: "object",
				Properties: orderedmap.New[string, *jsonschema.Schema](
					orderedmap.WithInitialData(
						orderedmap.Pair[string, *jsonschema.Schema]{
							Key: "city",
							Value: &jsonschema.Schema{
								Type:        "string",
								Description: "the city to get the weather",
							},
						},
					),
				),
				Required: []string{"city"},
			}),
		},
	}))
	if err != nil {
		log.Fatalf("failed to generate, err: %v", err)
	}

	if meta := msg.ResponseMeta.ClaudeExtension; meta != nil {
		log.Printf("request_id: %s\n", meta.ID)
	}

	respBody, _ := sonic.MarshalIndent(msg, "  ", "  ")
	log.Printf("body: %s\n", string(respBody))
}

Configuration

The AgenticModel can be configured using the agenticclaude.Config struct:

type Config struct {
    // HTTPClient specifies the client to send HTTP requests.
    // It is not applied when using Google Vertex AI.
    // Optional.
    HTTPClient *http.Client

    // RequestTimeout specifies the timeout for each API request.
    // Optional.
    RequestTimeout time.Duration

    // ByBedrock specifies the configuration for using AWS Bedrock.
    // Optional.
    ByBedrock *BedrockConfig

    // ByGoogleVertexAI specifies the configuration for using Google Vertex AI.
    // Optional.
    ByGoogleVertexAI *GoogleVertexAIConfig

    // BaseURL is the custom API endpoint URL
    // Use this to specify a different API endpoint, e.g., for proxies or enterprise setups
    // Optional.
    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.
    MaxTokens int

    // StopSequences specifies custom stop sequences
    // The model will stop generating when it encounters any of these sequences
    // Optional.
    StopSequences []string

    // DisableParallelToolUse specifies whether to disable parallel tool use.
    // It only takes effect when AgenticToolChoice is set.
    // Optional.
    DisableParallelToolUse *bool

    // Thinking specifies the configuration for Claude thinking mode.
    // Optional.
    Thinking *anthropic.ThinkingConfigParamUnion

    // CustomHeaders specifies custom HTTP headers to include in API requests.
    // CustomHeaders allows passing additional metadata or authentication information.
    // Optional.
    CustomHeaders map[string]string

    // ExtraFields specifies extra fields to include in the request body.
    // These fields will be merged into the top-level JSON request body, overriding any existing fields with the same key.
    // Optional.
    //
    // Example:
    //
    //	ExtraFields: map[string]any{
    //	    "reasoning_effort": "high",
    //	    "service_tier": "default",
    //	}
    //
    // The resulting request body will be:
    //
    //	{
    //	    "model": "o1",
    //	    "messages": [...],
    //	    "reasoning_effort": "high",
    //	    "service_tier": "default"
    //	}
    ExtraFields map[string]any

    // CacheControl configures automatic prompt caching behavior.
    // When non-nil, automatically applies a cache_control marker to the last
    // cacheable block in the request.
    // Optional.
    CacheControl *anthropic.CacheControlEphemeralParam
}

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 (e.g. ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN) 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.
  • ANTHROPIC_BASE_URL is still honored in both cases; Config.BaseURL takes precedence when set.

Extension Fields

Several fields of the Eino agentic schema are typed any so that each model implementation can attach provider-specific data. To consume the data this package produces, type-assert those fields to the concrete types defined here. For the strongly-typed extension fields (ClaudeExtension), no assertion is required.

ResponseMeta

AgenticResponseMeta.ClaudeExtension is populated with the strongly-typed *claude.ResponseMetaExtension, so no type assertion is needed. The generic Extension any field is not used by this package.

// github.com/cloudwego/eino/schema/claude
type ResponseMetaExtension struct {
    ID           string       // the upstream message ID
    StopReason   string       // why generation stopped, e.g. "end_turn", "tool_use"
    StopSequence string       // the custom stop sequence that was hit, if any
    StopDetails  *StopDetails // additional stop information
}
ext := msg.ResponseMeta.ClaudeExtension // *claude.ResponseMetaExtension
AssistantGenText Extension

UserInputText has no extension. Only AssistantGenText carries one: its ClaudeExtension field is populated with the strongly-typed *claude.AssistantGenTextExtension, so no assertion is needed. The generic Extension any field is not used by this package.

// github.com/cloudwego/eino/schema/claude
type AssistantGenTextExtension struct {
    Citations []*TextCitation // citations attached to the generated text, if any
}
ext := block.AssistantGenText.ClaudeExtension // *claude.AssistantGenTextExtension
ServerToolCall & ServerToolResult

This package supports Claude server-side (built-in) tools such as web search, web fetch, code execution, and tool search. For these blocks, the generic any fields are populated with concrete types defined in this package.

ServerToolCall.Arguments is populated with *agenticclaude.ServerToolCallArguments. Exactly one field is set, matching the invoked tool.

// package agenticclaude
type ServerToolCallArguments struct {
    WebSearch               *WebSearchArguments               // web_search
    WebFetch                *WebFetchArguments                // web_fetch
    CodeExecution           *CodeExecutionArguments           // code_execution
    BashCodeExecution       *BashCodeExecutionArguments       // bash_code_execution
    TextEditorCodeExecution *TextEditorCodeExecutionArguments // text_editor_code_execution
    ToolSearchToolBm25      *ToolSearchToolBm25Arguments      // tool_search_tool_bm25
    ToolSearchToolRegex     *ToolSearchToolRegexArguments     // tool_search_tool_regex
}
args := block.ServerToolCall.Arguments.(*agenticclaude.ServerToolCallArguments)

ServerToolResult.Content is populated with *agenticclaude.ServerToolResult. Exactly one field is set, matching the invoked tool.

// package agenticclaude
type ServerToolResult struct {
    WebSearch               *WebSearchResult               // web_search
    WebFetch                *WebFetchResult                // web_fetch
    CodeExecution           *CodeExecutionResult           // code_execution
    BashCodeExecution       *BashCodeExecutionResult       // bash_code_execution
    TextEditorCodeExecution *TextEditorCodeExecutionResult // text_editor_code_execution
    ToolSearchToolBm25      *ToolSearchToolResult          // tool_search_tool_bm25
    ToolSearchToolRegex     *ToolSearchToolResult          // tool_search_tool_regex
}
result := block.ServerToolResult.Content.(*agenticclaude.ServerToolResult)

Advanced Usage

Cache

Claude's prompt caching works by placing cache_control markers on content blocks. When the API sees a marker, it caches everything up to that point. Subsequent requests that share the same prefix get a cache hit, reducing latency and cost.

This package provides two caching strategies:

Strategy Config / API Use Case
Auto Cache CacheControl in Config Automatically marks the last cacheable block per request
Manual Cache SetContentBlockCacheControl / SetToolInfoCacheControl Fine-grained control on specific blocks or tools

The following diagram illustrates how both strategies work:

flowchart TD
    Input["am.Generate(ctx, input, opts...)"] --> Detail
    Detail["input = [System, User₁, Asst₁, User₂, ...]<br/>tools = [tool_A, tool_B, ...]"]
    Detail --> B{"CacheControl<br/>set in Config?"}
    B -- Yes --> C["Top-level cache_control set on request<br/>— SDK applies it to last cacheable block"]
    B -- No --> D{"Manual markers via<br/>SetContentBlockCacheControl /<br/>SetToolInfoCacheControl?"}
    D -- Yes --> E["Use manual cache_control markers<br/>on specified blocks/tools"]
    D -- No --> F["No caching — full computation each call"]
    C --> G["API caches prefix up to marker<br/>— subsequent calls get cache hit"]
    E --> G

    style Input fill:#e8f4fd,stroke:#4a90d9
    style Detail fill:#e8f4fd,stroke:#4a90d9
    style C fill:#d4edda,stroke:#28a745
    style E fill:#d4edda,stroke:#28a745
    style F fill:#fff3cd,stroke:#ffc107
    style G fill:#d4edda,stroke:#28a745
Auto Cache

Use CacheControl in the config to set a top-level cache control on the request. The SDK automatically applies it to the last cacheable block:

cacheCtrl := anthropic.NewCacheControlEphemeralParam()
cacheCtrl.TTL = anthropic.CacheControlEphemeralTTLTTL5m

am, err := agenticclaude.New(ctx, &agenticclaude.Config{
    BaseURL:      os.Getenv("CLAUDE_BASE_URL"),
    Model:        os.Getenv("CLAUDE_MODEL"),
    APIKey:       os.Getenv("CLAUDE_API_KEY"),
    MaxTokens:    4096,
    CacheControl: &cacheCtrl,
})
Manual Cache

For fine-grained control, use SetContentBlockCacheControl or SetToolInfoCacheControl to manually place cache breakpoints on specific blocks or tools. When a manual marker is set, the top-level auto-cache will not override it.

cacheCtrl := anthropic.NewCacheControlEphemeralParam()
cacheCtrl.TTL = anthropic.CacheControlEphemeralTTLTTL5m

// Cache a specific content block (e.g., a large system prompt).
block = agenticclaude.SetContentBlockCacheControl(block, &cacheCtrl)

// Cache a specific tool definition.
toolInfo = agenticclaude.SetToolInfoCacheControl(toolInfo, &cacheCtrl)
Tool Calling

The AgenticModel supports tool calling, including Function Tools, Deferred Tools, Client Tool Search, and Server Tools.

Function Tool Example
package main

import (
	"context"
	"errors"
	"io"
	"log"
	"os"

	"github.com/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticclaude"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
	"github.com/eino-contrib/jsonschema"
	orderedmap "github.com/wk8/go-ordered-map/v2"
)

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

	am, err := agenticclaude.New(ctx, &agenticclaude.Config{
		BaseURL:   os.Getenv("CLAUDE_BASE_URL"),
		Model:     os.Getenv("CLAUDE_MODEL"),
		APIKey:    os.Getenv("CLAUDE_API_KEY"),
		MaxTokens: 4096,
	})
	if err != nil {
		log.Fatalf("failed to create agentic model, err=%v", err)
	}

	functionTools := []*schema.ToolInfo{
		{
			Name: "get_weather",
			Desc: "get the weather in a city",
			ParamsOneOf: schema.NewParamsOneOfByJSONSchema(&jsonschema.Schema{
				Type: "object",
				Properties: orderedmap.New[string, *jsonschema.Schema](
					orderedmap.WithInitialData(
						orderedmap.Pair[string, *jsonschema.Schema]{
							Key: "city",
							Value: &jsonschema.Schema{
								Type:        "string",
								Description: "the city to get the weather",
							},
						},
					),
				),
				Required: []string{"city"},
			}),
		},
	}

	allowedTools := []*schema.AllowedTool{
		{
			FunctionName: "get_weather",
		},
	}

	opts := []model.Option{
		model.WithAgenticToolChoice(&schema.AgenticToolChoice{
			Type: schema.ToolChoiceForced,
			Forced: &schema.AgenticForcedToolChoice{
				Tools: allowedTools,
			},
		}),
		model.WithTools(functionTools),
	}

	firstInput := []*schema.AgenticMessage{
		schema.UserAgenticMessage("what's the weather like in Beijing today"),
	}

	sResp, err := am.Stream(ctx, firstInput, opts...)
	if err != nil {
		log.Fatalf("failed to stream, err: %v", err)
	}

	var msgs []*schema.AgenticMessage
	for {
		msg, recvErr := sResp.Recv()
		if recvErr != nil {
			if errors.Is(recvErr, io.EOF) {
				break
			}
			log.Fatalf("failed to receive stream response, err: %v", recvErr)
		}
		msgs = append(msgs, msg)
	}

	concatenated, err := schema.ConcatAgenticMessages(msgs)
	if err != nil {
		log.Fatalf("failed to concat agentic messages, err: %v", err)
	}

	lastBlock := concatenated.ContentBlocks[len(concatenated.ContentBlocks)-1]
	if lastBlock.Type != schema.ContentBlockTypeFunctionToolCall {
		log.Fatalf("last block is not function tool call, type: %s", lastBlock.Type)
	}

	toolCall := lastBlock.FunctionToolCall
	toolResultMsg := &schema.AgenticMessage{
		Role: schema.AgenticRoleTypeUser,
		ContentBlocks: []*schema.ContentBlock{
			schema.NewContentBlock(&schema.FunctionToolResult{
				CallID: toolCall.CallID,
				Name:   toolCall.Name,
				Content: []*schema.FunctionToolResultContentBlock{
					{Type: schema.FunctionToolResultContentBlockTypeText, Text: &schema.UserInputText{Text: "20 degrees"}},
				},
			}),
		},
	}

	secondInput := append(firstInput, concatenated, toolResultMsg)

	gResp, err := am.Generate(ctx, secondInput, opts...)
	if err != nil {
		log.Fatalf("failed to generate, err: %v", err)
	}

	if meta := concatenated.ResponseMeta.ClaudeExtension; meta != nil {
		log.Printf("request_id: %s\n", meta.ID)
	}

	respBody, _ := sonic.MarshalIndent(gResp, "  ", "  ")
	log.Printf("body: %s\n", string(respBody))
}
Server Tool Example
package main

import (
	"context"
	"errors"
	"io"
	"log"
	"os"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticclaude"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
)

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

	am, err := agenticclaude.New(ctx, &agenticclaude.Config{
		BaseURL:   os.Getenv("CLAUDE_BASE_URL"),
		Model:     os.Getenv("CLAUDE_MODEL"),
		APIKey:    os.Getenv("CLAUDE_API_KEY"),
		MaxTokens: 4096,
	})
	if err != nil {
		log.Fatalf("failed to create agentic model, err=%v", err)
	}

	serverTools := []*agenticclaude.ServerToolConfig{
		{
			WebSearch20260209: &anthropic.WebSearchTool20260209Param{},
		},
	}

	allowedTools := []*schema.AllowedTool{
		{
			ServerTool: &schema.AllowedServerTool{
				Name: string(agenticclaude.ServerToolNameWebSearch),
			},
		},
	}

	opts := []model.Option{
		model.WithAgenticToolChoice(&schema.AgenticToolChoice{
			Type: schema.ToolChoiceForced,
			Forced: &schema.AgenticForcedToolChoice{
				Tools: allowedTools,
			},
		}),
		agenticclaude.WithServerTools(serverTools),
	}

	input := []*schema.AgenticMessage{
		schema.UserAgenticMessage("what's cloudwego/eino"),
	}

	resp, err := am.Stream(ctx, input, opts...)
	if err != nil {
		log.Fatalf("failed to stream, err: %v", err)
	}

	var msgs []*schema.AgenticMessage
	for {
		msg, recvErr := resp.Recv()
		if recvErr != nil {
			if errors.Is(recvErr, io.EOF) {
				break
			}
			log.Fatalf("failed to receive stream response, err: %v", recvErr)
		}
		msgs = append(msgs, msg)
	}

	concatenated, err := schema.ConcatAgenticMessages(msgs)
	if err != nil {
		log.Fatalf("failed to concat agentic messages, err: %v", err)
	}

	for _, block := range concatenated.ContentBlocks {
		if block.ServerToolCall != nil {
			serverToolArgs := block.ServerToolCall.Arguments.(*agenticclaude.ServerToolCallArguments)
			args, _ := sonic.MarshalIndent(serverToolArgs, "  ", "  ")
			log.Printf("server_tool_args: %s\n", string(args))
		}

		if block.ServerToolResult != nil {
			result := block.ServerToolResult.Content.(*agenticclaude.ServerToolResult)
			resultJSON, _ := sonic.MarshalIndent(result, "  ", "  ")
			log.Printf("server_tool_result: %s\n", string(resultJSON))
		}
	}

	if meta := concatenated.ResponseMeta.ClaudeExtension; meta != nil {
		log.Printf("request_id: %s\n", meta.ID)
	}

	respBody, _ := sonic.MarshalIndent(concatenated, "  ", "  ")
	log.Printf("body: %s\n", string(respBody))
}

For more examples, please refer to the examples directory.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetContentBlockCacheControl

func SetContentBlockCacheControl(block *schema.ContentBlock, ctrl *anthropic.CacheControlEphemeralParam) *schema.ContentBlock

SetContentBlockCacheControl sets a cache control on a content block. When a manual control is set, the top-level auto-cache will not override it.

func SetToolInfoCacheControl

func SetToolInfoCacheControl(toolInfo *schema.ToolInfo, ctrl *anthropic.CacheControlEphemeralParam) *schema.ToolInfo

SetToolInfoCacheControl sets a cache control on a tool info. When a manual control is set, the top-level auto-cache will not override it.

func WithCustomHeaders

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

WithCustomHeaders specifies custom HTTP headers to include in API requests.

func WithExtraFields

func WithExtraFields(fields map[string]any) model.Option

WithExtraFields sets extra fields to include in the request body. These fields will be merged into the top-level JSON request body, overriding any existing fields with the same key.

Example:

WithExtraFields(map[string]any{
    "service_tier": "default",
    "metadata": map[string]any{"user_id": "user_123"},
})

The resulting request body will be:

{
    "model": "claude-sonnet-4-20250514",
    "messages": [...],
    "service_tier": "default",
    "metadata": {"user_id": "user_123"}
}

func WithRequestTimeout added in v0.1.3

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 WithServerTools

func WithServerTools(tools []*ServerToolConfig) model.Option

WithServerTools specifies server-side tools available to the model.

Types

type BashCodeExecutionArguments

type BashCodeExecutionArguments struct {
	Command string `json:"command,omitempty" mapstructure:"command,omitempty"`
}

type BashCodeExecutionResult

type BashCodeExecutionResult struct {
	Type   BashCodeExecutionResultType   `json:"type,omitempty" mapstructure:"type,omitempty"`
	Result *BashCodeExecutionResultBlock `json:"result,omitempty" mapstructure:"result,omitempty"`
	Error  *BashCodeExecutionResultError `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type BashCodeExecutionResultBlock

type BashCodeExecutionResultBlock struct {
	Content    []*CodeExecutionOutput `json:"content,omitempty" mapstructure:"content,omitempty"`
	Stdout     string                 `json:"stdout,omitempty" mapstructure:"stdout,omitempty"`
	Stderr     string                 `json:"stderr,omitempty" mapstructure:"stderr,omitempty"`
	ReturnCode int64                  `json:"return_code,omitempty" mapstructure:"return_code,omitempty"`
}

type BashCodeExecutionResultError

type BashCodeExecutionResultError struct {
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
}

type BashCodeExecutionResultType

type BashCodeExecutionResultType string
const (
	BashCodeExecutionResultTypeResult BashCodeExecutionResultType = "bash_code_execution_result"
	BashCodeExecutionResultTypeError  BashCodeExecutionResultType = "bash_code_execution_tool_result_error"
)

type BedrockConfig

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

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

	// SessionToken is your Bedrock API Session Token
	// Obtain from: https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
	// Optional.
	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.
	Profile string

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

type CodeExecutionArguments

type CodeExecutionArguments struct {
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
}

type CodeExecutionOutput

type CodeExecutionOutput struct {
	FileID string `json:"file_id,omitempty" mapstructure:"file_id,omitempty"`
}

type CodeExecutionResult

type CodeExecutionResult struct {
	Type            CodeExecutionResultType            `json:"type,omitempty" mapstructure:"type,omitempty"`
	Result          *CodeExecutionResultBlock          `json:"result,omitempty" mapstructure:"result,omitempty"`
	EncryptedResult *EncryptedCodeExecutionResultBlock `json:"encrypted_result,omitempty" mapstructure:"encrypted_result,omitempty"`
	Error           *CodeExecutionResultError          `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type CodeExecutionResultBlock

type CodeExecutionResultBlock struct {
	Content    []*CodeExecutionOutput `json:"content,omitempty" mapstructure:"content,omitempty"`
	Stdout     string                 `json:"stdout,omitempty" mapstructure:"stdout,omitempty"`
	Stderr     string                 `json:"stderr,omitempty" mapstructure:"stderr,omitempty"`
	ReturnCode int64                  `json:"return_code,omitempty" mapstructure:"return_code,omitempty"`
}

type CodeExecutionResultError

type CodeExecutionResultError struct {
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
}

type CodeExecutionResultType

type CodeExecutionResultType string
const (
	CodeExecutionResultTypeResult    CodeExecutionResultType = "code_execution_result"
	CodeExecutionResultTypeEncrypted CodeExecutionResultType = "encrypted_code_execution_result"
	CodeExecutionResultTypeError     CodeExecutionResultType = "code_execution_tool_result_error"
)

type Config

type Config struct {
	// HTTPClient specifies the client to send HTTP requests.
	// It is not applied when using Google Vertex AI.
	// Optional.
	HTTPClient *http.Client

	// RequestTimeout specifies the timeout for each API request.
	// Optional.
	RequestTimeout time.Duration

	// ByBedrock specifies the configuration for using AWS Bedrock.
	// Optional.
	ByBedrock *BedrockConfig

	// ByGoogleVertexAI specifies the configuration for using Google Vertex AI.
	// Optional.
	ByGoogleVertexAI *GoogleVertexAIConfig

	// BaseURL is the custom API endpoint URL
	// Use this to specify a different API endpoint, e.g., for proxies or enterprise setups
	// Optional.
	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.
	MaxTokens int

	// StopSequences specifies custom stop sequences
	// The model will stop generating when it encounters any of these sequences
	// Optional.
	StopSequences []string

	// DisableParallelToolUse specifies whether to disable parallel tool use.
	// It only takes effect when AgenticToolChoice is set.
	// Optional.
	DisableParallelToolUse *bool

	// Thinking specifies the configuration for Claude thinking mode.
	// Optional.
	Thinking *anthropic.ThinkingConfigParamUnion

	// CustomHeaders specifies custom HTTP headers to include in API requests.
	// CustomHeaders allows passing additional metadata or authentication information.
	// Optional.
	CustomHeaders map[string]string

	// ExtraFields specifies extra fields to include in the request body.
	// These fields will be merged into the top-level JSON request body, overriding any existing fields with the same key.
	// Optional.
	//
	// Example:
	//
	//	ExtraFields: map[string]any{
	//	    "reasoning_effort": "high",
	//	    "service_tier": "default",
	//	}
	//
	// The resulting request body will be:
	//
	//	{
	//	    "model": "o1",
	//	    "messages": [...],
	//	    "reasoning_effort": "high",
	//	    "service_tier": "default"
	//	}
	ExtraFields map[string]any

	// CacheControl configures automatic prompt caching behavior.
	// Top-level cache control automatically applies a cache_control marker to the last
	// cacheable block in the request.
	// Optional.
	CacheControl *anthropic.CacheControlEphemeralParam
}

type EncryptedCodeExecutionResultBlock

type EncryptedCodeExecutionResultBlock struct {
	Content         []*CodeExecutionOutput `json:"content,omitempty" mapstructure:"content,omitempty"`
	EncryptedStdout string                 `json:"encrypted_stdout,omitempty" mapstructure:"encrypted_stdout,omitempty"`
	Stderr          string                 `json:"stderr,omitempty" mapstructure:"stderr,omitempty"`
	ReturnCode      int64                  `json:"return_code,omitempty" mapstructure:"return_code,omitempty"`
}

type GoogleVertexAIConfig

type GoogleVertexAIConfig struct {
	// ProjectID is your Google Cloud project ID.
	// Required for Google Vertex AI requests. If not set, automatically detected
	// from ANTHROPIC_VERTEX_PROJECT_ID, GOOGLE_CLOUD_PROJECT, or GCLOUD_PROJECT
	// environment variables.
	ProjectID string

	// Region is the Vertex AI region (e.g., "us-east5").
	// Required for Google Vertex AI requests. If not set, automatically detected
	// from CLOUD_ML_REGION environment variable.
	// See: https://claude.ai/docs/en/google-vertex-ai
	Region string
}

type Model

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

func New

func New(ctx context.Context, cfg *Config) (*Model, error)

func (*Model) Generate

func (m *Model) Generate(ctx context.Context, input []*schema.AgenticMessage, opts ...model.Option) (outMsg *schema.AgenticMessage, err error)

func (*Model) GetType

func (m *Model) GetType() string

func (*Model) IsCallbacksEnabled

func (m *Model) IsCallbacksEnabled() bool

func (*Model) Stream

func (m *Model) Stream(ctx context.Context, input []*schema.AgenticMessage, opts ...model.Option) (outStream *schema.StreamReader[*schema.AgenticMessage], err error)

type ServerToolCallArguments

type ServerToolCallArguments struct {
	WebSearch               *WebSearchArguments               `json:"web_search,omitempty" mapstructure:"web_search,omitempty"`
	WebFetch                *WebFetchArguments                `json:"web_fetch,omitempty" mapstructure:"web_fetch,omitempty"`
	CodeExecution           *CodeExecutionArguments           `json:"code_execution,omitempty" mapstructure:"code_execution,omitempty"`
	BashCodeExecution       *BashCodeExecutionArguments       `json:"bash_code_execution,omitempty" mapstructure:"bash_code_execution,omitempty"`
	TextEditorCodeExecution *TextEditorCodeExecutionArguments `json:"text_editor_code_execution,omitempty" mapstructure:"text_editor_code_execution,omitempty"`
	ToolSearchToolBm25      *ToolSearchToolBm25Arguments      `json:"tool_search_tool_bm25,omitempty" mapstructure:"tool_search_tool_bm25,omitempty"`
	ToolSearchToolRegex     *ToolSearchToolRegexArguments     `json:"tool_search_tool_regex,omitempty" mapstructure:"tool_search_tool_regex,omitempty"`
}

type ServerToolConfig

type ServerToolConfig struct {
	// WebSearch20260209 specifies the web search server tool with 20260209 version.
	WebSearch20260209 *anthropic.WebSearchTool20260209Param
	// WebFetch20260309 specifies the web fetch server tool with 20260309 version.
	WebFetch20260309 *anthropic.WebFetchTool20260309Param
	// CodeExecution20260120 specifies the code execution server tool with 20260120 version.
	// This single request-side tool enables the runtime server tool names
	// "code_execution", "bash_code_execution", and "text_editor_code_execution".
	CodeExecution20260120 *anthropic.CodeExecutionTool20260120Param
	// ToolSearchToolBm25_20251119 specifies the BM25 tool search server tool with
	// 20251119 version.
	ToolSearchToolBm25_20251119 *anthropic.ToolSearchToolBm25_20251119Param
	// ToolSearchToolRegex20251119 specifies the regex tool search server tool with
	// 20251119 version.
	ToolSearchToolRegex20251119 *anthropic.ToolSearchToolRegex20251119Param
}

type ServerToolName

type ServerToolName string
const (
	ServerToolNameWebSearch               ServerToolName = "web_search"
	ServerToolNameWebFetch                ServerToolName = "web_fetch"
	ServerToolNameCodeExecution           ServerToolName = "code_execution"
	ServerToolNameBashCodeExecution       ServerToolName = "bash_code_execution"
	ServerToolNameTextEditorCodeExecution ServerToolName = "text_editor_code_execution"
	ServerToolNameToolSearchToolBm25      ServerToolName = "tool_search_tool_bm25"
	ServerToolNameToolSearchToolRegex     ServerToolName = "tool_search_tool_regex"
)

type ServerToolResult

type ServerToolResult struct {
	WebSearch               *WebSearchResult               `json:"web_search,omitempty" mapstructure:"web_search,omitempty"`
	WebFetch                *WebFetchResult                `json:"web_fetch,omitempty" mapstructure:"web_fetch,omitempty"`
	CodeExecution           *CodeExecutionResult           `json:"code_execution,omitempty" mapstructure:"code_execution,omitempty"`
	BashCodeExecution       *BashCodeExecutionResult       `json:"bash_code_execution,omitempty" mapstructure:"bash_code_execution,omitempty"`
	TextEditorCodeExecution *TextEditorCodeExecutionResult `json:"text_editor_code_execution,omitempty" mapstructure:"text_editor_code_execution,omitempty"`
	ToolSearchToolBm25      *ToolSearchToolResult          `json:"tool_search_tool_bm25,omitempty" mapstructure:"tool_search_tool_bm25,omitempty"`
	ToolSearchToolRegex     *ToolSearchToolResult          `json:"tool_search_tool_regex,omitempty" mapstructure:"tool_search_tool_regex,omitempty"`
}

type TextEditorCodeExecutionArguments

type TextEditorCodeExecutionArguments struct {
	Command  string `json:"command,omitempty" mapstructure:"command,omitempty"`
	Path     string `json:"path,omitempty" mapstructure:"path,omitempty"`
	FileText string `json:"file_text,omitempty" mapstructure:"file_text,omitempty"`
	OldStr   string `json:"old_str,omitempty" mapstructure:"old_str,omitempty"`
	NewStr   string `json:"new_str,omitempty" mapstructure:"new_str,omitempty"`
}

type TextEditorCodeExecutionCreateResult

type TextEditorCodeExecutionCreateResult struct {
	IsFileUpdate bool `json:"is_file_update,omitempty" mapstructure:"is_file_update,omitempty"`
}

type TextEditorCodeExecutionResult

type TextEditorCodeExecutionResult struct {
	Type       TextEditorCodeExecutionResultType        `json:"type,omitempty" mapstructure:"type,omitempty"`
	View       *TextEditorCodeExecutionViewResult       `json:"view,omitempty" mapstructure:"view,omitempty"`
	Create     *TextEditorCodeExecutionCreateResult     `json:"create,omitempty" mapstructure:"create,omitempty"`
	StrReplace *TextEditorCodeExecutionStrReplaceResult `json:"str_replace,omitempty" mapstructure:"str_replace,omitempty"`
	Error      *TextEditorCodeExecutionResultError      `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type TextEditorCodeExecutionResultError

type TextEditorCodeExecutionResultError struct {
	Code    string `json:"code,omitempty" mapstructure:"code,omitempty"`
	Message string `json:"message,omitempty" mapstructure:"message,omitempty"`
}

type TextEditorCodeExecutionResultType

type TextEditorCodeExecutionResultType string
const (
	TextEditorCodeExecutionResultTypeError      TextEditorCodeExecutionResultType = "text_editor_code_execution_tool_result_error"
	TextEditorCodeExecutionResultTypeCreate     TextEditorCodeExecutionResultType = "text_editor_code_execution_create_result"
	TextEditorCodeExecutionResultTypeStrReplace TextEditorCodeExecutionResultType = "text_editor_code_execution_str_replace_result"
	TextEditorCodeExecutionResultTypeView       TextEditorCodeExecutionResultType = "text_editor_code_execution_view_result"
)

type TextEditorCodeExecutionStrReplaceResult

type TextEditorCodeExecutionStrReplaceResult struct {
	OldStart int64    `json:"oldStart,omitempty" mapstructure:"oldStart,omitempty"`
	OldLines int64    `json:"oldLines,omitempty" mapstructure:"oldLines,omitempty"`
	NewStart int64    `json:"newStart,omitempty" mapstructure:"newStart,omitempty"`
	NewLines int64    `json:"newLines,omitempty" mapstructure:"newLines,omitempty"`
	Lines    []string `json:"lines,omitempty" mapstructure:"lines,omitempty"`
}

type TextEditorCodeExecutionViewResult

type TextEditorCodeExecutionViewResult struct {
	FileType   string `json:"file_type,omitempty" mapstructure:"file_type,omitempty"`
	Content    string `json:"content,omitempty" mapstructure:"content,omitempty"`
	NumLines   int64  `json:"numLines,omitempty" mapstructure:"numLines,omitempty"`
	StartLine  int64  `json:"startLine,omitempty" mapstructure:"startLine,omitempty"`
	TotalLines int64  `json:"totalLines,omitempty" mapstructure:"totalLines,omitempty"`
}

type ToolSearchToolBm25Arguments

type ToolSearchToolBm25Arguments struct {
	Query string `json:"query,omitempty" mapstructure:"query,omitempty"`
}

type ToolSearchToolReference

type ToolSearchToolReference struct {
	ToolName string `json:"tool_name,omitempty" mapstructure:"tool_name,omitempty"`
}

type ToolSearchToolRegexArguments

type ToolSearchToolRegexArguments struct {
	Query string `json:"query,omitempty" mapstructure:"query,omitempty"`
}

type ToolSearchToolResult

type ToolSearchToolResult struct {
	Type         ToolSearchToolResultType    `json:"type,omitempty" mapstructure:"type,omitempty"`
	SearchResult *ToolSearchToolSearchResult `json:"search_result,omitempty" mapstructure:"search_result,omitempty"`
	Error        *ToolSearchToolResultError  `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type ToolSearchToolResultError

type ToolSearchToolResultError struct {
	Code    string `json:"code,omitempty" mapstructure:"code,omitempty"`
	Message string `json:"message,omitempty" mapstructure:"message,omitempty"`
}

type ToolSearchToolResultType

type ToolSearchToolResultType string
const (
	ToolSearchToolResultTypeSearchResult ToolSearchToolResultType = "tool_search_tool_search_result"
	ToolSearchToolResultTypeError        ToolSearchToolResultType = "tool_search_tool_result_error"
)

type ToolSearchToolSearchResult

type ToolSearchToolSearchResult struct {
	ToolReferences []*ToolSearchToolReference `json:"tool_references,omitempty" mapstructure:"tool_references,omitempty"`
}

type WebFetchArguments

type WebFetchArguments struct {
	URL string `json:"url,omitempty" mapstructure:"url,omitempty"`
}

type WebFetchDocument

type WebFetchDocument struct {
	Source    *WebFetchDocumentSource    `json:"source,omitempty" mapstructure:"source,omitempty"`
	Title     string                     `json:"title,omitempty" mapstructure:"title,omitempty"`
	Citations *WebFetchDocumentCitations `json:"citations,omitempty" mapstructure:"citations,omitempty"`
}

type WebFetchDocumentCitations

type WebFetchDocumentCitations struct {
	Enabled bool `json:"enabled,omitempty" mapstructure:"enabled,omitempty"`
}

type WebFetchDocumentSource

type WebFetchDocumentSource struct {
	MIMEType string `json:"media_type,omitempty" mapstructure:"media_type,omitempty"`
	Data     string `json:"data,omitempty" mapstructure:"data,omitempty"`
}

type WebFetchResult

type WebFetchResult struct {
	Type   WebFetchResultType   `json:"type,omitempty" mapstructure:"type,omitempty"`
	Result *WebFetchResultBlock `json:"result,omitempty" mapstructure:"result,omitempty"`
	Error  *WebFetchResultError `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type WebFetchResultBlock

type WebFetchResultBlock struct {
	URL         string            `json:"url,omitempty" mapstructure:"url,omitempty"`
	RetrievedAt string            `json:"retrieved_at,omitempty" mapstructure:"retrieved_at,omitempty"`
	Content     *WebFetchDocument `json:"content,omitempty" mapstructure:"content,omitempty"`
}

type WebFetchResultError

type WebFetchResultError struct {
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
}

type WebFetchResultType

type WebFetchResultType string
const (
	WebFetchResultTypeResult WebFetchResultType = "web_fetch_result"
	WebFetchResultTypeError  WebFetchResultType = "web_fetch_tool_result_error"
)

type WebSearchArguments

type WebSearchArguments struct {
	Query string `json:"query,omitempty" mapstructure:"query,omitempty"`
}

type WebSearchResult

type WebSearchResult struct {
	Type   WebSearchResultType   `json:"type,omitempty" mapstructure:"type,omitempty"`
	Result *WebSearchResultBlock `json:"result,omitempty" mapstructure:"result,omitempty"`
	Error  *WebSearchResultError `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type WebSearchResultBlock

type WebSearchResultBlock struct {
	Content []*WebSearchResultItem `json:"content,omitempty" mapstructure:"content,omitempty"`
}

type WebSearchResultError

type WebSearchResultError struct {
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
}

type WebSearchResultItem

type WebSearchResultItem struct {
	Title            string `json:"title,omitempty" mapstructure:"title,omitempty"`
	URL              string `json:"url,omitempty" mapstructure:"url,omitempty"`
	EncryptedContent string `json:"encrypted_content,omitempty" mapstructure:"encrypted_content,omitempty"`
	PageAge          string `json:"page_age,omitempty" mapstructure:"page_age,omitempty"`
}

type WebSearchResultType

type WebSearchResultType string
const (
	WebSearchResultTypeResult WebSearchResultType = "web_search_result"
	WebSearchResultTypeError  WebSearchResultType = "web_search_tool_result_error"
)

Directories

Path Synopsis
examples
cache command
generate command

Jump to

Keyboard shortcuts

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