agenticopenai

package module
v0.2.2 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

OpenAI Agentic Model

An OpenAI model implementation for Eino that implements the AgenticModel component interface. This package provides two model implementations: Chat (Chat Completions API) and Responses (Responses API), enabling seamless integration with Eino's Agent capabilities.

Features

  • Implements github.com/cloudwego/eino/components/model.AgenticModel
  • Easy integration with Eino's agent system
  • Configurable model parameters
  • Support for both Chat Completions API and 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
  • Support for Azure OpenAI Service

Installation

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

Quick Start

Responses API
package main

import (
	"context"
	"log"
	"os"

	"github.com/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticopenai"
	"github.com/cloudwego/eino/schema"
)

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

	am, err := agenticopenai.NewResponsesModel(ctx, &agenticopenai.ResponsesConfig{
		APIKey: os.Getenv("OPENAI_API_KEY"),
		Model:  os.Getenv("OPENAI_MODEL_ID"),
	})
	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)
	}

	respBody, _ := sonic.MarshalIndent(msg, "  ", "  ")
	log.Printf("response: %s\n", string(respBody))
}
Chat Completions API
package main

import (
	"context"
	"log"
	"os"

	"github.com/bytedance/sonic"
	"github.com/cloudwego/eino-ext/components/model/agenticopenai"
	"github.com/cloudwego/eino/schema"
)

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

	m, err := agenticopenai.NewChatModel(ctx, &agenticopenai.ChatConfig{
		APIKey: os.Getenv("OPENAI_API_KEY"),
		Model:  os.Getenv("OPENAI_MODEL_ID"),
	})
	if err != nil {
		log.Fatalf("failed to create chat model, err: %v", err)
	}

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

	msg, err := m.Generate(ctx, input)
	if err != nil {
		log.Fatalf("failed to generate, err: %v", err)
	}

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

Configuration

ResponsesConfig

The ResponsesModel can be configured using the agenticopenai.ResponsesConfig struct:

type ResponsesConfig struct {
    // ByAzure specifies whether to use Azure OpenAI service.
    // Optional.
    ByAzure bool

    // BaseURL specifies the base URL for the OpenAI service endpoint.
    // Optional. Default: https://api.openai.com/v1
    BaseURL string

    // APIKey specifies the API key for authentication.
    // Required.
    APIKey string

    // Timeout specifies the maximum duration to wait for API responses.
    // Optional.
    Timeout *time.Duration

    // HTTPClient specifies the HTTP client used to send requests.
    // Optional.
    HTTPClient *http.Client

    // MaxRetries specifies the maximum number of retry attempts for failed requests.
    // Optional.
    MaxRetries *int

    // Model specifies the ID of the model to use for the response.
    // 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.
    // Range: 0.0 to 2.0.
    // Optional.
    Temperature *float32

    // TopP controls diversity via nucleus sampling.
    // Range: 0.0 to 1.0.
    // Optional.
    TopP *float32

    // ServiceTier specifies the latency tier for processing the request.
    // Optional.
    ServiceTier *responses.ResponseNewParamsServiceTier

    // Text specifies configuration for text generation output.
    // Optional.
    Text *responses.ResponseTextConfigParam

    // Reasoning specifies configuration for reasoning models.
    // Optional.
    Reasoning *responses.ReasoningParam

    // Store specifies whether to store the response on the server.
    // Optional.
    Store *bool

    // MaxToolCalls specifies the maximum number of tool calls allowed in a single turn.
    // Optional.
    MaxToolCalls *int

    // ParallelToolCalls specifies whether to allow multiple tool calls in a single turn.
    // Optional.
    ParallelToolCalls *bool

    // Include specifies a list of additional fields to include in the response.
    // Optional.
    Include []responses.ResponseIncludable

    // Truncation specifies how to handle context that exceeds the model's context window.
    // Optional.
    Truncation *responses.ResponseNewParamsTruncation

    // EnableAutoCache controls whether auto-caching for multi-turn conversations is active.
    // When enabled, the model automatically maintains context by locating the most recent
    // cached message in the input (via Response ID in ResponseMeta).
    // Optional.
    EnableAutoCache bool

    // PromptCacheRetention specifies the retention policy for the prompt cache.
    // Optional.
    PromptCacheRetention *responses.ResponseNewParamsPromptCacheRetention

    // CustomHeaders specifies custom HTTP headers to include in API requests.
    // 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
}
ChatConfig

The ChatModel can be configured using the agenticopenai.ChatConfig struct:

