### Install OpenAI Agents Go SDK Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/README.md This snippet shows the Go command to install the OpenAI Agents Go SDK. It is a prerequisite for using the SDK in your Go projects. ```go go get github.com/nlpodyssey/openai-agents-go ``` -------------------------------- ### LiteLLM Configuration File Example (YAML) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md An example `litellm_config.yaml` file demonstrating how to configure multiple LLM providers for LiteLLM. It includes settings for OpenAI, Anthropic, and local Ollama models, specifying their respective models and API keys or base URLs. ```yaml model_list: # OpenAI Models - model_name: openai-gpt-4o litellm_params: model: openai/gpt-4o-mini api_key: os.environ/OPENAI_API_KEY # Anthropic Models - model_name: claude-3-sonnet litellm_params: model: anthropic/claude-3-5-sonnet-20240620 api_key: os.environ/ANTHROPIC_API_KEY # Local Ollama Models - model_name: ollama-llama3 litellm_params: model: ollama/llama3 api_base: http://localhost:11434 ``` -------------------------------- ### Start LiteLLM Docker Container Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md This command starts the LiteLLM Docker container, mounting a configuration file and exposing the necessary port. It requires the OpenAI API key to be set as an environment variable. The container listens on port 4000. ```bash # Set your OpenAI API key export OPENAI_API_KEY="sk-your-openai-api-key-here" # Start LiteLLM with the provided config docker run \ -v $(pwd)/litellm_config.yaml:/app/config.yaml \ -e OPENAI_API_KEY="$OPENAI_API_KEY" \ -p 4000:4000 \ ghcr.io/berriai/litellm:main-stable \ --config /app/config.yaml \ --detailed_debug ``` -------------------------------- ### Create and Run a Basic Agent in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Demonstrates how to create a simple AI agent using the builder pattern and execute it to get a response. It initializes an agent with instructions and a model, then runs it with a specific prompt. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { // Create agent with builder pattern agent := agents.New("Assistant"). WithInstructions("You are a helpful assistant"). WithModel("gpt-4o") ctx := context.Background() // Execute agent and get result result, err := agents.Run(ctx, agent, "Write a haiku about recursion in programming.") if err != nil { panic(err) } // Access final output fmt.Println(result.FinalOutput) // Output: Function calls itself, // Deep within the endless loop, // Code mirrors its form. } ``` -------------------------------- ### Basic Agent Execution in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/README.md Demonstrates a basic 'Hello World' example using the OpenAI Agents Go SDK. It initializes an agent, sets instructions and a model, and runs a prompt, printing the final output. Ensure the OPENAI_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { agent := agents.New("Assistant"). WithInstructions("You are a helpful assistant"). WithModel("gpt-4o") result, err := agents.Run(context.Background(), agent, "Write a haiku about recursion in programming.") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // Function calls itself, // Deep within the endless loop, // Code mirrors its form. } ``` -------------------------------- ### LiteLLM Environment Variables Example (Bash) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md This section lists the environment variables required for LiteLLM to access different LLM providers. It includes variables for OpenAI, Anthropic, and Google API keys. ```bash # Required for OpenAI models export OPENAI_API_KEY="sk-..." # Optional for Anthropic models export ANTHROPIC_API_KEY="sk-ant-..." # Optional for Google models export GOOGLE_API_KEY="..." ``` -------------------------------- ### Model Fallbacks Configuration (YAML) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md An example snippet from `litellm_config.yaml` showing how to configure model fallbacks. If a primary model like `openai-gpt-4o` is unavailable, LiteLLM will attempt to use `openai-gpt-4o-mini`. ```yaml general_settings: fallbacks: - openai-gpt-4o - openai-gpt-4o-mini ``` -------------------------------- ### Use LiteLLM as OpenAI Proxy in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/README.md Demonstrates using LiteLLM as an OpenAI-compatible proxy with the Go SDK. This example includes setting up LiteLLM via Docker, configuring multi-provider routing with prefixes, and setting a global default. It requires Docker and an `OPENAI_API_KEY` for upstream providers. ```bash docker run \ -v $(pwd)/litellm_config.yaml:/app/config.yaml \ -e OPENAI_API_KEY="$OPENAI_API_KEY" \ -p 4000:4000 \ ghcr.io/berriai/litellm:main-stable \ --config /app/config.yaml \ --detailed_debug go run ./examples/model_providers/custom_example_litellm ``` -------------------------------- ### Add Custom Function Tools to an Agent in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Shows how to extend an agent's capabilities by adding custom function tools. This example defines a `GetWeather` tool with specific parameters and return types, then registers it with the agent. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) // Define tool parameter struct with JSON tags type GetWeatherParams struct { City string `json:"city"` } // Define return struct type Weather struct { City string `json:"city"` TemperatureRange string `json:"temperature_range"` Conditions string `json:"conditions"` } // Implement tool function func GetWeather(_ context.Context, params GetWeatherParams) (Weather, error) { // Tool logic here - can access APIs, databases, etc. return Weather{ City: params.City, TemperatureRange: "14-20C", Conditions: "Sunny with wind.", }, nil } // Register tool with agent var GetWeatherTool = agents.NewFunctionTool( "get_weather", "Get the current weather information for a specified city.", GetWeather, ) func main() { agent := agents.New("Weather Assistant"). WithInstructions("You are a helpful assistant."). WithTools(GetWeatherTool). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, agent, "What's the weather in Tokyo?") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // Output: The weather in Tokyo is 14-20C and sunny with wind. } ``` -------------------------------- ### Integrating Tools with Agents in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/README.md Shows how to define and register a custom tool (GetWeather) with an agent. The agent can then use this tool to respond to user queries that require external information. This example uses JSON tags for parameter definition and demonstrates tool execution within an agent's workflow. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) // Tool params type type GetWeatherParams struct { City string `json:"city"` } // Tool implementation func getWeather(_ context.Context, params GetWeatherParams) (string, error) { return fmt.Sprintf("The weather in %s is sunny.", params.City), nil } // Tool registration (using SDK's NewFunctionTool) var getWeatherTool = agents.NewFunctionTool("GetWeather", "", getWeather) func main() { agent := agents.New("Hello world"). WithInstructions("You are a helpful agent."). WithModel("gpt-4o"). WithTools(getWeatherTool) result, err := agents.Run(context.Background(), agent, "What's the weather in Tokyo?") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // The weather in Tokyo is sunny. } ``` -------------------------------- ### Agent Handoffs for Language Routing in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/README.md Illustrates how to use agent handoffs for routing requests based on language. This example sets up a triage agent that directs Spanish requests to a Spanish agent and English requests to an English agent. It demonstrates a multi-agent interaction flow. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { spanishAgent := agents.New("Spanish agent"). WithInstructions("You only speak Spanish."). WithModel("gpt-4o") englishAgent := agents.New("English agent"). WithInstructions("You only speak English."). WithModel("gpt-4o") triageAgent := agents.New("Triage agent"). WithInstructions("Handoff to the appropriate agent based on the language of the request."). WithAgentHandoffs(spanishAgent, englishAgent). WithModel("gpt-4o") result, err := agents.Run(context.Background(), triageAgent, "Hola, ¿cómo estás?") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // ¡Hola! Estoy bien, gracias. ¿Y tú cómo estás? } ``` -------------------------------- ### Go Custom Handoff with Input Filtering Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Demonstrates advanced handoff configuration in Go, enabling custom logic for routing requests between agents. This example shows how to define a specialized booking agent, configure a handoff with custom handlers and input filters to manage conversation context before transferring to another agent. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) type HandoffContext struct { FlightNumber string } func main() { // Specialized booking agent bookingAgent := agents.New("Booking Agent"). WithHandoffDescription("Handles flight bookings and seat updates."). WithInstructions("You help customers with booking-related requests."). WithModel("gpt-4o") // Configure handoff with custom logic handoff := agents.HandoffFromAgent(agents.HandoffFromAgentParams{ Agent: bookingAgent, ToolNameOverride: "transfer_to_booking", ToolDescriptionOverride: "Transfer to booking agent for reservations.", // Custom handler on handoff OnHandoff: agents.OnHandoffWithoutInput(func(ctx context.Context) error { // Set custom context when handing off fmt.Println("Handoff initiated - setting up booking context") return nil }), // Filter conversation history for new agent InputFilter: func(ctx context.Context, data agents.HandoffInputData) (agents.HandoffInputData, error) { // Remove system messages or sensitive data before handoff filtered := data // Custom filtering logic here return filtered, nil }, }) // Main triage agent triageAgent := agents.New("Triage Agent"). WithInstructions("Route customer requests to the appropriate agent."). WithHandoffs(handoff). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, triageAgent, "I need to change my seat on flight AA123.") if err != nil { panic(err) } fmt.Println("Response:", result.FinalOutput) fmt.Println("Handled by:", result.LastAgent.Name) } ``` -------------------------------- ### Implement Agent Handoffs for Task Delegation in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Illustrates how to implement agent handoffs, allowing one agent to delegate tasks to specialized agents based on the request. This example sets up a triage agent that routes requests to Spanish or English speaking agents. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { // Create specialized agents spanishAgent := agents.New("Spanish agent"). WithInstructions("You only speak Spanish."). WithModel("gpt-4o") englishAgent := agents.New("English agent"). WithInstructions("You only speak English."). WithModel("gpt-4o") // Create triage agent with handoffs triageAgent := agents.New("Triage agent"). WithInstructions("Handoff to the appropriate agent based on the language of the request."). WithAgentHandoffs(spanishAgent, englishAgent). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, triageAgent, "Hola, ¿cómo estás?") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // Output: ¡Hola! Estoy bien, gracias. ¿Y tú cómo estás? // The LastAgent shows which agent ultimately handled the request fmt.Println("Handled by:", result.LastAgent.Name) // Output: Handled by: Spanish agent } ``` -------------------------------- ### Direct LiteLLM Provider Integration (Go) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Demonstrates creating a dedicated LiteLLM provider using the OpenAI Agents Go SDK and using it directly with an agent. This pattern is useful for simple integrations where only LiteLLM is needed. ```go // Create a dedicated LiteLLM provider litellmProvider := NewLiteLLMProvider("", "") // Use it directly with an agent result, err := (agents.Runner{ Config: agents.RunConfig{ ModelProvider: litellmProvider, Model: param.NewOpt(agents.NewAgentModelName("openai-gpt-4o")), }, }).Run(context.Background(), agent, "Your prompt here") ``` -------------------------------- ### Dynamic Instructions - Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Illustrates how to implement context-aware dynamic instructions for an agent. By defining a custom `InstructionsGetter`, the agent's behavior can change based on runtime conditions, such as the current time of day. This allows for more adaptive and responsive AI interactions. ```go package main import ( "context" "fmt" "time" "github.com/nlpodyssey/openai-agents-go/agents" ) // Implement custom InstructionsGetter type TimeAwareInstructions struct { baseInstructions string } func (t TimeAwareInstructions) GetInstructions(ctx context.Context, agent *agents.Agent) (string, error) { hour := time.Now().Hour() timeContext := "" if hour < 12 { timeContext = "It's morning. Be energetic and cheerful." } else if hour < 18 { timeContext = "It's afternoon. Be professional and focused." } else { timeContext = "It's evening. Be calm and thoughtful." } return fmt.Sprintf("%s\n\n%s", t.baseInstructions, timeContext), nil } func main() { agent := agents.New("Assistant"). WithInstructionsGetter(TimeAwareInstructions{ baseInstructions: "You are a helpful assistant.", }). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, agent, "How are you doing?") if err != nil { panic(err) } fmt.Println(result.FinalOutput) } ``` -------------------------------- ### MultiProvider with Prefix Routing (Go) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Shows how to set up multiple LLM providers with prefixes using the `agents.NewMultiProvider` in the Go SDK. This allows agents to select providers based on a prefix in the model name, such as `litellm/openai-gpt-4o`. ```go // Setup multiple providers with prefixes providerMap := agents.NewMultiProviderMap() providerMap.AddProvider("litellm", NewLiteLLMProvider("", "")) multiProvider := agents.NewMultiProvider(agents.NewMultiProviderParams{ ProviderMap: providerMap, }) // Use with prefix-based model names agent.WithModel("litellm/openai-gpt-4o") ``` -------------------------------- ### Custom Headers and Settings (Go) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Demonstrates how to add custom headers to requests for specific providers using `modelsettings.ModelSettings` in the Go SDK. This is useful for passing provider-specific information or custom metadata through LiteLLM. ```go // Add custom headers for specific providers modelSettings := modelsettings.ModelSettings{ ExtraHeaders: map[string]string{ "X-LiteLLM-Provider": "anthropic", "X-Custom-Header": "value", }, } agent.WithModelSettings(modelSettings) ``` -------------------------------- ### Stream Responses in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Demonstrates how to stream text output in real-time from an OpenAI agent using the agents.RunStreamed function. It filters for delta events to print the response incrementally. Dependencies include the openai-agents-go library. ```go package main import ( "context" "fmt" "os" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { agent := agents.New("Joker"). WithInstructions("You are a helpful assistant."). WithModel("gpt-4o") ctx := context.Background() // Start streaming execution result, err := agents.RunStreamed(ctx, agent, "Tell me 3 jokes.") if err != nil { panic(err) } // Stream events as they arrive err = result.StreamEvents(func(event agents.StreamEvent) error { // Filter for text delta events if e, ok := event.(agents.RawResponsesStreamEvent); ok { if e.Data.Type == "response.output_text.delta" { fmt.Print(e.Data.Delta) _ = os.Stdout.Sync() } } return nil }) if err != nil { panic(err) } fmt.Println("\n\nFinal output:", result.FinalOutput()) } ``` -------------------------------- ### Add New LLM Providers to LiteLLM Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Demonstrates how to add new language model providers to LiteLLM by updating the 'model_list' in 'litellm_config.yaml'. This includes configurations for Hugging Face and Cohere, specifying model names and API keys. ```yaml model_list: # Hugging Face - model_name: hf-codellama litellm_params: model: huggingface/codellama/CodeLlama-7b-Instruct-hf api_key: os.environ/HUGGINGFACE_API_KEY # Cohere - model_name: cohere-command litellm_params: model: cohere/command-r-plus api_key: os.environ/COHERE_API_KEY ``` -------------------------------- ### Go Advanced Runner Configuration Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Illustrates advanced runner configuration in Go, allowing customization of agent execution. This includes overriding model settings like temperature and max tokens, limiting agent loop iterations, enabling tracing with sensitive data, and adding custom trace metadata. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" "github.com/nlpodyssey/openai-agents-go/modelsettings" ) func main() { agent := agents.New("Creative Writer"). WithInstructions("You are a creative writing assistant."). WithModel("gpt-4o") ctx := context.Background() // Create custom runner with configuration runner := agents.Runner{ Config: agents.RunConfig{ // Override model settings ModelSettings: modelsettings.ModelSettings{ Temperature: 0.9, MaxTokens: 2000, }, // Limit agent loop iterations MaxTurns: 5, // Enable tracing TracingDisabled: false, TraceIncludeSensitiveData: param.NewOpt(true), WorkflowName: "Creative Writing Workflow", // Custom trace metadata TraceMetadata: map[string]any{ "user_id": "user_123", "session": "writing_session_1", }, }, } result, err := runner.Run(ctx, agent, "Write a short story about a time traveler.") if err != nil { panic(err) } fmt.Println(result.FinalOutput) // Access usage statistics if len(result.RawResponses) > 0 { usage := result.RawResponses[0].Usage fmt.Printf("\nTokens used: %d input, %d output\n", usage.InputTokens, usage.OutputTokens) } } ``` -------------------------------- ### Implement Input Guardrails in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Illustrates how to implement input guardrails to validate and filter user input before processing. It defines a guardrail agent and function, then registers it with the main agent. This requires the openai-agents-go library and error handling for guardrail tripwires. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) // Define guardrail output type type MathHomeworkCheck struct { Reasoning string `json:"reasoning"` IsMathHomework bool `json:"is_math_homework"` } // Create guardrail agent var GuardrailAgent = agents.New("Guardrail check"). WithInstructions("Check if the user is asking you to do their math homework."). WithOutputType(agents.OutputType[MathHomeworkCheck]()). WithModel("gpt-4o") // Implement guardrail function func MathGuardrailFunction( ctx context.Context, _ *agents.Agent, input agents.Input, ) (agents.GuardrailFunctionOutput, error) { var result *agents.RunResult var err error switch v := input.(type) { case agents.InputString: result, err = agents.Run(ctx, GuardrailAgent, v.String()) case agents.InputItems: result, err = agents.RunInputs(ctx, GuardrailAgent, v) } if err != nil { return agents.GuardrailFunctionOutput{}, err } output := result.FinalOutput.(MathHomeworkCheck) return agents.GuardrailFunctionOutput{ OutputInfo: output, TripwireTriggered: output.IsMathHomework, }, nil } // Register guardrail var MathGuardrail = agents.InputGuardrail{ GuardrailFunction: MathGuardrailFunction, Name: "math_guardrail", } func main() { agent := agents.New("Support Agent"). WithInstructions("You are a customer support agent."). WithInputGuardrails([]agents.InputGuardrail{MathGuardrail}). WithModel("gpt-4o") ctx := context.Background() // This will trigger the guardrail result, err := agents.Run(ctx, agent, "Can you solve this equation: 2x + 5 = 13?") // Error is InputGuardrailTripwireTriggeredError var guardrailErr *agents.InputGuardrailTripwireTriggeredError if errors.As(err, &guardrailErr) { fmt.Println("Guardrail triggered:", guardrailErr.GuardrailResult.Guardrail.Name) output := guardrailErr.GuardrailResult.Output.OutputInfo.(MathHomeworkCheck) fmt.Println("Reason:", output.Reasoning) return } fmt.Println(result.FinalOutput) } ``` -------------------------------- ### Set Global Default LiteLLM Provider (Go) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Illustrates setting LiteLLM as the global default OpenAI client in the Go SDK. Once set, agents can use models directly without specifying a prefix, simplifying the configuration for projects primarily using LiteLLM. ```go // Set LiteLLM as the global default litellmClient := agents.NewOpenaiClient( param.NewOpt("http://localhost:4000"), param.NewOpt("dummy-key"), ) agents.SetDefaultOpenaiClient(litellmClient, false) // Now all agents use LiteLLM by default agent.WithModel("openai-gpt-4o") // No prefix needed ``` -------------------------------- ### Go Session Memory with SQLite Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Demonstrates how to maintain conversation history across multiple runs using SQLite for persistent session memory. It shows creating a session, configuring a runner with the session, and interacting with the agent, including retrieving conversation history. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" "github.com/nlpodyssey/openai-agents-go/memory" ) func main() { agent := agents.New("Assistant"). WithInstructions("Reply concisely."). WithModel("gpt-4o") ctx := context.Background() // Create persistent session session, err := memory.NewSQLiteSession(ctx, memory.SQLiteSessionParams{ SessionID: "conversation_123", }) if err != nil { panic(err) } defer session.Close() // Configure runner with session runner := agents.Runner{ Config: agents.RunConfig{ Session: session, }, } // First turn result, err := runner.Run(ctx, agent, "What city is the Golden Gate Bridge in?") if err != nil { panic(err) } fmt.Println("Turn 1:", result.FinalOutput) // Output: San Francisco // Second turn - agent remembers previous context automatically result, err = runner.Run(ctx, agent, "What state is it in?") if err != nil { panic(err) } fmt.Println("Turn 2:", result.FinalOutput) // Output: California // Retrieve session history with limit items, err := session.GetItems(ctx, 5) if err != nil { panic(err) } fmt.Printf("Stored %d conversation items\n", len(items)) } ``` -------------------------------- ### Verify LiteLLM Endpoint Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md This command uses curl to test the LiteLLM endpoint by sending a chat completion request. It verifies that LiteLLM is running and accessible on `http://localhost:4000`. ```bash # Test the endpoint curl --location 'http://localhost:4000/chat/completions' \ --header 'Content-Type: application/json' \ --data '{ "model": "openai-gpt-4o", "messages": [{"role": "user", "content": "Hello from LiteLLM!"}], "max_tokens": 50 }' ``` -------------------------------- ### Agent as Tool - Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Demonstrates how to create a specialized agent and then use it as a callable tool within another agent. This pattern facilitates hierarchical delegation and modular agent design. The `AsTool` method converts an agent into a tool, allowing it to be invoked by other agents with defined `ToolName` and `ToolDescription`. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) func main() { // Create a specialized research agent researchAgent := agents.New("Research Agent"). WithInstructions("You research topics thoroughly and provide factual summaries."). WithModel("gpt-4o") // Convert agent to tool callable by other agents researchTool := researchAgent.AsTool(agents.AgentAsToolParams{ ToolName: "research_topic", ToolDescription: "Research a topic and return a detailed summary", // Optional: custom output extractor CustomOutputExtractor: func(ctx context.Context, result agents.RunResult) (string, error) { return fmt.Sprintf("Research findings: %v", result.FinalOutput), nil }, }) // Main agent uses research agent as a tool mainAgent := agents.New("Writer"). WithInstructions("You write articles using research tools when needed."). WithTools(researchTool). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, mainAgent, "Write a brief article about quantum computing.") if err != nil { panic(err) } fmt.Println(result.FinalOutput) } ``` -------------------------------- ### LiteLLM Connection Check Function Stub (Go) Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md A placeholder function in Go (`checkLiteLLMConnection`) that outlines the logic for verifying if the LiteLLM service is running and accessible. It would typically involve making a simple request to the LiteLLM endpoint. ```go func checkLiteLLMConnection() bool { // Attempts a simple request to verify LiteLLM is accessible // Returns true if LiteLLM is running and responsive } ``` -------------------------------- ### Set Custom Client Per Agent in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/README.md Shows how to configure a custom OpenAI client for a specific agent using the `WithModelInstance` option. This allows for fine-grained control over which model provider and configuration an agent uses, independent of global settings. Environment variables for the provider must be set. ```bash export EXAMPLE_BASE_URL="http://your-provider-host" export EXAMPLE_API_KEY="your-custom-api-key" export EXAMPLE_MODEL_NAME="your-model-name" go run ./examples/model_providers/custom_example_agent ``` -------------------------------- ### Enable LiteLLM Debug Mode Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/custom_example_litellm/README.md Enables verbose logging for LiteLLM by setting 'set_verbose' to true in the configuration. Alternatively, debug information can be accessed via Docker container logs. ```yaml general_settings: set_verbose: true ``` ```bash docker logs ``` -------------------------------- ### Set Custom Model Provider in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/README.md Demonstrates how to provide a custom ModelProvider for use with the Runner. This involves defining a new provider and integrating it into the agent execution flow. It requires setting environment variables for the provider's base URL, API key, and model name. ```bash export EXAMPLE_BASE_URL="http://your-provider-host" export EXAMPLE_API_KEY="your-custom-api-key" export EXAMPLE_MODEL_NAME="your-model-name" go run ./examples/model_providers/custom_example_provider ``` -------------------------------- ### Set Global Default OpenAI Client in Go Source: https://github.com/nlpodyssey/openai-agents-go/blob/main/examples/model_providers/README.md Illustrates setting a global default OpenAI client and API endpoint (`chat_completions`) for all agents within the SDK. This simplifies configuration when all agents are intended to use the same provider. Environment variables for the provider must be set. ```bash export EXAMPLE_BASE_URL="http://your-provider-host" export EXAMPLE_API_KEY="your-custom-api-key" export EXAMPLE_MODEL_NAME="your-model-name" go run ./examples/model_providers/custom_example_global ``` -------------------------------- ### Define Typed Outputs in Go Source: https://context7.com/nlpodyssey/openai-agents-go/llms.txt Shows how to define and use typed output structures with validation for OpenAI agents. The WithOutputType method sets the expected struct, and FinalOutput is automatically parsed. Requires the openai-agents-go library and Go's JSON struct tags. ```go package main import ( "context" "fmt" "github.com/nlpodyssey/openai-agents-go/agents" ) // Define output structure type MovieRecommendation struct { Title string `json:"title"` Year int `json:"year"` Genre []string `json:"genre"` Rating float64 `json:"rating"` Description string `json:"description"` } func main() { agent := agents.New("Movie Recommender"). WithInstructions("You recommend movies based on user preferences."). WithOutputType(agents.OutputType[MovieRecommendation]()). WithModel("gpt-4o") ctx := context.Background() result, err := agents.Run(ctx, agent, "Recommend a sci-fi movie from the 1980s.") if err != nil { panic(err) } // FinalOutput is automatically parsed to the struct type movie := result.FinalOutput.(MovieRecommendation) fmt.Printf("Title: %s (%d)\n", movie.Title, movie.Year) fmt.Printf("Genre: %v\n", movie.Genre) fmt.Printf("Rating: %.1f/10\n", movie.Rating) fmt.Printf("Description: %s\n", movie.Description) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.