agenticark

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

README

Volcengine Ark Agentic Model

A Volcengine Ark 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 responses api
  • Support for streaming responses
  • Support for tool calling (Function Tools, MCP Tools, Server Tools)
  • Support for Prefix Cache and auto-caching for multi-turn conversations

Installation

go get github.com/cloudwego/eino-ext/components/model/agenticark@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/agenticark"
	"github.com/cloudwego/eino/schema"
)

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

	// Get ARK_API_KEY and ARK_MODEL_ID: https://www.volcengine.com/docs/82379/1399008
	am, err := agenticark.New(ctx, &agenticark.Config{
		Model:  os.Getenv("ARK_MODEL_ID"),
		APIKey: os.Getenv("ARK_API_KEY"),
	})
	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)
	if err != nil {
		log.Fatalf("failed to generate, err: %v", err)
	}

	meta := msg.ResponseMeta.Extension.(*agenticark.ResponseMetaExtension)

	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 agenticark.Config struct:

type Config struct {
    // Timeout specifies the maximum duration to wait for API responses.
    // If HTTPClient is set, Timeout will not be used.
    // Optional.
    Timeout *time.Duration
    
    // HTTPClient specifies the HTTP client used to send requests.
    // If HTTPClient is set, Timeout will not be used.
    // Optional. Default: &http.Client{Timeout: Timeout}
    HTTPClient *http.Client
    
    // RetryTimes specifies the number of retry attempts for failed API calls.
    // Optional.
    RetryTimes *int
    
    // BaseURL specifies the base URL for the Ark service endpoint.
    // Optional.
    BaseURL string
    
    // Region specifies the geographic region where the Ark service is located.
    // Optional.
    Region string
    
    // APIKey specifies the API key for authentication.
    // Either APIKey or both AccessKey and SecretKey must be provided.
    // APIKey takes precedence if both authentication methods are provided.
    // For details, see: https://www.volcengine.com/docs/82379/1298459
    APIKey string
    
    // AccessKey specifies the access key for authentication.
    // Must be used together with SecretKey.
    AccessKey string
    
    // SecretKey specifies the secret key for authentication.
    // Must be used together with AccessKey.
    SecretKey string
    
    // Model specifies the identifier of the model endpoint on the Ark platform.
    // For details, see: https://www.volcengine.com/docs/82379/1298454
    // Required.
    Model string
    
    // MaxTokens specifies the maximum number of tokens to generate in the response.
    // Optional.
    MaxTokens *int
    
    // Temperature controls the randomness of the model's output.
    // Lower values (e.g., 0.2) make the output more focused and deterministic.
    // Higher values (e.g., 1.0) make the output more creative and varied.
    // Range: 0.0 to 2.0.
    // Optional.
    Temperature *float32
    
    // TopP controls diversity via nucleus sampling, an alternative to Temperature.
    // TopP specifies the cumulative probability threshold for token selection.
    // For example, 0.1 means only tokens comprising the top 10% probability mass are considered.
    // We recommend using either Temperature or TopP, but not both.
    // Range: 0.0 to 1.0.
    // Optional.
    TopP *float32
    
    // ServiceTier specifies the service tier to use for the request.
    // Optional.
    ServiceTier *responses.ResponsesServiceTier_Enum
    
    // Text specifies text generation configuration options.
    // Optional.
    Text *responses.ResponsesText
    
    // Thinking controls whether the model uses deep thinking mode.
    // Optional.
    Thinking *responses.ResponsesThinking
    
    // Reasoning specifies the effort level for the model's reasoning process.
    // Optional.
    Reasoning *responses.ResponsesReasoning
    
    // EnablePassBackReasoning controls whether the model passes back reasoning items in the next request.
    // Note that doubao 1.6 does not support pass back reasoning.
    // Optional. Default: true
    EnablePassBackReasoning *bool
    
    // MaxToolCalls specifies the maximum number of tool calls the model can make in a single response.
    // Optional.
    MaxToolCalls *int64
    
    // ParallelToolCalls determines whether the model can invoke multiple tools simultaneously.
    // Optional.
    ParallelToolCalls *bool
    
    // EnableAutoCache controls whether auto-caching for multi-turn conversations is active for the model.
    // When enabled, conversation turns are stored, and the model automatically maintains context
    // by locating the most recent cached message in the input (via Response ID in ResponseMeta).
    // This cached message and all preceding inputs are excluded from the request.
    // If the cached message becomes invalid, you can call InvalidateMessageCaches to temporarily invalidate the cache.
    // Optional.
    EnableAutoCache bool

    // ExpireAtSec specifies the expiration Unix timestamp (in seconds) for auto caching or prefix cache.
    // Optional.
    ExpireAtSec *int64
    
    // ContextManagement specifies context management strategies to help the model utilize the context window effectively.
    // Supports clearing thinking blocks and tool call content.
    // Optional.
    ContextManagement *contextmanagement.ContextManagement
    
    // CustomHeaders specifies custom HTTP headers to include in API requests.
    // CustomHeaders allows passing additional metadata or authentication information.
    // Optional.
    CustomHeaders map[string]string
}