type ChatConfig struct {
    // APIKey is your authentication key.
    // Required.
    APIKey string

    // 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 client to send HTTP requests.
    // If HTTPClient is set, Timeout will not be used.
    // Optional.
    HTTPClient *http.Client

    // ByAzure indicates whether to use Azure OpenAI Service.
    // Optional. Default: false
    ByAzure bool

    // AzureModelMapperFunc is used to map the model name to the deployment name for Azure OpenAI Service.
    // Optional for Azure.
    AzureModelMapperFunc func(model string) string

    // APIVersion specifies the Azure OpenAI API version.
    // Required for Azure.
    APIVersion string

    // BaseURL specifies the API endpoint URL.
    // Optional. Default: https://api.openai.com/v1
    BaseURL string

    // Model specifies the ID of the model to use.
    // Required.
    Model string

    // MaxCompletionTokens specifies an upper bound for the number of tokens that can be generated.
    // Optional.
    MaxCompletionTokens *int

    // Temperature specifies what sampling temperature to use.
    // Range: 0.0 to 2.0.
    // Optional. Default: 1.0
    Temperature *float32

    // TopP controls diversity via nucleus sampling.
    // Range: 0.0 to 1.0.
    // Optional. Default: 1.0
    TopP *float32

    // Stop sequences where the API will stop generating further tokens.
    // Optional.
    Stop []string

    // PresencePenalty prevents repetition by penalizing tokens based on presence.
    // Range: -2.0 to 2.0.
    // Optional. Default: 0
    PresencePenalty *float32

    // FrequencyPenalty prevents repetition by penalizing tokens based on frequency.
    // Range: -2.0 to 2.0.
    // Optional. Default: 0
    FrequencyPenalty *float32

    // LogitBias modifies likelihood of specific tokens appearing in completion.
    // Optional.
    LogitBias map[string]int

    // LogProbs specifies whether to return log probabilities of the output tokens.
    // Optional. Default: false
    LogProbs bool

    // TopLogProbs specifies the number of most likely tokens to return at each token position.
    // Optional.
    TopLogProbs int

    // CustomHeaders specifies custom HTTP headers to include in the request.
    // 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
}

Extension Fields

Several fields in the Eino agentic schema are typed as any so that each model implementation can attach provider-specific data. When you consume responses produced by this package, you must type-assert these any fields to the concrete types defined here before you can read them. This section documents every such field and the exact type it carries.

ResponseMeta

Each returned *schema.AgenticMessage carries a ResponseMeta *schema.AgenticResponseMeta. Its shape differs between the two model implementations.

type AgenticResponseMeta struct {
    // TokenUsage is always populated with prompt / completion / total token counts.
    TokenUsage *TokenUsage

    // OpenAIExtension is populated by the Responses API implementation (NewResponsesModel).
    OpenAIExtension *openai.ResponseMetaExtension

    // Extension is an `any` field populated by the Chat Completions implementation (NewChatModel).
    Extension any

    // GeminiExtension / ClaudeExtension are unused by this package.
}
Responses API — ResponseMeta.OpenAIExtension

NewResponsesModel populates the strongly typed OpenAIExtension field (no assertion required). It exposes the server-side response state, including the response ID used for prefix caching:

type ResponseMetaExtension struct {
    ID                 string             // server-assigned response ID
    Status             ResponseStatus     // e.g. "completed", "incomplete"
    Error              *ResponseError     // non-nil when the response failed
    IncompleteDetails  *IncompleteDetails // non-nil when the response is incomplete
    PreviousResponseID string
    Reasoning          *Reasoning // reasoning effort / summary, for reasoning models
    ServiceTier        ServiceTier
    // ... and other server-side fields
}
ext := msg.ResponseMeta.OpenAIExtension // strongly typed, no assertion needed

Note: The OpenAIExtension.ID is exactly the value consumed by EnableAutoCache and WithHeadPreviousResponseID to continue a cached multi-turn conversation. See Cache.

Chat Completions API — ResponseMeta.Extension (any)

NewChatModel cannot use OpenAIExtension (which is Responses-specific), so it populates the generic Extension any field instead. You must assert it to *agenticopenai.ChatResponseMetaExtension before use:

type ChatResponseMetaExtension struct {
    ID           string           // the upstream request ID
    FinishReason string           // e.g. "stop", "length", "tool_calls"
    LogProbs     *schema.LogProbs // populated only when LogProbs is enabled in ChatConfig
}
// The concrete type is always *agenticopenai.ChatResponseMetaExtension.
ext, ok := msg.ResponseMeta.Extension.(*agenticopenai.ChatResponseMetaExtension)
AssistantGenText Extension

The text generated by the model is carried in AssistantGenText content blocks. The plain UserInputText block (user-provided text) has no extension — only the model-generated AssistantGenText block does. This package populates its strongly-typed OpenAIExtension *openai.AssistantGenTextExtension field (no assertion required), which carries refusals and citation annotations:

