Files
go-llm/v2/agent/example_test.go
Steve Dudenhoeffer 5b687839b2
All checks were successful
CI / Lint (pull_request) Successful in 10m18s
CI / Root Module (pull_request) Successful in 11m4s
CI / V2 Module (pull_request) Successful in 11m5s
feat: comprehensive token usage tracking for V2
Add provider-specific usage details, fix streaming usage, and return
usage from all high-level APIs (Chat.Send, Generate[T], Agent.Run).

Breaking changes:
- Chat.Send/SendMessage/SendWithImages now return (string, *Usage, error)
- Generate[T]/GenerateWith[T] now return (T, *Usage, error)
- Agent.Run/RunMessages now return (string, *Usage, error)

New features:
- Usage.Details map for provider-specific token breakdowns
  (reasoning, cached, audio, thoughts tokens)
- OpenAI streaming now captures usage via StreamOptions.IncludeUsage
- Google streaming now captures UsageMetadata from final chunk
- UsageTracker.Details() for accumulated detail totals
- ModelPricing and PricingRegistry for cost computation

Closes #2

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 04:33:18 +00:00

108 lines
3.4 KiB
Go

package agent_test
import (
"context"
"fmt"
"os"
llm "gitea.stevedudenhoeffer.com/steve/go-llm/v2"
"gitea.stevedudenhoeffer.com/steve/go-llm/v2/agent"
"gitea.stevedudenhoeffer.com/steve/go-llm/v2/tools"
)
// A researcher agent that can search the web and browse pages.
func Example_researcher() {
model := llm.OpenAI(os.Getenv("OPENAI_API_KEY")).Model("gpt-4o")
researcher := agent.New(model,
"You are a research assistant. Use web search to find information, "+
"then use the browser to read full articles when needed. "+
"Provide a concise summary of your findings.",
agent.WithTools(llm.NewToolBox(
tools.WebSearch(os.Getenv("BRAVE_API_KEY")),
tools.Browser(),
)),
agent.WithRequestOptions(llm.WithTemperature(0.3)),
)
result, _, err := researcher.Run(context.Background(), "What are the latest developments in Go generics?")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}
// A coder agent that can read, write, and execute code.
func Example_coder() {
model := llm.OpenAI(os.Getenv("OPENAI_API_KEY")).Model("gpt-4o")
coder := agent.New(model,
"You are a coding assistant. You can read files, write files, and execute commands. "+
"When asked to create a program, write the code to a file and then run it to verify it works.",
agent.WithTools(llm.NewToolBox(
tools.ReadFile(),
tools.WriteFile(),
tools.Exec(
tools.WithAllowedCommands([]string{"go", "python", "node", "cat", "ls"}),
tools.WithWorkDir(os.TempDir()),
),
)),
)
result, _, err := coder.Run(context.Background(),
"Create a Go program that prints the first 10 Fibonacci numbers. Save it and run it.")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}
// An orchestrator agent that delegates to specialized sub-agents.
// The orchestrator breaks a complex task into subtasks and dispatches them
// to the appropriate sub-agent via tool calls.
func Example_orchestrator() {
model := llm.OpenAI(os.Getenv("OPENAI_API_KEY")).Model("gpt-4o")
// Specialized sub-agents
researcher := agent.New(model,
"You are a research assistant. Search the web for information on the given topic "+
"and return a concise summary.",
agent.WithTools(llm.NewToolBox(
tools.WebSearch(os.Getenv("BRAVE_API_KEY")),
)),
)
coder := agent.New(model,
"You are a coding assistant. Write and test code as requested. "+
"Save files and run them to verify they work.",
agent.WithTools(llm.NewToolBox(
tools.ReadFile(),
tools.WriteFile(),
tools.Exec(tools.WithAllowedCommands([]string{"go", "python"})),
)),
)
// Orchestrator can delegate to both sub-agents
orchestrator := agent.New(model,
"You are a project manager. Break complex tasks into research and coding subtasks. "+
"Use delegate_research for information gathering and delegate_coding for implementation. "+
"Synthesize the results into a final answer.",
agent.WithTools(llm.NewToolBox(
researcher.AsTool("delegate_research",
"Delegate a research task. Provide a clear question or topic to research."),
coder.AsTool("delegate_coding",
"Delegate a coding task. Provide clear requirements for what to implement."),
)),
)
result, _, err := orchestrator.Run(context.Background(),
"Research how to implement a binary search tree in Go, then create one with insert and search operations.")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}