Extension Fields

Several fields of the Eino agentic schema are typed any so that each model implementation can attach its own provider-specific data. When you consume responses produced by this package, you must type-assert these fields to the concrete types defined here (all under the agenticark package).

ResponseMeta

The schema's AgenticResponseMeta does not define an Ark-specific field, so this package populates the generic Extension any field of *schema.AgenticMessage.ResponseMeta with a *agenticark.ResponseMetaExtension. Assert it to that type before use.

// agenticark.ResponseMetaExtension
type ResponseMetaExtension struct {
	ID                 string             // Ark response ID
	Status             ResponseStatus     // in_progress / completed / incomplete / failed
	IncompleteDetails  *IncompleteDetails // populated when Status is incomplete
	Error              *ResponseError     // populated when the response carries an error
	PreviousResponseID string             // ID of the previous response in a multi-turn chain
	Thinking           *ResponseThinking  // thinking mode reported by the server
	ExpireAt           *int64             // Unix timestamp when the cached response expires
	ServiceTier        ServiceTier        // auto / default
	StreamingError     *StreamingResponseError // error surfaced during streaming
}
meta := msg.ResponseMeta.Extension.(*agenticark.ResponseMetaExtension)
AssistantGenText Extension

UserInputText (user-supplied text) carries no extension. Only model-generated AssistantGenText blocks do. The schema defines no Ark-specific field for it, so this package populates the generic AssistantGenText.Extension any field with a *agenticark.AssistantGenTextExtension, which carries the citation/annotation data attached to the generated text.

// agenticark.AssistantGenTextExtension
type AssistantGenTextExtension struct {
	Annotations []*TextAnnotation // url_citation / doc_citation annotations on the text
}
ext := block.AssistantGenText.Extension.(*agenticark.AssistantGenTextExtension)
ServerToolCall & ServerToolResult

When server-side (built-in) tools such as web_search, image_process, doubao_app or knowledge_search are enabled, this package populates the generic ServerToolCall.Arguments any field with a *agenticark.ServerToolCallArguments and the ServerToolResult.Content any field with a *agenticark.ServerToolResult. Assert them to those concrete types.

// agenticark.ServerToolCallArguments — exactly one field is set per call
type ServerToolCallArguments struct {
	WebSearch       *WebSearchArguments       // web_search tool input
	ImageProcess    *ImageProcessArguments    // image_process tool input
	DoubaoApp       *DoubaoAppArguments       // doubao_app tool input
	KnowledgeSearch *KnowledgeSearchArguments // knowledge_search tool input
}

// agenticark.ServerToolResult — exactly one field is set per result
type ServerToolResult struct {
	ImageProcess *ImageProcessResult // image_process tool output
	DoubaoApp    *DoubaoAppResult    // doubao_app tool output
}
args := block.ServerToolCall.Arguments.(*agenticark.ServerToolCallArguments)
result := block.ServerToolResult.Content.(*agenticark.ServerToolResult)

Advanced Usage

Cache

Use EnableAutoCache to enable auto-caching for multi-turn conversations. If a cached message becomes invalid, call InvalidateMessageCaches to temporarily skip it.

For explicit prefix reuse, call CreatePrefixCache first and then pass the returned response ID with WithHeadPreviousResponseID.

expireAtSec := time.Now().Add(time.Hour).Unix()

am, err := agenticark.New(ctx, &agenticark.Config{
	Model:           os.Getenv("ARK_MODEL_ID"),
	APIKey:          os.Getenv("ARK_API_KEY"),
	EnableAutoCache: true,
	ExpireAtSec:     &expireAtSec,
})
Tool Calling