type AssistantGenTextExtension struct {
    // Refusal is set when the model declined to answer; Refusal.Reason holds the refusal text.
    Refusal *OutputRefusal

    // Annotations carry citations attached to the generated text
    // (URL citations, file citations, container-file citations, file paths).
    Annotations []*TextAnnotation
}

Note: AssistantGenText also exposes a generic Extension any field for other providers, but this package only ever populates OpenAIExtension.

ServerToolCall & ServerToolResult

When the model invokes a built-in server tool (web search, file search, code interpreter, image generation, shell, or tool search), the resulting content blocks carry *schema.ServerToolCall and *schema.ServerToolResult. Both wrap their payload in an any field, which this package always populates with its own concrete types.

type ServerToolCall struct {
    Name      string // tool name, e.g. "web_search" (see agenticopenai.ServerToolName* constants)
    CallID    string
    Arguments any    // concrete type: *agenticopenai.ServerToolCallArguments
}

type ServerToolResult struct {
    Name    string
    CallID  string
    Content any    // concrete type: *agenticopenai.ServerToolResult
}
ServerToolCall.Arguments (any)

Assert to *agenticopenai.ServerToolCallArguments. Exactly one of its sub-fields is non-nil, matching the tool that was invoked. Inspect ServerToolCall.Name (or the non-nil field) to decide which one to read:

type ServerToolCallArguments struct {
    WebSearch       *WebSearchArguments       // ServerToolNameWebSearch
    FileSearch      *FileSearchArguments      // ServerToolNameFileSearch
    CodeInterpreter *CodeInterpreterArguments // ServerToolNameCodeInterpreter
    ImageGeneration *ImageGenerationArguments // ServerToolNameImageGeneration
    Shell           *ShellArguments           // ServerToolNameShell
    ToolSearch      *ToolSearchArguments      // tool search calls
}
ServerToolResult.Content (any)

Assert to *agenticopenai.ServerToolResult. As with arguments, exactly one sub-field is populated, matching the tool that produced the result:

type ServerToolResult struct {
    WebSearch       *WebSearchResult
    FileSearch      *FileSearchResult
    CodeInterpreter *CodeInterpreterResult
    ImageGeneration *ImageGenerationResult
    Shell           *ShellResult
    ToolSearch      *ToolSearchResult // ToolSearchResult.Tools is []*schema.ToolInfo
}

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, pass the response ID with WithHeadPreviousResponseID.

am, err := agenticopenai.NewResponsesModel(ctx, &agenticopenai.ResponsesConfig{
    APIKey:          os.Getenv("OPENAI_API_KEY"),
    Model:           os.Getenv("OPENAI_MODEL_ID"),
    EnableAutoCache: true,
})
Tool Calling

The ResponsesModel 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/agenticopenai"
	"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 := agenticopenai.NewResponsesModel(ctx, &agenticopenai.ResponsesConfig{
		APIKey: os.Getenv("OPENAI_API_KEY"),
		Model:  os.Getenv("OPENAI_MODEL_ID"),
	})
	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)
	}

	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/agenticopenai"
	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
	"github.com/openai/openai-go/v3/responses"
)

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

	am, err := agenticopenai.NewResponsesModel(ctx, &agenticopenai.ResponsesConfig{
		APIKey: os.Getenv("OPENAI_API_KEY"),
		Model:  os.Getenv("OPENAI_MODEL_ID"),
		Include: []responses.ResponseIncludable{
			responses.ResponseIncludableWebSearchCallActionSources,
		},
	})
	if err != nil {
		log.Fatalf("failed to create agentic model, err=%v", err)
	}

	serverTools := []*agenticopenai.ResponsesServerToolConfig{
		{
			WebSearch: &responses.WebSearchToolParam{
				Type: responses.WebSearchToolTypeWebSearch,
			},
		},
	}

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

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

	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, 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)
	}

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

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

	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 GetToolSearchToolCall

func GetToolSearchToolCall(block *schema.ContentBlock) 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, OPENAI invalidates caches for that message and all subsequent ones. Call this to mark those message caches as invalid temporarily.

func WithCustomHeaders

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

WithCustomHeaders sets custom HTTP headers for the request.

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{
    "reasoning_effort": "high",
    "service_tier": "default",
})

The resulting request body will be:

{
    "model": "o1",
    "input": [...],
    "reasoning_effort": "high",
    "service_tier": "default"
}

func WithHeadPreviousResponseID

func WithHeadPreviousResponseID(id string) model.Option

WithHeadPreviousResponseID sets a response ID from a previous Responses API 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. Available only for Responses API.

