Examples
Runnable examples demonstrating GoAI features. Each example is a standalone main.go that you can run directly.
All examples live in goai/examples/.
Core
Basic text generation, streaming, and structured output.
chat
Simple non-streaming text generation with GenerateText.
- Provider: Google Gemini
- Features:
GenerateText,WithSystem,WithPrompt, token usage - Source:
examples/chat/
export GEMINI_API_KEY=...
go run examples/chat/main.gostreaming
Streaming text generation with real-time output via TextStream().
- Provider: Google Gemini
- Features:
StreamText,TextStream(),Result()for usage after streaming - Source:
examples/streaming/
export GEMINI_API_KEY=...
go run examples/streaming/main.gostructured
Structured output with typed Go structs using GenerateObject[T] and StreamObject[T].
- Provider: Google Gemini
- Features:
GenerateObject[T],StreamObject[T],PartialObjectStream(),SchemaFrom[T], struct tags (jsonschema) - Source:
examples/structured/
export GEMINI_API_KEY=...
go run ./examples/structured/main.goembedding
Text embeddings with Embed and EmbedMany, including cosine similarity comparison.
- Provider: Google Gemini (
gemini-embedding-001) - Features:
Embed,EmbedMany, auto-chunking, pairwise cosine similarity - Source:
examples/embedding/
export GEMINI_API_KEY=...
go run ./examples/embedding/main.gocitations
Accessing Sources from grounded AI responses. The Sources API is provider-agnostic.
- Provider: Google Gemini
- Features:
TextResult.Sources, per-step sources,Source.URL,Source.Title, text offsets - Source:
examples/citations/
export GEMINI_API_KEY=...
go run examples/citations/main.gocloudflare-chat
Non-streaming chat with Cloudflare Workers AI.
- Provider: Cloudflare Workers AI
- Features:
GenerateText,WithSystem,WithPrompt - Source:
examples/cloudflare-chat/
export CLOUDFLARE_API_TOKEN=...
export CLOUDFLARE_ACCOUNT_ID=...
go run examples/cloudflare-chat/main.gofptcloud-chat
Non-streaming chat with FPT Smart Cloud AI Marketplace.
- Provider: FPT Smart Cloud
- Features:
GenerateText,WithSystem,WithPrompt - Source:
examples/fptcloud-chat/
export FPT_API_KEY=...
# Optional: export FPT_REGION=jp # default is "global"
go run examples/fptcloud-chat/main.gonvidia-chat
Non-streaming chat with NVIDIA NIM.
- Provider: NVIDIA NIM
- Features:
GenerateText,WithPrompt - Source:
examples/nvidia-chat/
export NVIDIA_API_KEY=...
go run examples/nvidia-chat/main.govideo-generation
Video generation with Google Veo, including automatic long-running-operation polling.
- Provider: Google Gemini (Veo)
- Features:
GenerateVideo,WithVideoPrompt,WithVideoAspectRatio,WithVideoResolution,WithVideoDuration,WithVideoAudio - Source:
examples/video-generation/
export GEMINI_API_KEY=...
go run examples/video-generation/main.goTools
Custom tools, agent loops, and provider-defined tools.
tools
Single-step tool call with a custom tool definition and Execute handler.
- Provider: Google Gemini
- Features:
goai.Tool,InputSchema(JSON Schema),Executefunction,WithMaxSteps(2) - Source:
examples/tools/
export GEMINI_API_KEY=...
go run examples/tools/main.gomulti-turn
Multi-turn conversation with tools using ResponseMessages to preserve history across turns.
- Provider: Google Gemini
- Features:
ResponseMessages, multi-turn tool context, conversation history management - Source:
examples/multi-turn/
export GEMINI_API_KEY=...
go run examples/multi-turn/main.gostreaming-tools
Streaming text generation with multi-step tool loops via StreamText.
- Provider: OpenAI
- Features:
StreamText,WithMaxSteps, tool execution during streaming,Stream()consumption - Source:
examples/streaming-tools/
export OPENAI_API_KEY=...
go run examples/streaming-tools/main.goagent-loop
Multi-step agent loop with multiple tools and step/tool-call callbacks.
- Provider: Google Gemini
- Features: Multiple tools,
WithMaxSteps(5),WithOnStepFinish,WithOnToolCall, step history - Source:
examples/agent-loop/
export GEMINI_API_KEY=...
go run examples/agent-loop/main.goProvider-Defined Tools
These examples use built-in tools provided by specific AI providers. The provider handles tool execution server-side.
web-search
Web search across OpenAI, Anthropic, and Google using their respective provider-defined tools.
- Providers: OpenAI (direct + Azure), Anthropic (direct + Bedrock), Google
- Features:
openai.Tools.WebSearch(),anthropic.Tools.WebSearch(),google.Tools.GoogleSearch(), source citations - Source:
examples/web-search/
export OPENAI_API_KEY=...
go run examples/web-search/main.go openai
export ANTHROPIC_API_KEY=...
go run examples/web-search/main.go anthropic
export GEMINI_API_KEY=...
go run examples/web-search/main.go googlegoogle-search
Google Search grounding with Gemini, returning grounded responses with source URLs.
- Provider: Google Gemini
- Features:
google.Tools.GoogleSearch(), grounding sources - Source:
examples/google-search/
export GEMINI_API_KEY=...
go run examples/google-search/main.goweb-fetch
Anthropic's web fetch tool for retrieving and processing content from specific URLs.
- Providers: Anthropic (direct + Bedrock)
- Features:
anthropic.Tools.WebFetch(), citation support, URL content processing - Source:
examples/web-fetch/
export ANTHROPIC_API_KEY=...
go run examples/web-fetch/main.go anthropiccomputer-use
Anthropic's computer use tools: Computer (mouse/keyboard), Bash (shell), TextEditor (file editing).
- Providers: Anthropic (direct + Bedrock)
- Features:
anthropic.Tools.Computer(),anthropic.Tools.Bash(),anthropic.Tools.TextEditor(), provider-defined tools with client-sideExecutehandlers - Source:
examples/computer-use/
export ANTHROPIC_API_KEY=...
go run examples/computer-use/main.go anthropiccode-execution
Anthropic's sandboxed Python code execution tool.
- Providers: Anthropic (direct + Bedrock)
- Features:
anthropic.Tools.CodeExecution(), server-side Python execution (Anthropic direct) or tool-call-style client-side handling (Bedrock) - Source:
examples/code-execution/
export ANTHROPIC_API_KEY=...
go run examples/code-execution/main.go anthropiccode-interpreter
OpenAI's code interpreter tool for sandboxed Python execution.
- Providers: OpenAI (direct + Azure)
- Features:
openai.Tools.CodeInterpreter(), server-side Python execution - Source:
examples/code-interpreter/
export OPENAI_API_KEY=...
go run examples/code-interpreter/main.go openaigoogle-code-execution
Google Gemini's sandboxed Python code execution tool.
- Provider: Google Gemini
- Features:
google.Tools.CodeExecution(), server-side Python execution - Source:
examples/google-code-execution/
export GEMINI_API_KEY=...
go run examples/google-code-execution/main.goimage-generation
OpenAI's image generation tool via the Responses API. The LLM decides when to generate images during conversation.
- Providers: OpenAI (direct + Azure)
- Features:
openai.Tools.ImageGeneration(), image quality/size options - Source:
examples/image-generation/
export OPENAI_API_KEY=...
go run examples/image-generation/main.go openaifile-search
OpenAI's file search tool for semantic/keyword search over vector stores.
- Providers: OpenAI (direct + Azure)
- Features:
openai.Tools.FileSearch(), vector store integration - Source:
examples/file-search/
Requires a pre-created vector store with uploaded files.
export OPENAI_API_KEY=...
go run examples/file-search/main.go openai <vector-store-id>Realtime
realtime-voice
Bidirectional voice session with Gemini Live. Sends a text prompt or a recorded 16 kHz PCM file, writes the 24 kHz spoken reply to a file, prints transcripts, and lets the model call a local tool that the session runs automatically.
- Provider: Google Gemini (Gemini API or Vertex AI)
- Features:
google.Live,vertex.Live,OpenRealtimeSession,InputAudio,SendText,WithRealtimeTools, transcripts - Source:
examples/realtime-voice/
export GEMINI_API_KEY=...
go run ./examples/realtime-voice/main.go -text "What time is it in Tokyo?"
ffplay -f s16le -ar 24000 -ac 1 reply.pcmMCP
MCP (Model Context Protocol) client examples. Connect to MCP servers and use their tools with GoAI.
mcp-tools
MCP tools with GoAI LLM integration. Connects to an MCP server, converts its tools, and passes them to GenerateText for an agent loop.
Note: This example prefers the local MCP test server when available and otherwise falls back to the public
@modelcontextprotocol/server-filesystemserver.
- Provider: Google Gemini
- Features:
mcp.NewStdioTransport,mcp.NewClient,mcp.ConvertTools,goai.WithTools,WithMaxSteps - Source:
examples/mcp-tools/
export GEMINI_API_KEY=...
go run ./examples/mcp-tools/main.gomcp-parallel
Search the web or extract a page with Parallel Search MCP over Streamable HTTP. The example discovers tools and calls web_search or web_fetch directly, without a language model or API key. Anonymous access is free for light use, with lower rate limits.
- Transport: HTTP (
https://search.parallel.ai/mcp) - Requires: Go 1.25+ and internet access
- Features:
mcp.NewHTTPTransport,client.ListTools, search and page extraction - Source:
examples/mcp-parallel/
From a checkout of this repository, install the declared dependencies and run either mode:
go mod download
go run ./examples/mcp-parallel/main.go -query "Go 1.25 release highlights"
go run ./examples/mcp-parallel/main.go -url https://go.dev/doc/go1.25Both modes print the available tool names and the returned page excerpts. -url selects fetch instead of search. Ctrl+C cancels the request; the example has a two-minute overall deadline.
Like the example, its HTTP fixture tests are run by targeting the files directly:
go test -race ./examples/mcp-parallel/main.go ./examples/mcp-parallel/main_test.gomcp-deed-page
Publish an HTML page to a public https://{slug}.deed.page/ URL with the deed.page MCP server over Streamable HTTP, then delete it. The example discovers tools and calls publish_site or delete_site directly, without a language model, account or API key.
- Transport: HTTP (
https://deed.page/mcp) - Requires: Go 1.25+ and internet access
- Features:
mcp.NewHTTPTransport,client.ListTools, publishing and deleting a page - Source:
examples/mcp-deed-page/
From a checkout of this repository:
go mod download
go run ./examples/mcp-deed-page/main.go
go run ./examples/mcp-deed-page/main.go -file report.html -slug my-goai-report -ttl 0
DEED_PAGE_TOKEN=deed_tok_... go run ./examples/mcp-deed-page/main.go -delete my-goai-reportThe first command publishes a small sample page that expires after an hour (-ttl, default 3600; 0 keeps the page). The result includes the public url, the slug and, on the first publish, an owner token; set DEED_PAGE_TOKEN to that token to delete the page with -delete. Keep the token private, and only publish content that may be public: anyone with the URL can open it.
Like the example, its HTTP fixture tests are run by targeting the files directly:
go test -race ./examples/mcp-deed-page/main.go ./examples/mcp-deed-page/main_test.gomcp-sem
Inspect a known entity and its related source with Sem over stdio MCP. This optional example calls only sem_find; it does not use a language model or require an API key.
- Requires: Go 1.25+, Node.js with
npx, a trusted Git checkout, and supported macOS/Linux x64 or ARM64. - Source:
examples/mcp-sem/
go run ./examples/mcp-sem/main.go -repo /absolute/path/to/repo -query parse_config
go test -race ./examples/mcp-sem/main.go ./examples/mcp-sem/main_test.goReplace the path and symbol with your own. The first launch downloads the pinned npm package and native binary. The example disables Sem cloud sync and telemetry, not npm downloads. Ctrl+C cancels the operation; the overall deadline is two minutes.
The full Sem server is not read-only: other tools can execute repository commands. The explicit repository path is not an OS sandbox, and stdio inherits the parent environment. Use trusted repositories and a suitably isolated environment. Structural results depend on language/index coverage and do not prove the absence of callers or replace tests. No agent performance claims are implied by this connectivity example.
mcp-filesystem
Filesystem MCP server integration via stdio. Lists available tools and calls list_directory on the official MCP filesystem server.
- Transport: Stdio
- Requires: Node.js (npx)
- Features:
mcp.NewStdioTransport,client.ListTools, tool calling, file operations - Source:
examples/mcp-filesystem/
go run ./examples/mcp-filesystem/main.go /tmpmcp-github
GitHub MCP server integration via stdio. Discover and call GitHub tools.
- Transport: Stdio
- Requires: Node.js (npx),
GITHUB_TOKEN - Features:
mcp.NewStdioTransport, GitHub API tools - Source:
examples/mcp-github/
export GITHUB_TOKEN=ghp_...
go run ./examples/mcp-github/main.gomcp-playwright
Playwright MCP server for browser automation. Navigate, click, fill, screenshot via MCP tools.
- Transport: Stdio
- Requires: Node.js (npx)
- Features:
mcp.NewStdioTransport, browser automation tools - Source:
examples/mcp-playwright/
go run ./examples/mcp-playwright/main.gomcp-remote
MCP over Streamable HTTP transport. Demonstrates session management, notifications, and remote tool calling.
Note: This example requires a local MCP test server implementation compatible with the commands used in
examples/mcp-remote/main.go.
- Transport: Streamable HTTP
- Features:
mcp.NewHTTPTransport, session management, remote server - Source:
examples/mcp-remote/
go run ./examples/mcp-remote/main.gomcp-oauth
OAuth 2.1 + PKCE authentication for a remote MCP server. Runs a loopback server to capture the OAuth redirect, opens the authorization URL in your browser, then lists the server's tools. If GEMINI_API_KEY is set, it also lets Gemini call the MCP tools.
- Transport: Streamable HTTP (OAuth 2.1 + PKCE)
- Requires: a browser for OAuth authorization and a zero-config OAuth MCP server URL (e.g.
https://mcp.linear.app/mcp,https://mcp.sentry.dev/mcp);GEMINI_API_KEYis optional - Features:
mcp.NewOAuthTokenSource, dynamic client registration (RFC 7591), PKCE (RFC 7636), automatic token refresh - Source:
examples/mcp-oauth/
go run ./examples/mcp-oauth/main.go https://mcp.linear.app/mcpmcp-sse
MCP over legacy SSE transport (protocol version 2024-11-05). Endpoint discovery, tool listing, and tool calling.
Note: This example requires a local MCP test server implementation compatible with the commands used in
examples/mcp-sse/main.go.
- Transport: SSE (legacy)
- Features:
mcp.NewSSETransport, legacy protocol support - Source:
examples/mcp-sse/
go run ./examples/mcp-sse/main.gomcp-local
MCP client basics without an LLM. Exercises every MCP capability: tools, prompts, and resources.
Note: This example requires a local MCP test server implementation compatible with the commands used in
examples/mcp-local/main.go.
- Transport: Stdio
- Features:
mcp.NewStdioTransport,client.ListTools,client.ListPrompts,client.ListResources - Source:
examples/mcp-local/
go run ./examples/mcp-local/main.goObservability & Hooks
Lifecycle hooks, Langfuse tracing, and OpenTelemetry integration.
hooks
Lifecycle hooks for tool interception, output transformation, and loop control.
- Provider: Google Gemini
- Features:
OnBeforeToolExecute(permission gate),OnAfterToolExecute(secret scanning),OnBeforeStep(loop control),OnFinish(max_steps detection) - Source:
examples/hooks/
export GEMINI_API_KEY=...
go run examples/hooks/main.golangfuse
Langfuse tracing for a multi-step agent with tool calls.
- Provider: Google Gemini
- Features:
langfuse.WithTracing, trace hierarchy (trace → span → generation), token usage, tool spans - Source:
examples/langfuse/
export GEMINI_API_KEY=...
export LANGFUSE_PUBLIC_KEY=pk-lf-...
export LANGFUSE_SECRET_KEY=sk-lf-...
go run examples/langfuse/main.gootel
OpenTelemetry tracing with stdout exporter for local development.
- Provider: Google Gemini
- Features:
otel.WithTracing, span hierarchy, custom attributes,RecordInputMessages,RecordOutputMessages - Source:
examples/otel/
export GEMINI_API_KEY=...
cd examples/otel && go run .