The AgenticModel supports tool calling, including Function Tools, MCP Tools, 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/agenticark"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
	"github.com/eino-contrib/jsonschema"
	"github.com/volcengine/volcengine-go-sdk/service/arkruntime/model/responses"
	"github.com/wk8/go-ordered-map/v2"
)

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

	// Get ARK_API_KEY and ARK_MODEL_ID: https://www.volcengine.com/docs/82379/1399008
	am, err := agenticark.New(ctx, &agenticark.Config{
		Model:  os.Getenv("ARK_MODEL_ID"),
		APIKey: os.Getenv("ARK_API_KEY"),
		Thinking: &responses.ResponsesThinking{
			Type: responses.ThinkingType_disabled.Enum(),
		},
	})
	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, err := sResp.Recv()
		if err != nil {
			if errors.Is(err, io.EOF) {
				break
			}
			log.Fatalf("failed to receive stream response, err: %v", err)
		}
		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]
	
	toolCall := lastBlock.FunctionToolCall
	toolResultMsg := schema.FunctionToolResultAgenticMessage(toolCall.CallID, toolCall.Name, "20 degrees")

	secondInput := append(firstInput, concatenated, toolResultMsg)

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

	meta := concatenated.ResponseMeta.Extension.(*agenticark.ResponseMetaExtension)
	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/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticark"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
	"github.com/volcengine/volcengine-go-sdk/service/arkruntime/model/responses"
)

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

	// Get ARK_API_KEY and ARK_MODEL_ID: https://www.volcengine.com/docs/82379/1399008
	am, err := agenticark.New(ctx, &agenticark.Config{
		Model:  os.Getenv("ARK_MODEL_ID"),
		APIKey: os.Getenv("ARK_API_KEY"),
	})
	if err != nil {
		log.Fatalf("failed to create agentic model, err=%v", err)
	}

	serverTools := []*agenticark.ServerToolConfig{
		{
			WebSearch: &responses.ToolWebSearch{
				Type: responses.ToolType_web_search,
			},
		},
	}

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

	opts := []model.Option{
		agenticark.WithServerTools(serverTools),
		model.WithAgenticToolChoice(&schema.AgenticToolChoice{
			Type: schema.ToolChoiceForced,
			Forced: &schema.AgenticForcedToolChoice{
				Tools: allowedTools,
			},
		}),
		agenticark.WithThinking(&responses.ResponsesThinking{
			Type: responses.ThinkingType_disabled.Enum(),
		}),
	}

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

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

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

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

	meta := concatenated.ResponseMeta.Extension.(*agenticark.ResponseMetaExtension)
	for _, block := range concatenated.ContentBlocks {
		if block.ServerToolCall == nil {
			continue
		}

		serverToolArgs := block.ServerToolCall.Arguments.(*agenticark.ServerToolCallArguments)

		args, _ := sonic.MarshalIndent(serverToolArgs, "  ", "  ")
		log.Printf("server_tool_args: %s\n", string(args))
	}

	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 GetItemStatus

func GetItemStatus(block *schema.ContentBlock) (string, bool)

func GetUserInputVideoFPS

func GetUserInputVideoFPS(block *schema.UserInputVideo) (float64, bool)

func InvalidateMessageCaches

func InvalidateMessageCaches(messages []*schema.AgenticMessage) error

InvalidateMessageCaches temporarily disables caching for the specified messages. When a message is modified or model is switched, Ark invalidates caches for that message and all subsequent ones. Call this to mark those message caches as invalid temporarily.

func SetUserInputVideoFPS

func SetUserInputVideoFPS(block *schema.UserInputVideo, fps float64)

func WithCustomHeaders

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

func WithExpireAtSec

func WithExpireAtSec(expireAtSec int64) model.Option

WithExpireAtSec sets the expiration Unix timestamp (in seconds) for auto caching or prefix cache. This option overrides the ExpireAtSec field in Config.

func WithHeadPreviousResponseID

func WithHeadPreviousResponseID(id string) model.Option

WithHeadPreviousResponseID sets a response ID from a previous ResponsesAPI call. This ID links the current request to a previous conversation context, enabling features like conversation continuation and prefix caching. In populateCache, an auto-discovered response ID from input messages takes priority over this option. The referenced response must be cached before use.

func WithMCPTools

func WithMCPTools(tools []*responses.ToolMcp) model.Option

func WithMaxToolCalls