func WithResponsesMCPTools

func WithResponsesMCPTools(tools []*responses.ToolMcpParam) model.Option

WithResponsesMCPTools sets Model Context Protocol tools available to the model. Available only for Responses API.

func WithResponsesMaxToolCalls

func WithResponsesMaxToolCalls(maxToolCalls int) model.Option

WithResponsesMaxToolCalls sets the maximum number of tool calls allowed in a single turn. Available only for Responses API.

func WithResponsesParallelToolCalls

func WithResponsesParallelToolCalls(parallelToolCalls bool) model.Option

WithResponsesParallelToolCalls sets whether to allow multiple tool calls in a single turn. Available only for Responses API.

func WithResponsesPromptCacheKey

func WithResponsesPromptCacheKey(key string) model.Option

WithResponsesPromptCacheKey sets the prompt cache key for the request. Available only for Responses API.

func WithResponsesReasoning

func WithResponsesReasoning(reasoning *responses.ReasoningParam) model.Option

WithResponsesReasoning sets the reasoning configuration for the request. Available only for Responses API.

func WithResponsesServerTools

func WithResponsesServerTools(tools []*ResponsesServerToolConfig) model.Option

WithResponsesServerTools sets server-side tools available to the model. Available only for Responses API.

func WithResponsesStore

func WithResponsesStore(store bool) model.Option

WithResponsesStore sets whether to store the response on the server. Available only for Responses API.

func WithResponsesText

func WithResponsesText(text *responses.ResponseTextConfigParam) model.Option

WithResponsesText sets the text generation configuration for the request. Available only for Responses API.

func WithResponsesTruncation

func WithResponsesTruncation(truncation responses.ResponseNewParamsTruncation) model.Option

WithResponsesTruncation sets how to handle context that exceeds the model's context window. Available only for Responses API.

Types

type ChatConfig

type ChatConfig struct {
	// APIKey is your authentication key
	// Required
	APIKey string

	// Timeout specifies the maximum duration to wait for API responses
	// If HTTPClient is set, Timeout will not be used.
	// Optional. Default: no timeout
	Timeout time.Duration

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

	// ByAzure indicates whether to use Azure OpenAI Service
	// Optional. Default: false
	ByAzure bool

	// AzureModelMapperFunc is used to map the model name to the deployment name for Azure OpenAI Service.
	// Optional for Azure.
	AzureModelMapperFunc func(model string) string

	// APIVersion specifies the Azure OpenAI API version
	// Required for Azure
	APIVersion string

	// BaseURL specifies the API endpoint URL
	// Optional. Default: https://api.openai.com/v1
	BaseURL string

	// Model specifies the ID of the model to use
	// Required
	Model string

	// MaxCompletionTokens specifies an upper bound for the number of tokens that can be generated
	// for a completion, including visible output tokens and reasoning tokens.
	// Optional.
	MaxCompletionTokens *int

	// Temperature specifies what sampling temperature to use
	// Range: 0.0 to 2.0. Higher values make output more random
	// Optional. Default: 1.0
	Temperature *float32

	// TopP controls diversity via nucleus sampling
	// Range: 0.0 to 1.0. Lower values make output more focused
	// Optional. Default: 1.0
	TopP *float32

	// Stop sequences where the API will stop generating further tokens
	// Optional. Example: []string{"\n", "User:"}
	Stop []string

	// PresencePenalty prevents repetition by penalizing tokens based on presence
	// Range: -2.0 to 2.0. Positive values increase likelihood of new topics
	// Optional. Default: 0
	PresencePenalty *float32

	// FrequencyPenalty prevents repetition by penalizing tokens based on frequency
	// Range: -2.0 to 2.0. Positive values decrease likelihood of repetition
	// Optional. Default: 0
	FrequencyPenalty *float32

	// LogitBias modifies likelihood of specific tokens appearing in completion
	// Optional. Map token IDs to bias values from -100 to 100
	LogitBias map[string]int

	// LogProbs specifies whether to return log probabilities of the output tokens.
	// Optional. Default: false
	LogProbs bool

	// TopLogProbs specifies the number of most likely tokens to return at each token position.
	// Optional.
	TopLogProbs int

	// CustomHeaders specifies custom HTTP headers to include in the request.
	// 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
}

Config parameters detail see: https://platform.openai.com/docs/api-reference/chat/create

type ChatModel

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

func NewChatModel

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

func (*ChatModel) Generate

func (m *ChatModel) Generate(ctx context.Context, in []*schema.AgenticMessage, opts ...model.Option) (
	*schema.AgenticMessage, error)

func (*ChatModel) GetType

