### Quickstart Example: Orchestrator Service with Chat Agent Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/dsl-reference.md This example demonstrates defining a service named 'orchestrator' with a 'chat' agent. It includes defining toolsets, exporting tools, and setting run policies. ```go package design import ( . "goa.design/goa/v3/dsl" . "goa.design/goa-ai/dsl" ) var DocsToolset = Toolset("docs.search", func() { Tool("search", "Search indexed documentation", func() { Args(func() { Attribute("query", String, "Search phrase") Attribute("limit", Int, "Max results", func() { Default(5) }) Required("query") }) Return(func() { Attribute("documents", ArrayOf(String), "Matched snippets") Required("documents") }) Tags("docs", "search") }) }) var AssistantSuite = Toolset(FromMCP("assistant", "assistant-mcp")) var _ = Service("orchestrator", func() { Description("Human front door for the knowledge agent.") Agent("chat", "Conversational runner", func() { Use(DocsToolset) Use(AssistantSuite) Export("chat.tools", func() { Tool("summarize_status", "Produce operator-ready summaries", func() { Args(func() { Attribute("prompt", String, "User instructions") Required("prompt") }) Return(func() { Attribute("summary", String, "Assistant response") Required("summary") }) Tags("chat") }) }) RunPolicy(func() { DefaultCaps( MaxToolCalls(8), MaxConsecutiveFailedToolCalls(3), ) TimeBudget("2m") }) }) }) ``` -------------------------------- ### Complete MCP Server Example in Goa DSL Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/dsl-reference.md A comprehensive example demonstrating the setup of an MCP server with various features including static/dynamic prompts, resource definitions, watchable resources, subscriptions, notifications, and tools. ```go var _ = Service("assistant", func() { Description("Full-featured MCP server example") MCP("assistant-mcp", "1.0.0", ProtocolVersion("2025-06-18")) StaticPrompt("greeting", "Friendly greeting", "system", "You are a helpful assistant", "user", "Hello!") Method("search", func() { Description("Search documents") Payload(func() { Attribute("query", String, "Search query") Required("query") }) Result(func() { Attribute("results", ArrayOf(String), "Search results") Required("results") }) Tool("search", "Search documents by query") }) Method("get_readme", func() { Result(String) Resource("readme", "file:///README.md", "text/markdown") }) Method("get_status", func() { Result(func() { Attribute("status", String) Attribute("updated_at", String) }) WatchableResource("status", "status://system", "application/json") }) Method("subscribe_status", func() { Payload(func() { Attribute("uri", String) }) Result(String) Subscription("status") }) Method("review_code", func() { Payload(func() { Attribute("language", String) Attribute("code", String) Required("language", "code") }) Result(ArrayOf(Message)) DynamicPrompt("code_review", "Generate code review prompt") }) Method("notify_progress", func() { Payload(func() { Attribute("task_id", String) Attribute("progress", Int) Required("task_id", "progress") }) Notification("progress", "Task progress update") }) }) ``` -------------------------------- ### Install Temporalite for Development Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/production.md Install and start Temporalite, a lightweight Temporal server suitable for development environments. ```bash go install go.temporal.io/server/cmd/temporalite@latest temporalite start ``` -------------------------------- ### Start Documentation Container Source: https://github.com/goadesign/goa.design/blob/main/README.md Use these commands to start a previously created Docker container for the documentation. Then, execute commands inside the container to navigate to the app directory and start the development server. ```bash docker start goadocs; docker exec -it goadocs bash; cd /go/src/app; ``` -------------------------------- ### Health Check Setup with Clue Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/contributing.md Demonstrates how to initialize a health checker with various service pingers using the clue/health package. Ensure necessary imports are included for a runnable example. ```go // Include necessary imports import "goa.design/clue/health" // Show complete, runnable example checker := health.NewChecker( health.NewPinger("database", dbAddr), health.NewPinger("cache", redisAddr), ) ``` -------------------------------- ### Install Goa Ecosystem Libraries Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/_index.md Install the Goa ecosystem libraries using `go get`. This command fetches and installs the specified packages, making them available for use in your Go projects. ```bash go get goa.design/model go get goa.design/pulse go get goa.design/clue ``` -------------------------------- ### Install Goa CLI and Initialize Project Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/quickstart.md Installs the Goa CLI, creates a new project directory, initializes Go modules, and fetches necessary Goa and Goa-AI dependencies. ```bash go install goa.design/goa/v3/cmd/goa@latest mkdir quickstart && cd quickstart go mod init example.com/quickstart go get goa.design/goa/v3@latest goa.design/goa-ai@latest mkdir design ``` -------------------------------- ### Example Planner Logic for Handling Tool Outputs Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/toolsets.md Illustrates planner logic for processing tool outputs, specifically checking for errors and retry hints. It guides the planner on whether to seek clarification or proceed. ```go func (p *MyPlanner) PlanResume(ctx context.Context, in *planner.PlanResumeInput) (*planner.PlanResult, error) { if len(in.ToolOutputs) == 0 { return &planner.PlanResult{}, nil } last := in.ToolOutputs[len(in.ToolOutputs)-1] if last.Error != nil && last.RetryHint != nil { hint := last.RetryHint switch hint.Reason { case planner.RetryReasonMissingFields, planner.RetryReasonInvalidArguments: return &planner.PlanResult{ Await: &planner.Await{ Clarification: &planner.AwaitClarification{ ID: "fix-" + string(hint.Tool), Question: hint.ClarifyingQuestion, MissingFields: hint.MissingFields, RestrictToTool: hint.Tool, ExampleInput: hint.ExampleInput, ClarifyingPrompt: hint.Message, }, }, }, nil } } return &planner.PlanResult{/* FinalResponse, next ToolCalls, ... */}, nil } ``` -------------------------------- ### Complete Tool Example with All Features Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/dsl-reference.md A comprehensive example defining a tool with arguments, return types, enums, arrays, maps, and utilizing built-in template functions for hint generation. ```go Tool("analyze_data", "Analyze dataset", func() { Args(func() { Attribute("dataset_id", String, "Dataset identifier") Attribute("analysis_type", String, "Type of analysis", func() { Enum("summary", "detailed", "comparison") }) Attribute("filters", ArrayOf(String), "Optional filters") Required("dataset_id", "analysis_type") }) Return(func() { Attribute("insights", ArrayOf(String), "Analysis insights") Attribute("metrics", MapOf(String, Float64), "Computed metrics") Attribute("processing_time_ms", Int, "Processing time in milliseconds") Required("insights", "processing_time_ms") }) CallHintTemplate("Analyzing {{ .DatasetID }} ({{ .AnalysisType }})") ResultHintTemplate("{{ count .Result.Insights }} insights in {{ .Result.ProcessingTimeMs }}ms") }) ``` -------------------------------- ### Provide Sample Values for Documentation Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Use the `Example` function within type definitions to provide sample values for documentation. Multiple examples can be provided for a single attribute, and formats like `FormatEmail` can be applied. ```go var User = Type("User", func() { Attribute("name", String, func() { Example("John Doe") }) Attribute("email", String, func() { Example("work", "john@work.com") Example("personal", "john@gmail.com") Format(FormatEmail) }) }) var Address = Type("Address", func() { Attribute("street", String) Attribute("city", String) Required("street", "city") Example("Home Address", func() { Description("Example of a residential address") Value(Val{ "street": "123 Main St", "city": "Boston", }) }) }) ``` -------------------------------- ### Complete Example: Managing Todo Reminders Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/production.md This comprehensive example demonstrates the logic for adding, removing, and updating todo-related reminders based on the state of completed and pending items. ```go func (p *myPlanner) PlanResume(ctx context.Context, in *planner.PlanResumeInput) (*planner.PlanResult, error) { for _, tr := range in.ToolOutputs { if tr.Name == "todos.update_todos" { snap, err := specs.UnmarshalUpdateTodosResult(tr.Result) if err != nil { return nil, err } var rem *reminder.Reminder if len(snap.Items) == 0 { in.Agent.RemoveReminder("todos.no_active") in.Agent.RemoveReminder("todos.all_completed") } else if hasCompletedAll(snap) { rem = &reminder.Reminder{ ID: "todos.all_completed", Text: "All todos are completed. Provide your final response now.", Priority: reminder.TierGuidance, Attachment: reminder.Attachment{ Kind: reminder.AttachmentUserTurn, }, MaxPerRun: 1, } } else if hasPendingNoActive(snap) { rem = &reminder.Reminder{ ID: "todos.no_active", Text: buildTodosNudge(snap), Priority: reminder.TierGuidance, Attachment: reminder.Attachment{ Kind: reminder.AttachmentUserTurn, }, MinTurnsBetween: 3, } } if rem != nil { in.Agent.AddReminder(*rem) if rem.ID == "todos.all_completed" { in.Agent.RemoveReminder("todos.no_active") } else { in.Agent.RemoveReminder("todos.all_completed") } } } } return p.streamMessages(ctx, in) } ``` -------------------------------- ### Wire Generated Provider into Runtime Provider Loop Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/registry.md Wire the generated provider into the runtime provider loop to serve tool calls from the registry gateway. This example shows how to initialize the provider and start the Serve function, handling potential errors. ```go handler := toolsetpkg.NewProvider(serviceImpl) go func() { err := provider.Serve(ctx, pulseClient, toolsetID, handler, provider.Options{ Pong: func(ctx context.Context, pingID string) error { return registryClient.Pong(ctx, ®istry.PongPayload{ PingID: pingID, Toolset: toolsetID, }) }, }) if err != nil { panic(err) } }() ``` -------------------------------- ### Example Binary Deployment Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/registry.md Deploy the example registry binary. Nodes with the same `REGISTRY_NAME` and Redis instance form a cluster automatically, sharing registrations and coordinating health checks. ```bash # Single node (development) REDIS_URL=localhost:6379 go run ./registry/cmd/registry # Multi-node cluster (production) REGISTRY_NAME=prod REGISTRY_ADDR=:9090 REDIS_URL=redis:6379 ./registry REGISTRY_NAME=prod REGISTRY_ADDR=:9091 REDIS_URL=redis:6379 ./registry REGISTRY_NAME=prod REGISTRY_ADDR=:9092 REDIS_URL=redis:6379 ./registry ``` -------------------------------- ### Complete Goa Service Example with Instrumentation Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/clue.md A comprehensive example of a Goa service demonstrating the integration of logging, OpenTelemetry, and middleware for request handling. This setup includes initializing logging context, configuring OpenTelemetry exporters, creating service endpoints, and applying a middleware stack to the HTTP handler. ```go package main import ( "context" "net/http" "goa.design/clue/clue" "goa.design/clue/debug" "goa.design/clue/health" "goa.design/clue/log" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" genservice "myapp/gen/myservice" ) func main() { // 1. Initialize logging context with trace correlation ctx := log.Context(context.Background(), log.WithFormat(log.FormatJSON), log.WithFunc(log.Span)) // 2. Configure OpenTelemetry spanExporter, _ := otlptracegrpc.New(ctx, otlptracegrpc.WithInsecure()) metricExporter, _ := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithInsecure()) cfg, _ := clue.NewConfig(ctx, "myservice", "1.0.0", metricExporter, spanExporter) clue.ConfigureOpenTelemetry(ctx, cfg) // 3. Create service and endpoints svc := NewService() endpoints := genservice.NewEndpoints(svc) endpoints.Use(debug.LogPayloads()) // Log payloads when debug enabled endpoints.Use(log.Endpoint) // Add service/method to logs // 4. Create HTTP handler with middleware stack handler := genservice.NewHandler(endpoints) handler = otelhttp.NewHandler(handler, "myservice") // OpenTelemetry handler = debug.HTTP()(handler) // Debug log control handler = log.HTTP(ctx)(handler) // Request logging // 5. Mount on mux mux := http.NewServeMux() mux.Handle("/", handler) // 6. Mount operational endpoints debug.MountDebugLogEnabler(mux) debug.MountPprofHandlers(mux) mux.Handle("/healthz", health.Handler( health.NewChecker( health.NewPinger("database", dbAddr), ), )) // 7. Start server log.Printf(ctx, "starting server on :8080") http.ListenAndServe(":8080", mux) } ``` -------------------------------- ### Goa gRPC Server Implementation Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Sets up a gRPC server, registers the generated gRPC Calc server implementation, and starts serving requests on TCP port 8080. ```go func main() { svc := calc.New() endpoints := gencalc.NewEndpoints(svc) svr := grpc.NewServer() gensvr := gengrpc.New(endpoints, nil) genpb.RegisterCalcServer(svr, gensvr) lis, _ := net.Listen("tcp", ":8080") svr.Serve(lis) } ``` -------------------------------- ### Install Pulse Packages Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/pulse.md Installs the necessary Pulse packages for streaming, worker pools, and replicated maps using go get. ```bash go get goa.design/pulse/streaming go get goa.design/pulse/pool go get goa.design/pulse/rmap ``` -------------------------------- ### Install Goa Packages and CLI Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/quickstart.md Installs the Goa packages and the Goa CLI tool. Ensure your Go bin directory is in your PATH. ```bash # Pull the Goa packages go get goa.design/goa/v3/... # Install the Goa CLI go install goa.design/goa/v3/cmd/goa@latest # Verify the installation goa version ``` ```bash export PATH=$PATH:$(go env GOPATH)/bin ``` -------------------------------- ### Start Interactive Editor with mdl serve Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Starts a web-based editor for the model. Use this for interactive design and visualization. ```bash mdl serve ./model -dir gen -port 8080 ``` -------------------------------- ### Install Temporal Development Server (Docker) Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/production.md Use this one-liner to quickly set up a Temporal development server using Docker for local testing. ```bash docker run --rm -d --name temporal-dev -p 7233:7233 temporalio/auto-setup:latest ``` -------------------------------- ### Add Example to DSL Attribute Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/testing.md Enhance tool descriptions by adding examples directly in the DSL definition. This snippet demonstrates how to add an example value for the 'limit' attribute, along with its minimum and maximum allowed values. ```go Args(func() { Attribute("limit", Int, "Maximum results", func() { Example(10) Minimum(1) Maximum(100) }) }) ``` -------------------------------- ### Install Goa CLI Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Installs the Goa command-line interface using go install. Ensure your Go environment is set up correctly. ```bash go install goa.design/goa/v3/cmd/goa@latest ``` -------------------------------- ### Basic Health Checker Setup Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/clue.md Set up a basic health checker and mount its handler to /healthz and /livez endpoints. ```go import "goa.design/clue/health" func main() { checker := health.NewChecker() mux := http.NewServeMux() mux.Handle("/healthz", health.Handler(checker)) mux.Handle("/livez", health.Handler(checker)) } ``` -------------------------------- ### Implement Basic Authentication Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Example implementation of the BasicAuth method. It checks the provided username and password against hardcoded credentials. ```go func (s *svc) BasicAuth(ctx context.Context, user, pass string, scheme *security.BasicScheme) (context.Context, error) { if user != "goa" || pass != "rocks" { return ctx, ErrUnauthorized } return contextWithAuthInfo(ctx, authInfo{user: user}), nil } ``` -------------------------------- ### Goa Example Command Signature Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Presents the command signature for 'goa example', a scaffolding command that creates a one-time example implementation with handler stubs. ```bash goa example [-o ] ``` -------------------------------- ### Generate Deterministic Examples Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md To ensure consistent and predictable examples, use the `Randomizer` function with a deterministic randomizer. ```go var _ = API("exampleAPI", func() { Randomizer(expr.NewDeterministicRandomizer()) }) ``` -------------------------------- ### Install Clue Packages Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/clue.md Install specific Clue packages based on your needs. Each package provides distinct instrumentation features. ```bash go get goa.design/clue/clue go get goa.design/clue/log go get goa.design/clue/health go get goa.design/clue/debug go get goa.design/clue/mock go get goa.design/clue/interceptors ``` -------------------------------- ### Install Model CLI Tools Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Installs the 'mdl' and 'stz' command-line tools for generating and serving architecture diagrams. Requires Go 1.23+. ```bash go install goa.design/model/cmd/mdl@latest go install goa.design/model/cmd/stz@latest ``` -------------------------------- ### Planner Making MCP Tool Calls Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/mcp-integration.md Example of a planner implementing the PlanStart method to make a tool call to the 'assistant.assistant-mcp.search' tool with a specific query. ```go func (p *MyPlanner) PlanStart(ctx context.Context, in *planner.PlanInput) (*planner.PlanResult, error) { return &planner.PlanResult{ ToolCalls: []planner.ToolRequest{ { Name: "assistant.assistant-mcp.search", Payload: []byte(`{"query": "golang tutorials"}`), }, }, }, nil } ``` -------------------------------- ### Download Dependencies and Run Server Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/quickstart.md Downloads project dependencies using go mod tidy and starts the HTTP server on port 8080. ```bash go mod tidy go run ./cmd/hello --http-port=8080 ``` -------------------------------- ### Run Goa Example Service Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/_index.md Commands to generate and run a sample Goa service after defining the API design. ```bash goa gen hello/design goa example hello/design go run ./cmd/hello ``` -------------------------------- ### Copy Environment File Source: https://github.com/goadesign/goa.design/blob/main/scripts/TRANSLATION.md Copies the example environment file to be edited. Ensure you have a DeepL API key. ```bash cp .env.example .env ``` -------------------------------- ### CSS Theming Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Demonstrates how to implement light and dark themes using CSS custom properties defined by the generated SVGs. ```css /* Light theme (defaults from SVG) */ :root { --mdl-database-bg: #438DD5; --mdl-database-color: #ffffff; --mdl-rel-async-color: #707070; } /* Dark theme overrides */ [data-theme="dark"] { --mdl-database-bg: #3a7bc8; --mdl-database-color: #f0f0f0; --mdl-rel-async-color: #9ca3af; } ``` -------------------------------- ### Example Element and Relationship Styles for Theming Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Illustrates how element and relationship styles are defined, which are then used to generate CSS variables for theming. ```go Styles(func() { ElementStyle("database", func() { Background("#438DD5") Color("#ffffff") }) RelationshipStyle("async", func() { Color("#707070") }) }) ``` -------------------------------- ### Implement Goa Service Method Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/_index.md Implement the generated service interfaces to provide your business logic. This example shows the implementation of a `SayHello` method. ```go // service.go - You write this type helloService struct{} func (s *helloService) SayHello(ctx context.Context, p *hello.SayHelloPayload) (string, error) { return fmt.Sprintf("Hello, %s!", p.Name), nil } ``` -------------------------------- ### Map Primitive Payload to Header Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Maps a float32 payload to an HTTP header value. Example: GET / with header version=1.0 maps to List(1.0). ```go // Header Method("list", func() { Payload(Float32) HTTP(func() { GET("") Header("version") }) }) // GET / with header version=1.0 → List(1.0) ``` -------------------------------- ### Initialize Go Module and Create Design Directory Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/quickstart.md Sets up a new project directory and initializes a Go module. Creates a directory for the API design files. ```bash mkdir hello-goa && cd hello-goa go mod init hello mkdir design ``` -------------------------------- ### Map Primitive Payload to Path Parameter Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Maps an integer payload to a URL path parameter. Example: GET /1 maps to Show(1). ```go Method("show", func() { Payload(Int) HTTP(func() { GET("/{id}") }) }) // GET /1 → Show(1) ``` -------------------------------- ### Complete Agent Configuration with Caching Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/dsl-reference.md An example demonstrating a complete agent configuration including tool usage, run policies, and cache settings. Use AfterSystem() when the system prompt is stable, and AfterTools() when tool definitions are stable. ```go Agent("assistant", "Conversational assistant", func() { Use(DocsToolset) Use(SearchToolset) RunPolicy(func() { DefaultCaps(MaxToolCalls(10)) TimeBudget("5m") Cache(func() { AfterSystem() // cache the system prompt AfterTools() // cache tool definitions (Claude only) }) }) }) ``` -------------------------------- ### Map Array Payload to Query String Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Maps an array of strings payload to a repeated query string parameter. Example: GET /?filter=a&filter=b maps to List([]string{"a", "b"}). ```go // Array in query string Method("list", func() { Payload(ArrayOf(String)) HTTP(func() { GET("") Param("filter") }) }) // GET /?filter=a&filter=b → List([]string{"a", "b"}) ``` -------------------------------- ### Set up HTTP and gRPC Servers with Interceptors and Middleware Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/interceptors.md This Go code snippet illustrates the setup of a service with Goa interceptors, HTTP middleware, and gRPC interceptors. It demonstrates creating a service, configuring HTTP and gRPC servers, and mounting endpoints. Ensure all necessary imports are present for these components. ```go func main() { // 1. Create service with Goa interceptors svc := NewService() interceptors := NewInterceptors(log.Default()) endpoints := NewEndpoints(svc, interceptors) // 2. Set up HTTP with middleware mux := goahttp.NewMuxer() mux.Use(otelhttp.NewMiddleware("payment-svc")) mux.Use(debug.HTTP()) mux.Use(log.HTTP(ctx)) httpServer := genhttp.New(endpoints, mux, dec, enc, eh, eh) genhttp.Mount(mux, httpServer) // 3. Set up gRPC with interceptors grpcServer := grpc.NewServer( grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( grpc_recovery.UnaryServerInterceptor(), grpc_prometheus.UnaryServerInterceptor, )), ) grpcSvr := gengrpc.New(endpoints, nil) genpb.RegisterPaymentServer(grpcServer, grpcSvr) } ``` -------------------------------- ### gRPC Server Implementation Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/grpc-guide.md Set up a gRPC server using Goa's generated code. This example demonstrates initializing the service, endpoints, gRPC server, and listening for incoming connections. Ensure all necessary packages are imported. ```go package main import ( "log" "net" "google.golang.org/grpc" "github.com/yourusername/calc" gencalc "github.com/yourusername/calc/gen/calc" genpb "github.com/yourusername/calc/gen/grpc/calc/pb" gengrpc "github.com/yourusername/calc/gen/grpc/calc/server" ) func main() { svc := calc.New() endpoints := gencalc.NewEndpoints(svc) svr := grpc.NewServer() gensvr := gengrpc.New(endpoints, nil) genpb.RegisterCalcServer(svr, gensvr) lis, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } log.Println("gRPC server listening on :8080") svr.Serve(lis) } ``` -------------------------------- ### Run Documentation with Docker Source: https://github.com/goadesign/goa.design/blob/main/README.md This command sequence sets up and runs the documentation site using Docker. It mounts the current directory, exposes port 1313, and installs Node.js within the container to serve the site. Ensure you are in the `goa.design` directory before running. ```bash cd goa.design; docker run --name goadocs --volume .:/go/src/app -p 1313:1313 -e BIND=0.0.0.0 -it golang:latest bash; # in the container: curl -fsSL https://deb.nodesource.com/setup_26.x | bash -; apt install -y nodejs; cd /go/src/app; make prereqs; make start; ``` -------------------------------- ### Basic Static File Serving with Goa Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Demonstrates serving a directory, a specific file, and an index file for the root path using the `Files` DSL. Ensure the paths provided are relative to the project root. ```go var _ = Service("web", func() { // Serve a directory Files("/static/{*path}", "./public/static") // Serve a specific file Files("/favicon.ico", "./public/favicon.ico") // Serve index.html for root Files("/", "./public/index.html") }) ``` -------------------------------- ### Call Agent from Code Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/quickstart.md Demonstrates how to initialize a runtime, create a session, and interact with an AI agent using its generated client. Use `Run` for conversational flows and `OneShotRun` for request/response jobs. ```go rt, cleanup, err := bootstrap.New(ctx) if err != nil { log.Fatal(err) } defert cleanup() if _, err := rt.CreateSession(ctx, "session-1"); err != nil { log.Fatal(err) } client := chat.NewClient(rt) out, err := client.Run(ctx, "session-1", []*model.Message{{ Role: model.ConversationRoleUser, Parts: []model.Part{model.TextPart{Text: "Hello"}}, }}) if err != nil { log.Fatal(err) } fmt.Println(out.RunID) out, err = client.OneShotRun(ctx, []*model.Message{{ Role: model.ConversationRoleUser, Parts: []model.Part{model.TextPart{Text: "Summarize this document"}}, }}) if err != nil { log.Fatal(err) } fmt.Println(out.RunID) ``` -------------------------------- ### Endpoint Middleware Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md An example of a logging middleware that can be applied to Goa endpoints. Middleware intercepts requests and responses for cross-cutting concerns. ```go func LoggingMiddleware(next goa.Endpoint) goa.Endpoint { return func(ctx context.Context, req any) (res any, err error) { log.Printf("request: %v", req) res, err = next(ctx, req) log.Printf("response: %v", res) return } } endpoints.Use(LoggingMiddleware) ``` -------------------------------- ### Example: System Delivers to Person Relationship Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Example of defining a relationship where a notification system delivers order updates to a customer via email. ```go NotificationSystem.Delivers(Customer, "Sends order updates to", "Email") ``` -------------------------------- ### Registry Store Implementations Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/registry.md Shows how to initialize the registry with either the default in-memory store or a production-ready MongoDB store. Health state and stream coordination always use Redis/Pulse. ```go import ( "goa.design/goa-ai/registry/store/memory" "goa.design/goa-ai/registry/store/mongo" ) // In-memory store (default, for development) reg, _ := registry.New(ctx, registry.Config{ Redis: rdb, // Store defaults to memory.New() }) // MongoDB store (for production persistence) mongoStore, _ := mongo.New(mongoClient, "registry", "toolsets") reg, _ := registry.New(ctx, registry.Config{ Redis: rdb, Store: mongoStore, }) ``` -------------------------------- ### Example: System Uses System Relationship Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Example of defining a synchronous relationship where one system processes payments via a bank API. ```go PaymentSystem.Uses(BankAPI, "Processes payments via", "REST/JSON", Synchronous) ``` -------------------------------- ### Example: Container Uses External System Relationship Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Example of defining an asynchronous relationship where an API charges cards using an external Stripe API. ```go API.Uses("Stripe/API", "Charges cards", "HTTPS", Asynchronous) ``` -------------------------------- ### Sessionless One-Shot Run Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/runtime.md This example demonstrates how to perform durable, sessionless runs using `StartOneShot` and `OneShotRun`. It's suitable for tasks not attached to an existing session, returning a `WorkflowHandle` for further waiting or direct output retrieval. ```go client := chat.NewClient(rt) handle, err := client.StartOneShot(ctx, msgs, runtime.WithRunID("run-123"), runtime.WithLabels(map[string]string{"tenant": "acme"}), ) if err != nil { panic(err) } out, err := handle.Wait(ctx) if err != nil { panic(err) } fmt.Println(out.RunID) ``` -------------------------------- ### Client-Only Runtime Setup Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/runtime.md Use this snippet to construct a runtime with a client-capable engine for processes that only submit runs. It initializes the engine and creates a chat client without registering agents. ```go rt := runtime.New(runtime.WithEngine(temporalClient)) // engine client // No agent registration needed in a caller-only process client := chat.NewClient(rt) if _, err := rt.CreateSession(ctx, "s1"); err != nil { panic(err) } out, err := client.Run(ctx, "s1", msgs) ``` -------------------------------- ### Goa HTTP Server Implementation Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Sets up a new HTTP server with provided endpoints, muxer, decoders, encoders, and error handlers. The Server type exposes handlers for modification and can apply middleware. ```go func New( e *calc.Endpoints, mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder, encoder func(context.Context, http.ResponseWriter) goahttp.Encoder, errhandler func(context.Context, http.ResponseWriter, error), formatter func(ctx context.Context, err error) goahttp.Statuser, ) *Server // Server exposes handlers for modification type Server struct { Mounts []*MountPoint Add http.Handler Multiply http.Handler } // Use applies HTTP middleware to all handlers func (s *Server) Use(m func(http.Handler) http.Handler) ``` ```go func main() { svc := calc.New() endpoints := gencalc.NewEndpoints(svc) mux := goahttp.NewMuxer() server := genhttp.New( endpoints, mux, goahttp.RequestDecoder, goahttp.ResponseEncoder, nil, nil) genhttp.Mount(mux, server) http.ListenAndServe(":8080", mux) } ``` -------------------------------- ### Executor Example Implementation Source: https://github.com/goadesign/goa.design/blob/main/content/it/docs/2-goa-ai/toolsets.md An example of an executor function that decides how to run a tool and handles different tool calls. It includes argument unmarshalling, optional transformations, client calls, and error handling. ```go func Execute(ctx context.Context, meta *runtime.ToolCallMeta, call *planner.ToolRequest) (*runtime.ToolExecutionResult, error) { switch call.Name { case "orchestrator.profiles.upsert": args, err := profilesspecs.UnmarshalUpsertPayload(call.Payload) if err != nil { return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.NewToolError("invalid payload"), }), nil } // Trasformazioni opzionali se emesse da codegen mp, _ := profilesspecs.ToMethodPayload_Upsert(args) methodRes, err := client.Upsert(ctx, mp) if err != nil { return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.ToolErrorFromError(err), }), nil } tr, _ := profilesspecs.ToToolReturn_Upsert(methodRes) return runtime.Executed(&planner.ToolResult{ Name: call.Name, Result: tr, }), nil default: return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.NewToolError("unknown tool"), }), nil } } ``` -------------------------------- ### Initialize Clue and OpenTelemetry Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/production.md Sets up the logger, OpenTelemetry exporters for tracing and metrics, and initializes Clue configuration. Ensure collector address and credentials are correctly configured. ```go import ( "goa.design/clue/clue" "goa.design/clue/log" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" ) func main() { // 1. Create logger format := log.FormatJSON if log.IsTerminal() { format = log.FormatTerminal } ctx := log.Context(context.Background(), log.WithFormat(format), log.WithFunc(log.Span)) // 2. Configure OpenTelemetry exporters spanExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithEndpoint(*collectorAddr), otlptracegrpc.WithTLSCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf(ctx, err, "failed to initialize tracing") } metricExporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithEndpoint(*collectorAddr), otlpmetricgrpc.WithTLSCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf(ctx, err, "failed to initialize metrics") } // 3. Initialize Clue cfg, err := clue.NewConfig(ctx, genservice.ServiceName, genservice.APIVersion, metricExporter, spanExporter) clue.ConfigureOpenTelemetry(ctx, cfg) } ``` -------------------------------- ### Executor Example for Tool Execution Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/toolsets.md Implement the ToolCallExecutor interface to define how specific tool calls are executed. This example handles 'orchestrator.profiles.upsert' and includes argument unmarshalling, client invocation, and result transformation. ```go func Execute(ctx context.Context, meta *runtime.ToolCallMeta, call *planner.ToolRequest) (*runtime.ToolExecutionResult, error) { switch call.Name { case "orchestrator.profiles.upsert": args, err := profilesspecs.UnmarshalUpsertPayload(call.Payload) if err != nil { return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.NewToolError("invalid payload"), }), nil } // Optional transforms if emitted by codegen mp, _ := profilesspecs.ToMethodPayload_Upsert(args) methodRes, err := client.Upsert(ctx, mp) if err != nil { return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.ToolErrorFromError(err), }), nil } tr, _ := profilesspecs.ToToolReturn_Upsert(methodRes) return runtime.Executed(&planner.ToolResult{ Name: call.Name, Result: tr, }), nil default: return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.NewToolError("unknown tool"), }), nil } } ``` -------------------------------- ### Goa HTTP Client Implementation Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Constructs a new HTTP client with specified scheme, host, and transport options. It then creates a Goa client using the HTTP client's service methods. ```go func NewClient( scheme string, host string, doer goahttp.Doer, enc func(*http.Request) goahttp.Encoder, dec func(*http.Response) goahttp.Decoder, restoreBody bool, ) *Client ``` ```go func main() { httpClient := genclient.NewClient( "http", "localhost:8080", http.DefaultClient, goahttp.RequestEncoder, goahttp.ResponseDecoder, false, ) client := gencalc.NewClient( httpClient.Add(), httpClient.Multiply(), ) result, err := client.Add(context.Background(), &gencalc.AddPayload{A: 1, B: 2}) ``` -------------------------------- ### Import and Reference Shared Infrastructure Components Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/model.md Demonstrates how to import shared infrastructure components from other packages and reference them within your service model. ```go // shared/infrastructure.go package shared import . "goa.design/model/dsl" var Stripe = SoftwareSystem("Stripe", "Payment processing", func() { External() Tag("external", "payments") }) ``` ```go // myservice/model.go package model import ( . "goa.design/model/dsl" _ "mycompany/shared" // Import shared elements ) var _ = Design("My Service", func() { var Service = SoftwareSystem("My Service", func() { Uses("Stripe", "Processes payments via") // Reference by name }) }) ``` -------------------------------- ### Goa gRPC Client Implementation Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md Establishes a gRPC connection to localhost:8080 using insecure credentials, creates a gRPC client, and then initializes a Goa client for the Calc service. ```go func main() { conn, _ := grpc.Dial("localhost:8080", grpc.WithTransportCredentials(insecure.NewCredentials())) defer conn.Close() grpcClient := genclient.NewClient(conn) client := gencalc.NewClient( grpcClient.Add(), grpcClient.Multiply(), ) result, _ := client.Add(context.Background(), &gencalc.AddPayload{A: 1, B: 2}) ``` -------------------------------- ### Implement and Add a Job Handler Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/3-ecosystem/pulse.md Defines a worker handler by implementing Start and Stop methods. The Start method unmarshals the job payload and performs the work. Attach the handler to a node to process jobs. ```go // Worker implementation: decode strongly-typed jobs from []byte payloads. type EmailJobHandler struct{} func (h *EmailJobHandler) Start(job *pool.Job) error { var payload EmailJob if err := json.Unmarshal(job.Payload, &payload); err != nil { return err } return sendEmail(payload.Email) } func (h *EmailJobHandler) Stop(key string) error { // Optional: clean up resources for the given job key. return nil } // Attach the handler to a worker in the pool. _, err := node.AddWorker(ctx, &EmailJobHandler{}) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Return RetryHint for Invalid Payload Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/testing.md When an invalid payload error occurs, return a RetryHint from the executor to allow the planner to self-correct. This example shows how to return a ToolResult with a RetryHint indicating invalid arguments and providing an example input. ```go if err != nil { return runtime.Executed(&planner.ToolResult{ Name: call.Name, Error: planner.NewToolError("invalid payload"), RetryHint: &planner.RetryHint{ Reason: planner.RetryReasonInvalidArguments, Tool: call.Name, ExampleInput: map[string]any{"query": "example", "limit": 10}, Message: "limit must be an integer", }, }), nil } ``` -------------------------------- ### Goa Server Interceptor Example Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/interceptors.md An example of a Goa server interceptor that enriches the result with processing time and sets a processed timestamp. It uses `info.Result(res)` for type-safe access and `next(ctx, info.RawPayload())` to continue the chain. ```go type Interceptors struct{} func (i *Interceptors) RequestAudit(ctx context.Context, info *RequestAuditInfo, next goa.Endpoint) (any, error) { start := time.Now() res, err := next(ctx, info.RawPayload()) if err != nil { return nil, err } r := info.Result(res) r.SetProcessedAt(time.Now().UTC().Format(time.RFC3339Nano)) r.SetDuration(int(time.Since(start).Milliseconds())) return res, nil } ``` -------------------------------- ### Register Chat Agent and Run Session Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/runtime.md Demonstrates how to initialize the runtime, register a chat agent, create a session, and run a chat interaction. The in-memory engine is used by default. ```go package main import ( "context" chat "example.com/assistant/gen/orchestrator/agents/chat" "goa.design/goa-ai/runtime/agent/model" "goa.design/goa-ai/runtime/agent/runtime" ) func main() { // In-memory engine is the default; pass WithEngine for Temporal or custom engines. rt := runtime.New() ctx := context.Background() err := chat.RegisterChatAgent(ctx, rt, chat.ChatAgentConfig{Planner: newChatPlanner()}) if err != nil { panic(err) } // Sessions are first-class: create a session before starting runs under it. if _, err := rt.CreateSession(ctx, "session-1"); err != nil { panic(err) } client := chat.NewClient(rt) out, err := client.Run(ctx, "session-1", []*model.Message{{ Role: model.ConversationRoleUser, Parts: []model.Part{model.TextPart{Text: "Summarize the latest status."}}, }}) if err != nil { panic(err) } // Use out.RunID, out.Final (the assistant message), etc. } ``` -------------------------------- ### Configure Pulse Sink for Production Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/2-goa-ai/production.md Set up a Pulse sink for publishing events to a shared bus in production environments. This example shows how to initialize the Pulse client and configure the sink, including custom stream naming. ```go pulseClient := pulse.NewClient(redisClient) s, err := pulseSink.NewSink(pulseSink.Options{ Client: pulseClient, // Optional: override stream naming (defaults to `session/`). StreamID: func(ev stream.Event) (string, error) { if ev.SessionID() == "" { return "", errors.New("missing session id") } return fmt.Sprintf("session/%s", ev.SessionID()), nil }, }) if err != nil { log.Fatal(err) } rt := runtime.New( runtime.WithEngine(eng), runtime.WithStream(s), ) ``` -------------------------------- ### Goa Version Command Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/code-generation.md A simple command to display the installed version of the Goa CLI. ```bash goa version ``` -------------------------------- ### Result Types Examples Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Illustrates defining simple and structured result types for methods. ```APIDOC ### Result Types ```go // Simple result Method("count", func() { Result(Int64) }) // Structured result Method("search", func() { Result(func() { Field(1, "items", ArrayOf(User), "Matching users") Field(2, "total", Int64, "Total count") Required("items", "total") }) }) ``` ``` -------------------------------- ### Streaming Methods Examples Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Shows how to define methods that involve streaming payloads and/or results. ```APIDOC ### Streaming Methods ```go Method("streamNumbers", func() { Description("Stream a sequence of numbers") StreamingPayload(Int32) StreamingResult(Int32) }) Method("processEvents", func() { StreamingPayload(func() { Field(1, "event_type", String) Field(2, "data", Any) Required("event_type", "data") }) Result(func() { Field(1, "processed", Int64) Field(2, "errors", Int64) Required("processed", "errors") }) }) ``` ``` -------------------------------- ### Payload Types Examples Source: https://github.com/goadesign/goa.design/blob/main/content/en/docs/1-goa/dsl-reference.md Demonstrates defining simple, structured, and referenced payload types for methods. ```APIDOC ### Payload Types ```go // Simple payload Method("getUser", func() { Payload(String, "User ID") Result(User) }) // Structured payload Method("createUser", func() { Payload(func() { Field(1, "name", String, "User's full name") Field(2, "email", String, "Email address", func() { Format(FormatEmail) }) Field(3, "role", String, "User role", func() { Enum("admin", "user", "guest") }) Required("name", "email", "role") }) Result(User) }) // Reference to predefined type Method("updateUser", func() { Payload(UpdateUserPayload) Result(User) }) ``` ```