func WithMaxToolCalls(maxToolCalls int64) model.Option

func WithParallelToolCalls

func WithParallelToolCalls(parallelToolCalls bool) model.Option

func WithReasoning

func WithReasoning(reasoning *responses.ResponsesReasoning) model.Option

func WithServerTools

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

func WithText

func WithText(text *responses.ResponsesText) model.Option

func WithThinking

func WithThinking(thinking *responses.ResponsesThinking) model.Option

Types

type AssistantGenTextExtension

type AssistantGenTextExtension struct {
	Annotations []*TextAnnotation `json:"annotations,omitempty" mapstructure:"annotations,omitempty"`
}

type CacheInfo

type CacheInfo struct {
	// ResponseID return by ResponsesAPI, it's specifies the id of prefix that can be used with [WithHeadPreviousResponseID] option.
	ResponseID string
	// Usage specifies the token usage of prefix
	Usage schema.TokenUsage
}

type Config

type Config struct {
	// Timeout specifies the maximum duration to wait for API responses.
	// If HTTPClient is set, Timeout will not be used.
	// Optional.
	Timeout *time.Duration

	// HTTPClient specifies the HTTP client used to send requests.
	// If HTTPClient is set, Timeout will not be used.
	// Optional. Default: &http.Client{Timeout: Timeout}
	HTTPClient *http.Client

	// RetryTimes specifies the number of retry attempts for failed API calls.
	// Optional.
	RetryTimes *int

	// BaseURL specifies the base URL for the Ark service endpoint.
	// Optional.
	BaseURL string

	// Region specifies the geographic region where the Ark service is located.
	// Optional.
	Region string

	// APIKey specifies the API key for authentication.
	// Either APIKey or both AccessKey and SecretKey must be provided.
	// APIKey takes precedence if both authentication methods are provided.
	// For details, see: https://www.volcengine.com/docs/82379/1298459
	APIKey string

	// AccessKey specifies the access key for authentication.
	// Must be used together with SecretKey.
	AccessKey string

	// SecretKey specifies the secret key for authentication.
	// Must be used together with AccessKey.
	SecretKey string

	// Model specifies the identifier of the model endpoint on the Ark platform.
	// For details, see: https://www.volcengine.com/docs/82379/1298454
	// Required.
	Model string

	// MaxTokens specifies the maximum number of tokens to generate in the response.
	// Optional.
	MaxTokens *int

	// Temperature controls the randomness of the model's output.
	// Lower values (e.g., 0.2) make the output more focused and deterministic.
	// Higher values (e.g., 1.0) make the output more creative and varied.
	// Range: 0.0 to 2.0.
	// Optional.
	Temperature *float32

	// TopP controls diversity via nucleus sampling, an alternative to Temperature.
	// TopP specifies the cumulative probability threshold for token selection.
	// For example, 0.1 means only tokens comprising the top 10% probability mass are considered.
	// We recommend using either Temperature or TopP, but not both.
	// Range: 0.0 to 1.0.
	// Optional.
	TopP *float32

	// ServiceTier specifies the service tier to use for the request.
	// Optional.
	ServiceTier *responses.ResponsesServiceTier_Enum

	// Text specifies text generation configuration options.
	// Optional.
	Text *responses.ResponsesText

	// Thinking controls whether the model uses deep thinking mode.
	// Optional.
	Thinking *responses.ResponsesThinking

	// Reasoning specifies the effort level for the model's reasoning process.
	// Optional.
	Reasoning *responses.ResponsesReasoning

	// EnablePassBackReasoning controls whether the model passes back reasoning items in the next request.
	// Note that doubao 1.6 does not support pass back reasoning.
	// Optional. Default: true
	EnablePassBackReasoning *bool

	// MaxToolCalls specifies the maximum number of tool calls the model can make in a single response.
	// Optional.
	MaxToolCalls *int64

	// ParallelToolCalls determines whether the model can invoke multiple tools simultaneously.
	// Optional.
	ParallelToolCalls *bool

	// EnableAutoCache controls whether auto-caching for multi-turn conversations is active for the model.
	// When enabled, conversation turns are stored, and the model automatically maintains context
	// by locating the most recent cached message in the input (via Response ID in ResponseMeta).
	// This cached message and all preceding inputs are excluded from the request.
	// If the cached message becomes invalid, you can call [InvalidateMessageCaches] to temporarily invalidate the cache.
	// Optional.
	EnableAutoCache bool

	// ExpireAtSec specifies the expiration Unix timestamp (in seconds) for auto caching or prefix cache.
	// Optional.
	ExpireAtSec *int64

	// ContextManagement specifies context management strategies to help the model utilize the context window effectively.
	// Supports clearing thinking blocks and tool call content.
	// Optional.
	ContextManagement *contextmanagement.ContextManagement

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

type ContentFilter

type ContentFilter struct {
	Type    string `json:"type,omitempty" mapstructure:"type,omitempty"`
	Details string `json:"details,omitempty" mapstructure:"details,omitempty"`
}

type CoverImage

type CoverImage struct {
	URL    string `json:"url,omitempty" mapstructure:"url,omitempty"`
	Width  *int64 `json:"width,omitempty" mapstructure:"width,omitempty"`
	Height *int64 `json:"height,omitempty" mapstructure:"height,omitempty"`
}

type DocCitation

type DocCitation struct {
	DocID           string           `json:"doc_id,omitempty" mapstructure:"doc_id,omitempty"`
	DocName         string           `json:"doc_name,omitempty" mapstructure:"doc_name,omitempty"`
	ChunkID         *int32           `json:"chunk_id,omitempty" mapstructure:"chunk_id,omitempty"`
	ChunkAttachment []map[string]any `json:"chunk_attachment,omitempty" mapstructure:"chunk_attachment,omitempty"`
}

type DoubaoAppArguments

type DoubaoAppArguments struct {
	Feature DoubaoAppFeature `json:"feature,omitempty" mapstructure:"feature,omitempty"`
}

type DoubaoAppBlock

type DoubaoAppBlock struct {
	// Index is the index of this block within DoubaoApp result.
	// Only available in streaming response.
	Index *int `json:"index,omitempty" mapstructure:"index,omitempty"`

	Type            DoubaoAppBlockType        `json:"type,omitempty" mapstructure:"type,omitempty"`
	OutputText      *DoubaoAppOutputText      `json:"output_text,omitempty" mapstructure:"output_text,omitempty"`
	ReasoningText   *DoubaoAppReasoningText   `json:"reasoning_text,omitempty" mapstructure:"reasoning_text,omitempty"`
	Search          *DoubaoAppSearch          `json:"search,omitempty" mapstructure:"search,omitempty"`
	ReasoningSearch *DoubaoAppReasoningSearch `json:"reasoning_search,omitempty" mapstructure:"reasoning_search,omitempty"`
}

type DoubaoAppBlockType

type DoubaoAppBlockType string
const (
	DoubaoAppBlockTypeOutputText      DoubaoAppBlockType = "output_text"
	DoubaoAppBlockTypeReasoningText   DoubaoAppBlockType = "reasoning_text"
	DoubaoAppBlockTypeSearch          DoubaoAppBlockType = "search"
	DoubaoAppBlockTypeReasoningSearch DoubaoAppBlockType = "reasoning_search"
)

type DoubaoAppFeature

type DoubaoAppFeature string
const (
	DoubaoAppFeatureChat            DoubaoAppFeature = "chat"
	DoubaoAppFeatureDeepChat        DoubaoAppFeature = "deep_chat"
	DoubaoAppFeatureAISearch        DoubaoAppFeature = "ai_search"
	DoubaoAppFeatureReasoningSearch DoubaoAppFeature = "reasoning_search"
)

type DoubaoAppOutputText

type DoubaoAppOutputText struct {
	ID       string `json:"id,omitempty" mapstructure:"id,omitempty"`
	ParentID string `json:"parent_id,omitempty" mapstructure:"parent_id,omitempty"`
	Text     string `json:"text,omitempty" mapstructure:"text,omitempty"`

	// Status represents the status of the output text.
	// Only available in non-streaming response.
	Status string `json:"status,omitempty" mapstructure:"status,omitempty"`
}

type DoubaoAppReasoningSearch

type DoubaoAppReasoningSearch struct {
	ID       string                   `json:"id,omitempty" mapstructure:"id,omitempty"`
	ParentID string                   `json:"parent_id,omitempty" mapstructure:"parent_id,omitempty"`
	Summary  string                   `json:"summary,omitempty" mapstructure:"summary,omitempty"`
	Queries  []string                 `json:"queries,omitempty" mapstructure:"queries,omitempty"`
	Results  []*DoubaoAppSearchResult `json:"results,omitempty" mapstructure:"results,omitempty"`

	// SearchingState represents the state of reasoning search.
	// It is only available in streaming response.
	SearchingState string `json:"searching_state,omitempty" mapstructure:"searching_state,omitempty"`

	// Status represents the status of the reasoning search.
	// It is only available in non-streaming response.
	Status string `json:"status,omitempty" mapstructure:"status,omitempty"`
}

type DoubaoAppReasoningText

type DoubaoAppReasoningText struct {
	ID            string `json:"id,omitempty" mapstructure:"id,omitempty"`
	ParentID      string `json:"parent_id,omitempty" mapstructure:"parent_id,omitempty"`
	ReasoningText string `json:"reasoning_text,omitempty" mapstructure:"reasoning_text,omitempty"`

	// Status represents the status of the reasoning text.
	// Only available in non-streaming response.
	Status string `json:"status,omitempty" mapstructure:"status,omitempty"`
}

type DoubaoAppResult

type DoubaoAppResult struct {
	Blocks []*DoubaoAppBlock `json:"blocks,omitempty" mapstructure:"blocks,omitempty"`
}

type DoubaoAppSearch

type DoubaoAppSearch struct {
	ID       string                   `json:"id,omitempty" mapstructure:"id,omitempty"`
	ParentID string                   `json:"parent_id,omitempty" mapstructure:"parent_id,omitempty"`
	Summary  string                   `json:"summary,omitempty" mapstructure:"summary,omitempty"`
	Queries  []string                 `json:"queries,omitempty" mapstructure:"queries,omitempty"`
	Results  []*DoubaoAppSearchResult `json:"results,omitempty" mapstructure:"results,omitempty"`

	// SearchingState represents the state of searching.
	// Only available in streaming response.
	SearchingState string `json:"searching_state,omitempty" mapstructure:"searching_state,omitempty"`

	// Status represents the status of the search.
	// Only available in non-streaming response.
	Status string `json:"status,omitempty" mapstructure:"status,omitempty"`
}

type DoubaoAppSearchResult

type DoubaoAppSearchResult struct {
	Title    string `json:"title,omitempty" mapstructure:"title,omitempty"`
	URL      string `json:"url,omitempty" mapstructure:"url,omitempty"`
	SiteName string `json:"site_name,omitempty" mapstructure:"site_name,omitempty"`
}

type ImageProcessAction

type ImageProcessAction string
const (
	ImageProcessActionPoint     ImageProcessAction = "point"
	ImageProcessActionGrounding ImageProcessAction = "grounding"
	ImageProcessActionRotate    ImageProcessAction = "rotate"
	ImageProcessActionZoom      ImageProcessAction = "zoom"
)

type ImageProcessArguments

type ImageProcessArguments struct {
	ActionType ImageProcessAction     `json:"action_type,omitempty" mapstructure:"action_type,omitempty"`
	Point      *ImageProcessPoint     `json:"point,omitempty" mapstructure:"point,omitempty"`
	Grounding  *ImageProcessGrounding `json:"grounding,omitempty" mapstructure:"grounding,omitempty"`
	Rotate     *ImageProcessRotate    `json:"rotate,omitempty" mapstructure:"rotate,omitempty"`
	Zoom       *ImageProcessZoom      `json:"zoom,omitempty" mapstructure:"zoom,omitempty"`
}

type ImageProcessGrounding

type ImageProcessGrounding struct {
	ImageIndex int32  `json:"image_index,omitempty" mapstructure:"image_index,omitempty"`
	BboxStr    string `json:"bbox_str,omitempty" mapstructure:"bbox_str,omitempty"`
	Crop       bool   `json:"crop,omitempty" mapstructure:"crop,omitempty"`
}

type ImageProcessPoint

type ImageProcessPoint struct {
	ImageIndex int32  `json:"image_index,omitempty" mapstructure:"image_index,omitempty"`
	Points     string `json:"points,omitempty" mapstructure:"points,omitempty"`
	DrawLine   bool   `json:"draw_line,omitempty" mapstructure:"draw_line,omitempty"`
}

type ImageProcessResult

type ImageProcessResult struct {
	Action *ImageProcessResultAction `json:"action,omitempty" mapstructure:"action,omitempty"`
	Error  *ImageProcessResultError  `json:"error,omitempty" mapstructure:"error,omitempty"`
}

type ImageProcessResultAction

type ImageProcessResultAction struct {
	Type           ImageProcessAction `json:"type,omitempty" mapstructure:"type,omitempty"`
	ResultImageURL string             `json:"result_image_url,omitempty" mapstructure:"result_image_url,omitempty"`
}

type ImageProcessResultError

type ImageProcessResultError struct {
	Message string `json:"message,omitempty" mapstructure:"message,omitempty"`
}

type ImageProcessRotate

type ImageProcessRotate struct {
	ImageIndex int32 `json:"image_index,omitempty" mapstructure:"image_index,omitempty"`
	Degree     int32 `json:"degree,omitempty" mapstructure:"degree,omitempty"`
}

type ImageProcessZoom

type ImageProcessZoom struct {
	ImageIndex int32   `json:"image_index,omitempty" mapstructure:"image_index,omitempty"`
	BboxStr    string  `json:"bbox_str,omitempty" mapstructure:"bbox_str,omitempty"`
	Scale      float64 `json:"scale,omitempty" mapstructure:"scale,omitempty"`
}

type IncompleteDetails

type IncompleteDetails struct {
	Reason        string         `json:"reason,omitempty" mapstructure:"reason,omitempty"`
	ContentFilter *ContentFilter `json:"content_filter,omitempty" mapstructure:"content_filter,omitempty"`
}

type KnowledgeSearchArguments

type KnowledgeSearchArguments struct {
	KnowledgeResourceID string   `json:"knowledge_resource_id,omitempty" mapstructure:"knowledge_resource_id,omitempty"`
	Queries             []string `json:"queries,omitempty" mapstructure:"queries,omitempty"`
}

type Model

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

func New

func New(_ context.Context, config *Config) (*Model, error)

func (*Model) CreatePrefixCache

func (m *Model) CreatePrefixCache(ctx context.Context, prefix []*schema.AgenticMessage,
	opts ...model.Option) (info *CacheInfo, err error)

CreatePrefixCache creates a prefix context on the server side. The server will input the prefix cached context and this turn of input into the model for processing. This improves efficiency by reducing token usage and request size.

Parameters:

  • ctx: The context for the request
  • prefix: Initial messages to be cached as prefix context

The expiration Unix timestamp (in seconds) for the cached prefix can be set via WithExpireAtSec option or the ExpireAtSec field in Config. Defaults to 3 days from now if not specified.

Returns:

  • info: Information about the created prefix cache, including the context ID and token usage
  • err: Any error encountered during the operation

ref: https://www.volcengine.com/docs/82379/1396490#_1-%E5%88%9B%E5%BB%BA%E5%89%8D%E7%BC%80%E7%BC%93%E5%AD%98

Note:

  • It is unavailable for doubao models of version 1.6 and above.

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)