func (m *ChatModel) GetType() string

func (*ChatModel) IsCallbacksEnabled

func (m *ChatModel) IsCallbacksEnabled() bool

func (*ChatModel) Stream

type ChatResponseMetaExtension

type ChatResponseMetaExtension struct {
	ID           string           `json:"id,omitempty"`
	FinishReason string           `json:"finish_reason,omitempty"`
	LogProbs     *schema.LogProbs `json:"logprobs,omitempty"`
}

type CodeInterpreterArguments

type CodeInterpreterArguments struct {
}

CodeInterpreterArguments represents the arguments for a code interpreter tool call.

type CodeInterpreterOutput

type CodeInterpreterOutput struct {
	// Type is the output type: "logs" or "image".
	Type CodeInterpreterOutputType `json:"type,omitempty" mapstructure:"type,omitempty"`
	// Logs is set when Type is "logs".
	Logs *CodeInterpreterOutputLogs `json:"logs,omitempty" mapstructure:"logs,omitempty"`
	// Image is set when Type is "image".
	Image *CodeInterpreterOutputImage `json:"image,omitempty" mapstructure:"image,omitempty"`
}

CodeInterpreterOutput represents a single output from the code interpreter.

type CodeInterpreterOutputImage

type CodeInterpreterOutputImage struct {
	// URL is the URL of the generated image.
	URL string `json:"url,omitempty" mapstructure:"url,omitempty"`
}

CodeInterpreterOutputImage represents the image output from the code interpreter.

type CodeInterpreterOutputLogs

type CodeInterpreterOutputLogs struct {
	// Logs is the log content from code execution.
	Logs string `json:"logs,omitempty" mapstructure:"logs,omitempty"`
}

CodeInterpreterOutputLogs represents the logs output from the code interpreter.

type CodeInterpreterOutputType

type CodeInterpreterOutputType string
const (
	CodeInterpreterOutputTypeLogs  CodeInterpreterOutputType = "logs"
	CodeInterpreterOutputTypeImage CodeInterpreterOutputType = "image"
)

type CodeInterpreterResult

type CodeInterpreterResult struct {
	// Code is the code that was run.
	Code string `json:"code,omitempty" mapstructure:"code,omitempty"`
	// ContainerID is the ID of the container used to run the code.
	ContainerID string `json:"container_id,omitempty" mapstructure:"container_id,omitempty"`
	// Outputs are the outputs generated by the code interpreter.
	Outputs []*CodeInterpreterOutput `json:"outputs,omitempty" mapstructure:"outputs,omitempty"`
}

CodeInterpreterResult represents the result of a code interpreter tool call.

type FileSearchArguments

type FileSearchArguments struct {
	// Queries are the queries used to search for files.
	Queries []string `json:"queries,omitempty" mapstructure:"queries,omitempty"`
}

FileSearchArguments represents the arguments for a file search tool call.

type FileSearchAttribute

type FileSearchAttribute struct {
	// OfString is set when the attribute value is a string.
	OfString *string `json:"of_string,omitempty" mapstructure:"of_string,omitempty"`
	// OfFloat is set when the attribute value is a number.
	OfFloat *float64 `json:"of_float,omitempty" mapstructure:"of_float,omitempty"`
	// OfBool is set when the attribute value is a boolean.
	OfBool *bool `json:"of_bool,omitempty" mapstructure:"of_bool,omitempty"`
}

FileSearchAttribute represents an attribute value, which can be string, float, or bool.

type FileSearchResult

type FileSearchResult struct {
	// Results contains the matched files.
	Results []*FileSearchResultItem `json:"results,omitempty" mapstructure:"results,omitempty"`
}

FileSearchResult represents the result of a file search tool call.

type FileSearchResultItem

type FileSearchResultItem struct {
	// FileID is the unique ID of the file.
	FileID string `json:"file_id,omitempty" mapstructure:"file_id,omitempty"`
	// FileName is the name of the file.
	FileName string `json:"file_name,omitempty" mapstructure:"file_name,omitempty"`
	// Score is the relevance score, a value between 0 and 1.
	Score float64 `json:"score,omitempty" mapstructure:"score,omitempty"`
	// Text is the text content retrieved from the file.
	Text string `json:"text,omitempty" mapstructure:"text,omitempty"`
	// Attributes contains the metadata key-value pairs attached to the file.
	Attributes map[string]*FileSearchAttribute `json:"attributes,omitempty" mapstructure:"attributes,omitempty"`
}

FileSearchResultItem represents a single matched file.

type ImageGenerationArguments

type ImageGenerationArguments struct {
}

ImageGenerationArguments represents the arguments for an image generation tool call.

type ImageGenerationResult

