Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Add DockerAgent example and fix planner loop (#276)

anj-s62cc24e21a83
diff --git a/examples/docker_agent/main.go b/examples/docker_agent/main.go
new file mode 100644
index 0000000..8b72e80
--- /dev/null
+++ b/examples/docker_agent/main.go
@@ -0,0 +1,273 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "os"
+
+ "google.golang.org/genai"
+ "google.golang.org/grpc"
+
+ "github.com/google/ax/internal/skills"
+ "github.com/google/ax/proto"
+ "github.com/google/uuid"
+)
+
+const port = ":50052"
+
+type server struct {
+ proto.UnimplementedAgentServiceServer
+ genaiClient *genai.Client
+ skillsExecutor *skills.Executor
+}
+
+func (s *server) Connect(stream grpc.BidiStreamingServer[proto.AgentMessage, proto.AgentMessage]) error {
+ incoming, err := stream.Recv()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+
+ start := incoming.GetStart()
+ if start == nil {
+ return errors.New("missing start message")
+ }
+
+ contents := protoToContents(start.Messages)
+
+ for {
+ model := os.Getenv("AX_GEMINI_MODEL")
+ if model == "" {
+ model = "gemini-3-flash-preview"
+ }
+ resp, err := s.genaiClient.Models.GenerateContent(stream.Context(), model, contents, &genai.GenerateContentConfig{
+ SystemInstruction: genai.Text("You are DockerAgent, an agent specialized in writing Dockerfiles. Use the docker-writer skill to fulfill requests. Keep responses concise.")[0],
+ Tools: []*genai.Tool{skills.BuildTool(s.skillsExecutor.SkillNames())},
+ })
+ if err != nil {
+ return fmt.Errorf("failed to generate content: %w", err)
+ }
+
+ if len(resp.Candidates) == 0 {
+ return errors.New("no candidates from Gemini")
+ }
+ candidate := resp.Candidates[0]
+
+ var keepLooping bool
+ var functionCall *genai.FunctionCall
+ var thoughtSignature []byte
+
+ for _, part := range candidate.Content.Parts {
+ if part.FunctionCall != nil {
+ functionCall = part.FunctionCall
+ thoughtSignature = part.ThoughtSignature
+ break
+ }
+ }
+
+ if functionCall != nil {
+ if functionCall.ID == "" {
+ functionCall.ID = uuid.NewString()
+ }
+
+ // Handle skill call
+ result, err := s.skillsExecutor.HandleCall(stream.Context(), functionCall)
+ if err != nil {
+ return fmt.Errorf("failed to handle skill call: %w", err)
+ }
+
+ // Append function call and response to history
+ contents = append(contents, &genai.Content{
+ Role: "model",
+ Parts: []*genai.Part{{
+ FunctionCall: functionCall,
+ ThoughtSignature: thoughtSignature,
+ }},
+ })
+ contents = append(contents, &genai.Content{
+ Role: "user",
+ Parts: []*genai.Part{{
+ FunctionResponse: &genai.FunctionResponse{
+ ID: functionCall.ID,
+ Name: functionCall.Name,
+ Response: map[string]any{"result": result.Stdout},
+ },
+ }},
+ })
+
+ if functionCall.Name == "activate_skill" {
+ keepLooping = true
+ }
+ }
+
+ if !keepLooping {
+ // Send final text output if any
+ for _, part := range candidate.Content.Parts {
+ if part.Text != "" {
+ responseMsg := &proto.Message{
+ Role: "assistant",
+ Content: &proto.Content{
+ Type: &proto.Content_Text{
+ Text: &proto.TextContent{Text: "[DockerAgent] " + part.Text},
+ },
+ },
+ }
+ if err := stream.Send(&proto.AgentMessage{
+ ConversationId: incoming.ConversationId,
+ ExecId: incoming.ExecId,
+ Type: &proto.AgentMessage_Outputs{
+ Outputs: &proto.AgentOutputs{
+ Messages: []*proto.Message{responseMsg},
+ },
+ },
+ }); err != nil {
+ return err
+ }
+ }
+ }
+ break
+ }
+ }
+
+ fmt.Println("DockerAgent finished execution turn.")
+
+ // Send AgentEnd
+ return stream.Send(&proto.AgentMessage{
+ ConversationId: incoming.ConversationId,
+ ExecId: incoming.ExecId,
+ Type: &proto.AgentMessage_End{
+ End: &proto.AgentEnd{},
+ },
+ })
+}
+// protoToContents converts history to Gemini conversation format.
+func protoToContents(inputs []*proto.Message) []*genai.Content {
+ var contents []*genai.Content
+ for _, msg := range inputs {
+ if msg.GetInternalOnly() {
+ continue
+ }
+ role := msg.Role
+ if role != "user" {
+ role = "model"
+ }
+
+ content := msg.GetContent()
+ if content == nil {
+ continue
+ }
+
+ switch m := content.Type.(type) {
+ case *proto.Content_Text:
+ contents = append(contents, &genai.Content{
+ Role: role,
+ Parts: []*genai.Part{
+ {
+ Text: m.Text.Text,
+ },
+ },
+ })
+ case *proto.Content_Confirmation:
+ // shouldn't be sent to Gemini
+ switch m.Confirmation.Decision.(type) {
+ case *proto.ConfirmationContent_Decline:
+ // shouldn't be sent to Gemini
+ case *proto.ConfirmationContent_Approval:
+ // shouldn't be sent to Gemini
+ }
+ case *proto.Content_ToolCall:
+ tc := m.ToolCall
+ if fc := tc.GetFunctionCall(); fc != nil {
+ contents = append(contents, &genai.Content{
+ Role: "model",
+ Parts: []*genai.Part{
+ {
+ ThoughtSignature: tc.Signature,
+ FunctionCall: &genai.FunctionCall{
+ ID: tc.Id,
+ Name: fc.Name,
+ Args: fc.Arguments.AsMap(),
+ },
+ },
+ },
+ })
+ }
+ case *proto.Content_ToolResult:
+ tr := m.ToolResult
+ if fr := tr.GetFunctionResult(); fr != nil {
+ var respMap map[string]any
+ if fr.GetResponse() != nil {
+ respMap = fr.GetResponse().AsMap()
+ }
+ contents = append(contents, &genai.Content{
+ Role: "user",
+ Parts: []*genai.Part{
+ {
+ FunctionResponse: &genai.FunctionResponse{
+ ID: tr.CallId,
+ Name: fr.Name,
+ Response: respMap,
+ },
+ },
+ },
+ })
+ }
+ }
+ }
+ return contents
+}
+
+func (s *server) HealthCheck(ctx context.Context, req *proto.HealthCheckRequest) (*proto.HealthCheckResponse, error) {
+ return &proto.HealthCheckResponse{
+ Healthy: true,
+ Message: "DockerAgent is healthy",
+ }, nil
+}
+
+func main() {
+ ctx := context.Background()
+ client, err := genai.NewClient(ctx, &genai.ClientConfig{})
+ if err != nil {
+ log.Fatalf("Failed to create GenAI client: %v", err)
+ }
+
+ // Create skills executor pointing to the local skills directory
+ skillsExecutor, err := skills.NewExecutor("./examples/docker_agent/skills")
+ if err != nil {
+ log.Fatalf("Failed to create skills executor: %v", err)
+ }
+
+ fmt.Printf("Listening on port: %s\n", port)
+ lis, err := net.Listen("tcp", port)
+ if err != nil {
+ log.Fatalf("Failed to listen: %v", err)
+ }
+
+ grpcServer := grpc.NewServer()
+ proto.RegisterAgentServiceServer(grpcServer, &server{genaiClient: client, skillsExecutor: skillsExecutor})
+
+ fmt.Println("\nDockerAgent server is running...")
+ if err := grpcServer.Serve(lis); err != nil {
+ log.Fatalf("Failed to serve: %v", err)
+ }
+}
diff --git a/examples/docker_agent/run_docker_agent.sh b/examples/docker_agent/run_docker_agent.sh
new file mode 100755
index 0000000..2deed4a
--- /dev/null
+++ b/examples/docker_agent/run_docker_agent.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Exit immediately if a command exits with a non-zero status
+set -e
+
+# Function to cleanup background processes
+cleanup() {
+ echo "Cleaning up background processes..."
+ jobs -p | xargs -I {} kill {} 2>/dev/null || true
+}
+trap cleanup EXIT
+
+echo "Cleaning up port 50052 if in use..."
+kill -9 $(lsof -t -i:50052) 2>/dev/null || true
+
+echo "Starting DockerAgent in background..."
+go run examples/docker_agent/main.go &
+
+echo "Waiting for agent to be ready..."
+sleep 3
+
+echo "Running test client..."
+go run examples/docker_agent/test/test_docker_agent.go
diff --git a/examples/docker_agent/run_e2e.sh b/examples/docker_agent/run_e2e.sh
new file mode 100755
index 0000000..60439fa
--- /dev/null
+++ b/examples/docker_agent/run_e2e.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Exit immediately if a command exits with a non-zero status
+set -e
+
+# Function to cleanup background processes
+cleanup() {
+ echo "Cleaning up background processes..."
+ jobs -p | xargs -I {} kill {} 2>/dev/null || true
+}
+trap cleanup EXIT
+
+echo "Cleaning up port 50052 if in use..."
+kill -9 $(lsof -t -i:50052) 2>/dev/null || true
+
+echo "Starting DockerAgent in background..."
+go run examples/docker_agent/main.go &
+AGENT_PID=$!
+
+echo "Starting AX Server in background..."
+ax serve &
+SERVER_PID=$!
+
+# Give servers a few seconds to start up
+echo "Waiting for servers to be ready..."
+for i in {1..30}; do
+ if (echo > /dev/tcp/localhost/50052) >/dev/null 2>&1 && (echo > /dev/tcp/localhost/8494) >/dev/null 2>&1; then
+ echo "Servers are ready!"
+ break
+ fi
+ echo "Waiting..."
+ sleep 1
+done
+
+echo "Registering DockerAgent..."
+ax register \
+ --agent-id DockerAgent \
+ --agent-addr localhost:50052 \
+ --agent-name "Docker Agent" \
+ --agent-description "Agent specialized in generating Dockerfiles. Call this agent whenever the user request involves creating, writing, or generating a Dockerfile."
+
+echo "Executing task..."
+ax exec --server localhost:8494 --input "Write a Dockerfile for a Python flask app that says hello world."
+
+# Wait for the exec command to finish
+# The trap will kill the background servers when the script exits
diff --git a/examples/docker_agent/skills/docker-writer/SKILL.md b/examples/docker_agent/skills/docker-writer/SKILL.md
new file mode 100644
index 0000000..1d8df18
--- /dev/null
+++ b/examples/docker_agent/skills/docker-writer/SKILL.md
@@ -0,0 +1,13 @@
+---
+name: docker-writer
+description: Skill for writing Dockerfiles based on user requirements.
+---
+
+# Instructions
+You are the Docker Writer skill. Your job is to generate a Dockerfile directly in the response.
+
+**IMPORTANT**: There are no scripts in this skill's directory. Do NOT attempt to call `run_skill_script`. Just generate the Dockerfile content directly as text in your response.
+
+1. Analyze the user's request for language, dependencies, and environment.
+2. Generate a well-commented Dockerfile.
+3. Output the Dockerfile content directly.
diff --git a/examples/docker_agent/test/test_docker_agent.go b/examples/docker_agent/test/test_docker_agent.go
new file mode 100644
index 0000000..c6c5dfb
--- /dev/null
+++ b/examples/docker_agent/test/test_docker_agent.go
@@ -0,0 +1,86 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ "github.com/google/ax/proto"
+)
+
+func main() {
+ fmt.Println("Connecting to DockerAgent at localhost:50052...")
+ conn, err := grpc.NewClient("localhost:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ log.Fatalf("Failed to connect: %v", err)
+ }
+ defer conn.Close()
+
+ client := proto.NewAgentServiceClient(conn)
+ stream, err := client.Connect(context.Background())
+ if err != nil {
+ log.Fatalf("Failed to open stream: %v", err)
+ }
+
+ fmt.Println("Sending request to write a Dockerfile...")
+ // Send start message
+ err = stream.Send(&proto.AgentMessage{
+ ConversationId: "test-conversation-id",
+ ExecId: "test-exec-id",
+ Type: &proto.AgentMessage_Start{
+ Start: &proto.AgentStart{
+ AgentId: "DockerAgent",
+ Messages: []*proto.Message{
+ {
+ Role: "user",
+ Content: &proto.Content{
+ Type: &proto.Content_Text{
+ Text: &proto.TextContent{Text: "Write a Dockerfile for a simple Node.js app."},
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ if err != nil {
+ log.Fatalf("Failed to send message: %v", err)
+ }
+
+ fmt.Println("Waiting for response...")
+ // Read responses
+ for {
+ resp, err := stream.Recv()
+ if err != nil {
+ log.Fatalf("Error receiving: %v", err)
+ }
+ if resp.GetEnd() != nil {
+ fmt.Println("\n\n[Agent finished]")
+ break
+ }
+ if outputs := resp.GetOutputs(); outputs != nil {
+ for _, m := range outputs.Messages {
+ if txt := m.GetContent().GetText(); txt != nil {
+ fmt.Print(txt.Text)
+ }
+ }
+ }
+ }
+}
diff --git a/internal/gemini/gemini_planner.go b/internal/gemini/gemini_planner.go
index b412c01..49a2bd5 100644
--- a/internal/gemini/gemini_planner.go
+++ b/internal/gemini/gemini_planner.go
@@ -67,24 +67,17 @@ func NewGeminiPlannerAgent(ctx context.Context, registry AgentRegistry, cfg Gemi
// Default system prompt
if cfg.GeminiConfig.SystemPrompt == "" {
- cfg.GeminiConfig.SystemPrompt = `You are an intelligent orchestrator. Your role is to analyze the conversation history and user requests, then select the most appropriate agent to handle the task.
-
-Available tools have been provided to you as function tools. Each agent has:
-- A unique ID
-- A description of its capabilities
-
-Your job is to:
-1. Analyze the current conversation context and understand what needs to be done
-2. Select the best tool for the task by calling the appropriate function
-3. If enough work is done, stop to indicate completion
-
-Guidelines:
-- Choose tools based on their capabilities and the user's needs.
-- Keep responses concise, don't chat too much about what you can do.
-- If no suitable tool exists, stop.
-- Keep the conversation context in mind when selecting tools.
-- It's valid not to choose a tool.
-- Once something is approved, try executing it.`
+ cfg.GeminiConfig.SystemPrompt = `You are the Primary Architect and Executor Agent in the AX system. Your goal is to solve the user's request as thoroughly and efficiently as possible.
+
+You have two primary ways to accomplish tasks:
+1. **Direct Execution**: You have access to a 'bash' tool to run shell commands on the system. Use this to perform work directly (e.g., creating files, running tests, searching).
+2. **Delegation**: You have access to specialized subagents (registered as function tools). Review their descriptions and delegate tasks to them if they are better suited for the job.
+
+Rules for Operation:
+- **MANDATORY FIRST STEP**: You MUST first check if any available subagent is specialized for the user's request. If a specialized subagent exists, you MUST call that subagent. Do not attempt the task yourself if a subagent can handle it.
+- If no subagent is specialized, you must attempt to solve the task yourself using the 'bash' tool. Do not give up; use commands to explore, create, and verify.
+- **Clarification**: If the user's request is ambiguous or you are unclear about any requirements, stop and ask the user for clarification before proceeding with any tool calls or delegation.
+- Always be concise. Focus on action and execution results rather than conversational explanations.`
}
client, err := genai.NewClient(ctx, &genai.ClientConfig{})
@@ -149,7 +142,7 @@ func (p *geminiPlannerAgent) loop(ctx context.Context, conversationID string, st
Messages: append(start.Messages, outputs...),
}
outputs = nil
- if _, err := e.Exec(ctx, conversationID, nextAgentID, start, handler); err != nil {
+ if _, err := e.Exec(ctx, conversationID, nextAgentID, start, outputCapturer); err != nil {
return err
}
}