func (*Model) WithTools

func (m *Model) WithTools(functionTools []*schema.ToolInfo) (model.AgenticModel, error)

type ResponseError

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

type ResponseMetaExtension

type ResponseMetaExtension struct {
	ID                 string             `json:"id,omitempty" mapstructure:"id,omitempty"`
	Status             ResponseStatus     `json:"status,omitempty" mapstructure:"status,omitempty"`
	IncompleteDetails  *IncompleteDetails `json:"incomplete_details" mapstructure:"incomplete_details,omitempty"`
	Error              *ResponseError     `json:"error" mapstructure:"error,omitempty"`
	PreviousResponseID string             `json:"previous_response_id,omitempty" mapstructure:"previous_response_id,omitempty"`
	Thinking           *ResponseThinking  `json:"thinking,omitempty" mapstructure:"thinking,omitempty"`
	ExpireAt           *int64             `json:"expire_at,omitempty" mapstructure:"expire_at,omitempty"`
	ServiceTier        ServiceTier        `json:"service_tier,omitempty" mapstructure:"service_tier,omitempty"`

	StreamingError *StreamingResponseError `json:"streaming_error,omitempty" mapstructure:"streaming_error,omitempty"`
}

type ResponseStatus

type ResponseStatus string
const (
	ResponseStatusInProgress ResponseStatus = "in_progress"
	ResponseStatusCompleted  ResponseStatus = "completed"
	ResponseStatusIncomplete ResponseStatus = "incomplete"
	ResponseStatusFailed     ResponseStatus = "failed"
)