type ImageGenerationResult struct {
	// ImageBase64 is the base64-encoded image data.
	ImageBase64 string `json:"image_base64,omitempty" mapstructure:"image_base64,omitempty"`
}

ImageGenerationResult represents the result of an image generation tool call.

type ResponsesConfig

type ResponsesConfig struct {
	// ByAzure specifies whether to use Azure OpenAI service.
	// Optional.
	ByAzure bool

	// BaseURL specifies the base URL for the OpenAI service endpoint.
	// Optional. Default: https://api.openai.com/v1
	BaseURL string

	// APIKey specifies the API key for authentication.
	// Required.
	APIKey string

	// Timeout specifies the maximum duration to wait for API responses.
	// Optional.
	Timeout *time.Duration

	// HTTPClient specifies the HTTP client used to send requests.
	// Optional.
	HTTPClient *http.Client

	// MaxRetries specifies the maximum number of retry attempts for failed requests.
	// Optional.
	MaxRetries *int

	// Model specifies the ID of the model to use for the response.
	// 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.
	// Higher values (e.g., 0.8) make the output more random, while lower values (e.g., 0.2) make it more focused and deterministic.
	// Range: 0.0 to 2.0.
	// Optional.
	Temperature *float32

	// TopP controls diversity via nucleus sampling.
	// It specifies the cumulative probability threshold for token selection.
	// Recommended to use either Temperature or TopP, but not both.
	// Range: 0.0 to 1.0.
	// Optional.
	TopP *float32

	// ServiceTier specifies the latency tier for processing the request.
	// Optional.
	ServiceTier *responses.ResponseNewParamsServiceTier

	// Text specifies configuration for text generation output.
	// Optional.
	Text *responses.ResponseTextConfigParam

	// Reasoning specifies configuration for reasoning models.
	// Optional.
	Reasoning *responses.ReasoningParam

	// Store specifies whether to store the response on the server.
	// Optional.
	Store *bool

	// MaxToolCalls specifies the maximum number of tool calls allowed in a single turn.
	// Optional.
	MaxToolCalls *int

	// ParallelToolCalls specifies whether to allow multiple tool calls in a single turn.
	// Optional.
	ParallelToolCalls *bool

	// Include specifies a list of additional fields to include in the response.
	// Optional.
	Include []responses.ResponseIncludable

	// Truncation specifies how to handle context that exceeds the model's context window.
	// Optional.
	Truncation *responses.ResponseNewParamsTruncation

	// 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.
	// Unless Store is set to false explicitly for a request, auto-cache forces Store to true.
	// Optional.
	EnableAutoCache bool

	// PromptCacheRetention specifies the retention policy for the prompt cache.
	// Optional.
	PromptCacheRetention *responses.ResponseNewParamsPromptCacheRetention

	// 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
}

type ResponsesModel

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

func NewResponsesModel

func NewResponsesModel(_ context.Context, config *ResponsesConfig) (*ResponsesModel, error)

func (*ResponsesModel) Generate

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

func (*ResponsesModel) GetType

func (m *ResponsesModel) GetType() string

func (*ResponsesModel) IsCallbacksEnabled

func (m *ResponsesModel) IsCallbacksEnabled() bool

func (*ResponsesModel) Stream

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

type ResponsesServerToolConfig

type ResponsesServerToolConfig struct {
	WebSearch       *responses.WebSearchToolParam
	FileSearch      *responses.FileSearchToolParam
	CodeInterpreter *responses.ToolCodeInterpreterParam
	Shell           *responses.FunctionShellToolParam
}

type ServerToolCallArguments

type ServerToolCallArguments struct {
	WebSearch       *WebSearchArguments       `json:"web_search,omitempty" mapstructure:"web_search,omitempty"`
	FileSearch      *FileSearchArguments      `json:"file_search,omitempty" mapstructure:"file_search,omitempty"`
	CodeInterpreter *CodeInterpreterArguments `json:"code_interpreter,omitempty" mapstructure:"code_interpreter,omitempty"`
	ImageGeneration *ImageGenerationArguments `json:"image_generation,omitempty" mapstructure:"image_generation,omitempty"`
	Shell           *ShellArguments           `json:"shell,omitempty" mapstructure:"shell,omitempty"`
	ToolSearch      *ToolSearchArguments      `json:"tool_search,omitempty" mapstructure:"-"`
}

type ServerToolName

type ServerToolName string
const (
	ServerToolNameWebSearch       ServerToolName = "web_search"
	ServerToolNameFileSearch      ServerToolName = "file_search"
	ServerToolNameCodeInterpreter ServerToolName = "code_interpreter"
	ServerToolNameImageGeneration ServerToolName = "image_generation"
	ServerToolNameShell           ServerToolName = "shell"
)

