Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .github/workflows/gemini-go-docs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Gemini Go documentation

on:
pull_request:
branches: [main, dev]
paths:
- 'examples/traceai/gemini-go/**'
- 'src/pages/docs/integrations/traceai/go/gemini.mdx'
- 'scripts/gemini-go-page.test.mjs'
- '.github/workflows/gemini-go-docs.yml'

permissions:
contents: read

jobs:
privacy-contract:
name: Gemini Go privacy (SDK ${{ matrix.sdk }})
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
sdk: ['v1.71.0', 'v1.75.0']
defaults:
run:
working-directory: examples/traceai/gemini-go
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.26.0'
cache: false
- name: Install the released integration and supported SDK
run: |
go mod init example.com/gemini-go-example
go get github.com/future-agi/traceAI/go/genai@v0.1.1 google.golang.org/genai@${{ matrix.sdk }}
go get go.opentelemetry.io/otel/sdk@v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp@v1.47.0
go mod tidy
- name: Check formatting and exercise exported privacy behavior
env:
GOPROXY: 'off'
GOTOOLCHAIN: local
GOWORK: 'off'
run: |
test -z "$(gofmt -l main.go main_test.go)"
go test -race -count=1 -v ./...
32 changes: 32 additions & 0 deletions examples/traceai/gemini-go/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Gemini Go example

The complete program for the [Gemini Go guide](https://docs.futureagi.com/docs/integrations/traceai/go/gemini): a small
weather agent on the Google Gen AI Go SDK (`google.golang.org/genai`, Gemini Developer API) traced with
`github.com/future-agi/traceAI/go/genai`.

One run is one trace: an agent span, an LLM span that asks for `get_weather`, the tool span, and the final answer
(streamed with `-stream`). `-fail` adds one call to a model that does not exist, to show an ERROR span.

Custom agent and tool spans carry only identity, session and status metadata, not prompts, answers, tool arguments
or results. The traced client's content follows the guide's privacy settings. In v0.1.1, text-only hiding does not
redact arbitrary `input.value` or `output.value` attributes passed to `TraceConfig.SetAttributes`; this example
omits them. Privacy switches affect telemetry, not the answer printed to your terminal.

## Run it

Needs Go 1.26 or later, a Future AGI key pair and a Gemini Developer API key.

```bash
go mod init example.com/gemini-go-example
go get github.com/future-agi/traceAI/go/genai@v0.1.1 google.golang.org/genai@latest
go get go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp
go mod tidy

export FI_API_KEY="your-futureagi-api-key"
export FI_SECRET_KEY="your-futureagi-secret-key"
export FI_PROJECT_NAME="gemini-go-example"
export GEMINI_API_KEY="your-gemini-api-key"
go run . -stream -fail
```

`FI_BASE_URL` is optional (default `https://api.futureagi.com`). `-model` (or `GEMINI_MODEL`) picks the model.
232 changes: 232 additions & 0 deletions examples/traceai/gemini-go/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
// Command example runs a small weather agent on the Google Gen AI Go SDK
// (google.golang.org/genai, Gemini Developer API) and traces it to Future AGI
// with traceaigenai.
//
// export FI_API_KEY=... FI_SECRET_KEY=... FI_PROJECT_NAME=my-service GEMINI_API_KEY=...
// go run . -stream -fail
//
// One run is one trace: an agent span, an LLM span that asks for a tool, the
// tool span, and an LLM span for the final answer. -fail adds one call to a
// model that does not exist, to show an ERROR span.
//
// The exporter is the stock OpenTelemetry OTLP/HTTP exporter: Future AGI needs
// the X-Api-Key and X-Secret-Key headers, the project_name resource attribute,
// and an uncompressed body.
package main

import (
"context"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"

traceaigenai "github.com/future-agi/traceAI/go/genai"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"google.golang.org/genai"
)

func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}

// newTracerProvider sends spans to Future AGI over OTLP/HTTP: the full traces
// URL, both auth headers, no gzip (the collector rejects it), and the
// project_name / project_type resource attributes. It adds no host, process or
// OS resource detector, so no host name, user name or local path is exported.
func newTracerProvider(ctx context.Context) (*sdktrace.TracerProvider, error) {
apiKey, secretKey := os.Getenv("FI_API_KEY"), os.Getenv("FI_SECRET_KEY")
project := os.Getenv("FI_PROJECT_NAME")
if apiKey == "" || secretKey == "" || project == "" {
return nil, errors.New("set FI_API_KEY, FI_SECRET_KEY and FI_PROJECT_NAME")
}
base := strings.TrimRight(envOr("FI_BASE_URL", "https://api.futureagi.com"), "/")

exp, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpointURL(base+"/tracer/v1/traces"),
otlptracehttp.WithHeaders(map[string]string{
"X-Api-Key": apiKey,
"X-Secret-Key": secretKey,
}),
otlptracehttp.WithCompression(otlptracehttp.NoCompression),
)
if err != nil {
return nil, err
}
res, err := resource.Merge(resource.Default(), resource.NewSchemaless(
attribute.String("project_name", project),
attribute.String("project_type", "observe"),
attribute.String("service.name", project),
))
if err != nil {
return nil, err
}
return sdktrace.NewTracerProvider(
sdktrace.WithResource(res),
sdktrace.WithBatcher(exp),
), nil
}