type ResponseThinking

type ResponseThinking struct {
	Type ThinkingType `json:"type,omitempty" mapstructure:"type,omitempty"`
}

type ServerToolCallArguments

type ServerToolCallArguments struct {
	WebSearch       *WebSearchArguments       `json:"web_search,omitempty" mapstructure:"web_search,omitempty"`
	ImageProcess    *ImageProcessArguments    `json:"image_process,omitempty" mapstructure:"image_process,omitempty"`
	DoubaoApp       *DoubaoAppArguments       `json:"doubao_app,omitempty" mapstructure:"doubao_app,omitempty"`
	KnowledgeSearch *KnowledgeSearchArguments `json:"knowledge_search,omitempty" mapstructure:"knowledge_search,omitempty"`
}

type ServerToolConfig

type ServerToolConfig struct {
	WebSearch       *responses.ToolWebSearch
	ImageProcess    *responses.ToolImageProcess
	DoubaoApp       *responses.ToolDoubaoApp
	KnowledgeSearch *responses.ToolKnowledgeSearch
}

type ServerToolName

type ServerToolName string
const (
	ServerToolNameWebSearch       ServerToolName = "web_search"
	ServerToolNameImageProcess    ServerToolName = "image_process"
	ServerToolNameDoubaoApp       ServerToolName = "doubao_app"
	ServerToolNameKnowledgeSearch ServerToolName = "knowledge_search"
)