type ServerToolResult

type ServerToolResult struct {
	WebSearch       *WebSearchResult       `json:"web_search,omitempty" mapstructure:"web_search,omitempty"`
	FileSearch      *FileSearchResult      `json:"file_search,omitempty" mapstructure:"file_search,omitempty"`
	CodeInterpreter *CodeInterpreterResult `json:"code_interpreter,omitempty" mapstructure:"code_interpreter,omitempty"`
	ImageGeneration *ImageGenerationResult `json:"image_generation,omitempty" mapstructure:"image_generation,omitempty"`
	Shell           *ShellResult           `json:"shell,omitempty" mapstructure:"shell,omitempty"`
	ToolSearch      *ToolSearchResult      `json:"tool_search,omitempty" mapstructure:"-"`
}

type ShellAction

type ShellAction struct {
	// Commands are the shell commands to run.
	Commands []string `json:"commands,omitempty" mapstructure:"commands,omitempty"`
	// TimeoutMs is the timeout in milliseconds for the commands.
	TimeoutMs int64 `json:"timeout_ms,omitempty" mapstructure:"timeout_ms,omitempty"`
	// MaxOutputLength is the maximum number of characters to return from each command.
	MaxOutputLength int64 `json:"max_output_length,omitempty" mapstructure:"max_output_length,omitempty"`
}

ShellAction contains the shell commands and execution limits.

type ShellArguments

type ShellArguments struct {
	// Action contains the shell commands to execute.
	Action *ShellAction `json:"action,omitempty" mapstructure:"action,omitempty"`
	// Environment specifies where to run the commands.
	Environment *ShellEnvironment `json:"environment,omitempty" mapstructure:"environment,omitempty"`
	// CreatedBy is the ID of the entity that created this tool call.
	CreatedBy string `json:"created_by,omitempty" mapstructure:"created_by,omitempty"`
}

ShellArguments represents the arguments for a shell tool call.

type ShellEnvironment

type ShellEnvironment struct {
	// Type is the environment type: "local" or "container_reference".
	Type ShellEnvironmentType `json:"type,omitempty" mapstructure:"type,omitempty"`
	// Local is set when Type is "local".
	Local *ShellEnvironmentLocal `json:"local,omitempty" mapstructure:"local,omitempty"`
	// ContainerReference is set when Type is "container_reference".
	ContainerReference *ShellEnvironmentContainerReference `json:"container_reference,omitempty" mapstructure:"container_reference,omitempty"`
}

ShellEnvironment specifies the execution environment for shell commands.

type ShellEnvironmentContainerReference

type ShellEnvironmentContainerReference struct {
	// ContainerID is the ID of the container.
	ContainerID string `json:"container_id,omitempty" mapstructure:"container_id,omitempty"`
}

ShellEnvironmentContainerReference identifies a container to run commands in.

type ShellEnvironmentLocal

type ShellEnvironmentLocal struct {
	// Skills is an optional list of skills available in the local environment.
	Skills []*ShellEnvironmentLocalSkill `json:"skills,omitempty" mapstructure:"skills,omitempty"`
}

ShellEnvironmentLocal represents a local execution environment for shell commands.

type ShellEnvironmentLocalSkill

type ShellEnvironmentLocalSkill struct {
	// Name is the name of the skill.
	Name string `json:"name,omitempty" mapstructure:"name,omitempty"`
	// Description is the description of the skill.
	Description string `json:"description,omitempty" mapstructure:"description,omitempty"`
	// Path is the path to the directory containing the skill.
	Path string `json:"path,omitempty" mapstructure:"path,omitempty"`
}

ShellEnvironmentLocalSkill represents a skill available in a local environment.

type ShellEnvironmentType

type ShellEnvironmentType string
const (
	ShellEnvironmentTypeLocal              ShellEnvironmentType = "local"
	ShellEnvironmentTypeContainerReference ShellEnvironmentType = "container_reference"
)

type ShellOutputItem

type ShellOutputItem struct {
	// Stdout is the captured standard output.
	Stdout string `json:"stdout,omitempty" mapstructure:"stdout,omitempty"`
	// Stderr is the captured standard error.
	Stderr string `json:"stderr,omitempty" mapstructure:"stderr,omitempty"`
	// Outcome indicates how the command finished (exit or timeout).
	Outcome *ShellOutputOutcome `json:"outcome,omitempty" mapstructure:"outcome,omitempty"`
	// CreatedBy is the identifier of the actor that created this output.
	CreatedBy string `json:"created_by,omitempty" mapstructure:"created_by,omitempty"`
}