// shutdown flushes every queued span. A span that is only queued when the
// process exits is lost.
func shutdown(tp *sdktrace.TracerProvider) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tp.Shutdown(ctx); err != nil {
fmt.Fprintln(os.Stderr, "trace export:", err)
}
}

func run() error {
model := flag.String("model", envOr("GEMINI_MODEL", "gemini-3.8-flash"), "Gemini model")
question := flag.String("question", "What is the weather in Paris right now? Answer in one sentence.", "user question")
stream := flag.Bool("stream", false, "stream the final answer")
fail := flag.Bool("fail", false, "also call a model that does not exist, to show an ERROR span")
session := flag.String("session", fmt.Sprintf("gemini-go-example-%d", time.Now().Unix()), "session id")
flag.Parse()

ctx := context.Background()

// 1. Exporter and provider.
tp, err := newTracerProvider(ctx)
if err != nil {
return err
}
// 2. Flush before exit.
defer shutdown(tp)

// 3. The Gemini client with the traced HTTP client. The SDK reads
// GEMINI_API_KEY (or GOOGLE_API_KEY) as usual.
client, err := genai.NewClient(ctx, &genai.ClientConfig{
Backend: genai.BackendGeminiAPI,
HTTPClient: traceaigenai.NewHTTPClient(traceaigenai.WithTracerProvider(tp)),
})
if err != nil {
return err
}

tracer := tp.Tracer("gemini-go-example")
sessionCtx := traceaigenai.ContextWithSessionID(ctx, *session)
answer, err := runAgent(sessionCtx, client, tracer, *model, *question, *stream)
if err != nil {
return err
}
fmt.Println("answer:", answer)

if *fail {
// A separate trace in the same session.
_, err := client.Models.GenerateContent(sessionCtx, "no-such-model", genai.Text(*question), nil)
var apiErr genai.APIError
if errors.As(err, &apiErr) {
fmt.Printf("expected failure: HTTP %d %s\n", apiErr.Code, apiErr.Status)
} else {
fmt.Printf("expected failure, got: %v\n", err)
}
}
return nil
}

// Custom spans carry identity, session and status metadata only. Content is
// recorded only by the traced client, which applies its FI_HIDE_* switches.
func runAgent(sessionCtx context.Context, client *genai.Client, tracer trace.Tracer,
model, question string, stream bool) (string, error) {
ctx, agent := tracer.Start(sessionCtx, "weather-agent", trace.WithAttributes(
attribute.String(traceaigenai.GenAISpanKind, traceaigenai.SpanKindAgent),
attribute.String(traceaigenai.GenAIOperationName, "invoke_agent"),
attribute.String("gen_ai.agent.name", "weather-agent"),
), trace.WithAttributes(traceaigenai.ContextAttributes(sessionCtx)...))
defer agent.End()
fmt.Printf("trace_id=%s\n", agent.SpanContext().TraceID())

answer, err := askWithTool(ctx, client, tracer, model, question, stream)
if err != nil {
agent.SetStatus(codes.Error, "agent failed")
}
return answer, err
}

func askWithTool(ctx context.Context, client *genai.Client, tracer trace.Tracer,
model, question string, stream bool) (string, error) {
config := &genai.GenerateContentConfig{
SystemInstruction: genai.NewContentFromText("You are a weather assistant. Always call get_weather before answering.", genai.RoleUser),
Tools: []*genai.Tool{{FunctionDeclarations: []*genai.FunctionDeclaration{{
Name: "get_weather",
Description: "Current weather for a city",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{"city": {Type: genai.TypeString}},
Required: []string{"city"},
},
}}}},
}
history := genai.Text(question)

first, err := client.Models.GenerateContent(ctx, model, history, config)
if err != nil {
return "", err
}
calls := first.FunctionCalls()
if len(calls) == 0 {
return first.Text(), nil
}
// Send the model's turn back unchanged (it carries the thought signature
// Gemini needs), then one function response per call.
history = append(history, first.Candidates[0].Content)
var results []*genai.Part
for _, call := range calls {
result := runTool(ctx, tracer, call.ID, call.Name, call.Args)
part := genai.NewPartFromFunctionResponse(call.Name, result)
part.FunctionResponse.ID = call.ID
results = append(results, part)
}
history = append(history, genai.NewContentFromParts(results, genai.RoleUser))

if !stream {
final, err := client.Models.GenerateContent(ctx, model, history, config)
if err != nil {
return "", err
}
return final.Text(), nil
}

var b strings.Builder
for chunk, err := range client.Models.GenerateContentStream(ctx, model, history, config) {
if err != nil {
return b.String(), err
}
b.WriteString(chunk.Text())
}
return b.String(), nil
}

// runTool executes the tool locally inside its own span. The transport spans
// the model calls; your tool code is yours to span.
func runTool(ctx context.Context, tracer trace.Tracer, id, name string, args map[string]any) map[string]any {
_, span := tracer.Start(ctx, "execute_tool "+name, trace.WithAttributes(
attribute.String(traceaigenai.GenAISpanKind, traceaigenai.SpanKindTool),
attribute.String(traceaigenai.GenAIOperationName, "execute_tool"),
attribute.String(traceaigenai.GenAIToolName, name),
attribute.String(traceaigenai.GenAIToolCallID, id),
), trace.WithAttributes(traceaigenai.ContextAttributes(ctx)...))
defer span.End()

city, _ := args["city"].(string)
return map[string]any{"city": city, "temperature_c": 21, "conditions": "sunny"}
}

func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
Loading
Loading