type ServerToolResult

type ServerToolResult struct {
	ImageProcess *ImageProcessResult `json:"image_process,omitempty" mapstructure:"image_process,omitempty"`
	DoubaoApp    *DoubaoAppResult    `json:"doubao_app,omitempty" mapstructure:"doubao_app,omitempty"`
}

type ServiceTier

type ServiceTier string
const (
	ServiceTierAuto    ServiceTier = "auto"
	ServiceTierDefault ServiceTier = "default"
)

type StreamingResponseError

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

type TextAnnotation

type TextAnnotation struct {
	Index int `json:"index,omitempty" mapstructure:"index,omitempty"`

	Type TextAnnotationType `json:"type,omitempty" mapstructure:"type,omitempty"`

	URLCitation *URLCitation `json:"url_citation,omitempty" mapstructure:"url_citation,omitempty"`
	DocCitation *DocCitation `json:"doc_citation,omitempty" mapstructure:"doc_citation,omitempty"`
}

type TextAnnotationType

type TextAnnotationType string
const (
	TextAnnotationTypeURLCitation TextAnnotationType = "url_citation"
	TextAnnotationTypeDocCitation TextAnnotationType = "doc_citation"
)

type ThinkingType

type ThinkingType string
const (
	ThinkingTypeAuto     ThinkingType = "auto"
	ThinkingTypeEnabled  ThinkingType = "enabled"
	ThinkingTypeDisabled ThinkingType = "disabled"
)