ShellOutputItem represents the output from a single command.

type ShellOutputOutcome

type ShellOutputOutcome struct {
	// Type is the outcome type: "exit" or "timeout".
	Type ShellOutputOutcomeType `json:"type,omitempty" mapstructure:"type,omitempty"`
	// Exit is set when Type is "exit".
	Exit *ShellOutputOutcomeExit `json:"exit,omitempty" mapstructure:"exit,omitempty"`
}

ShellOutputOutcome indicates how a shell command finished.

type ShellOutputOutcomeExit

type ShellOutputOutcomeExit struct {
	// ExitCode is the exit code from the shell process.
	ExitCode int64 `json:"exit_code,omitempty" mapstructure:"exit_code,omitempty"`
}

ShellOutputOutcomeExit contains exit information for a completed command.

type ShellOutputOutcomeType

type ShellOutputOutcomeType string
const (
	ShellOutputOutcomeTypeTimeout ShellOutputOutcomeType = "timeout"
	ShellOutputOutcomeTypeExit    ShellOutputOutcomeType = "exit"
)

type ShellResult

type ShellResult struct {
	// MaxOutputLength is the maximum length of output returned per command.
	MaxOutputLength int64 `json:"max_output_length,omitempty" mapstructure:"max_output_length,omitempty"`
	// Outputs contains the output from each command.
	Outputs []*ShellOutputItem `json:"outputs,omitempty" mapstructure:"outputs,omitempty"`
	// CreatedBy is the identifier of the actor that created this result.
	CreatedBy string `json:"created_by,omitempty" mapstructure:"created_by,omitempty"`
}

ShellResult represents the result of a shell tool call.

type ToolSearchArguments

type ToolSearchArguments struct {
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

type ToolSearchResult

type ToolSearchResult struct {
	Tools []*schema.ToolInfo `json:"tools"`
}

type WebSearchAction

type WebSearchAction string
const (
	WebSearchActionSearch   WebSearchAction = "search"
	WebSearchActionOpenPage WebSearchAction = "open_page"
	WebSearchActionFind     WebSearchAction = "find"
)

type WebSearchArguments

type WebSearchArguments struct {
	// ActionType is the type of action: search, open_page, or find.
	ActionType WebSearchAction `json:"action_type,omitempty" mapstructure:"action_type,omitempty"`
	// Search is the search query parameters. Present when ActionType is "search".
	Search *WebSearchQuery `json:"search,omitempty" mapstructure:"search,omitempty"`
	// OpenPage is the open page parameters. Present when ActionType is "open_page".
	OpenPage *WebSearchOpenPage `json:"open_page,omitempty" mapstructure:"open_page,omitempty"`
	// Find is the find in page parameters. Present when ActionType is "find".
	Find *WebSearchFind `json:"find,omitempty" mapstructure:"find,omitempty"`
}

WebSearchArguments represents the arguments for a web search tool call.

type WebSearchFind

type WebSearchFind struct {
	// URL is the URL of the page.
	URL string `json:"url,omitempty" mapstructure:"url,omitempty"`
	// Pattern is the pattern to find in the page.
	Pattern string `json:"pattern,omitempty" mapstructure:"pattern,omitempty"`
}

WebSearchFind represents find in page parameters.

type WebSearchOpenPage

type WebSearchOpenPage struct {
	// URL is the URL to open.
	URL string `json:"url,omitempty" mapstructure:"url,omitempty"`
}

WebSearchOpenPage represents open page parameters.

type WebSearchQuery

type WebSearchQuery struct {
	// Queries are the search queries.
	Queries []string `json:"queries,omitempty" mapstructure:"queries,omitempty"`
}

WebSearchQuery represents a web search query parameters.

type WebSearchQueryResult

type WebSearchQueryResult struct {
	// Sources are the sources returned from the search.
	Sources []*WebSearchQuerySource `json:"sources,omitempty" mapstructure:"sources,omitempty"`
}

WebSearchQueryResult represents the result of a web search query.

type WebSearchQuerySource

type WebSearchQuerySource struct {
	// URL is the URL of the source.
	URL string `json:"url,omitempty" mapstructure:"url,omitempty"`
}

WebSearchQuerySource represents a source returned from the search.

type WebSearchResult

type WebSearchResult struct {
	// ActionType is the type of action performed.
	ActionType WebSearchAction `json:"action_type,omitempty" mapstructure:"action_type,omitempty"`
	// Search contains the search query result. Present when ActionType is "search".
	Search *WebSearchQueryResult `json:"search,omitempty" mapstructure:"search,omitempty"`
}

WebSearchResult represents the result of a web search tool call.

Jump to

Keyboard shortcuts

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