type URLCitation

type URLCitation struct {
	Title         string      `json:"title,omitempty" mapstructure:"title,omitempty"`
	URL           string      `json:"url,omitempty" mapstructure:"url,omitempty"`
	LogoURL       string      `json:"logo_url,omitempty" mapstructure:"logo_url,omitempty"`
	MobileURL     string      `json:"mobile_url,omitempty" mapstructure:"mobile_url,omitempty"`
	SiteName      string      `json:"site_name,omitempty" mapstructure:"site_name,omitempty"`
	PublishTime   string      `json:"publish_time,omitempty" mapstructure:"publish_time,omitempty"`
	CoverImage    *CoverImage `json:"cover_image,omitempty" mapstructure:"cover_image,omitempty"`
	Summary       string      `json:"summary,omitempty" mapstructure:"summary,omitempty"`
	FreshnessInfo string      `json:"freshness_info,omitempty" mapstructure:"freshness_info,omitempty"`
}

type WebSearchAction

type WebSearchAction string
const (
	WebSearchActionSearch WebSearchAction = "search"
)

type WebSearchArguments

type WebSearchArguments struct {
	ActionType WebSearchAction `json:"action_type,omitempty" mapstructure:"action_type,omitempty"`
	Search     *WebSearchQuery `json:"search,omitempty" mapstructure:"search,omitempty"`
}

type WebSearchQuery

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

Directories

Path Synopsis
examples
generate command
prefix_cache command
session_cache command
stream_with_function_tool command
* Copyright 2026 CloudWeGo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
* Copyright 2026 CloudWeGo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.

Jump to

Keyboard shortcuts

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