micro--go-micro
1bc886fa82
* docs: Agent interface design sketch Proposes Agent as a top-level abstraction alongside Service in the micro package. Agent manages services — scoped tools, system prompt, conversation memory, registry-discoverable. Design only, no implementation. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: Agent as a first-class abstraction Introduce micro.NewAgent() alongside micro.New() — Agent is to intelligence what Service is to capability. Agent interface: - Chat(ctx, message) (*Response, error) — core interaction method - Run() — registers in registry, subscribes to broker, blocks - Stop() — graceful shutdown - Scoped tools — only sees endpoints of its assigned services - Persistent memory — conversation history stored in store - Agent-to-agent — communication via broker topics Top-level API: agent := micro.NewAgent("task-mgr", micro.AgentServices("task"), micro.AgentPrompt("You manage tasks."), micro.AgentProvider("anthropic"), ) agent.Run() https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: wire agents into chat router, add micro agent CLI, expose Flow Three top-level abstractions: micro.New("task") — Service (capability) micro.NewAgent("task-mgr") — Agent (intelligence) micro.NewFlow("onboard-user") — Flow (event-driven orchestration) micro chat as router: - Discovers agents from registry on startup - Single agent: routes directly - Multiple agents: LLM classifies intent, dispatches to right agent via route_to_agent tool - No agents: falls back to current direct-service behaviour - Banner shows discovered agents micro agent CLI: - micro agent list — shows registered agents and their services - micro agent describe <name> — shows agent details from registry https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: move flow to top level, update docs for three abstractions Package structure now consistent: service/ — Service (capability) agent/ — Agent (intelligence) flow/ — Flow (event-driven orchestration) ai/flow/ kept as backward-compatible re-export. Updated across all surfaces: - CLAUDE.md: added agent/ and flow/ to project structure - README: added "Building Agents" section with NewAgent() examples, updated features table (Agents, Flows, Chat router), CLI table (agent list, agent describe), docs links - Website: features grid shows Services, Agents, Flows as the three pillars alongside generation, MCP, and pluggable architecture - micro.go: Flow imported from top-level flow/ package https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * docs: rewrite getting-started, fix ai-integration import paths Getting started now covers all three abstractions: - Service (write handlers, micro run, templates) - Agent (micro.NewAgent, scoped tools, memory, CLI) - Flow (event-driven LLM orchestration) Leads with prompt-based generation, then manual service creation. ai-integration.md: fixed flow import path from go-micro.dev/v5/ai/flow to go-micro.dev/v5/flow, updated stack diagram to show agent/flow/chat. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * blog: Introducing micro.NewAgent() Post 16 — announces Agent as a first-class abstraction. Shows the API (NewAgent, AgentServices, AgentPrompt, AgentProvider), scoped tools, persistent memory, multi-service agents, multi-agent systems, and the three-abstraction comparison table (Service/Agent/Flow). https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: fix agent registration, blog post 16 Agent registration: - Add node with address so mDNS can discover agents - Store type and services in node metadata (mDNS requirement) - Connect broker before subscribing, non-fatal if broker unavailable - Print registration confirmation on Run() Agent/chat discovery: - Check both service-level and node-level metadata for type=agent (mDNS stores metadata on nodes, not services) Blog post 16: "Introducing micro.NewAgent()" — announces the Agent abstraction with code examples, comparison table, multi-agent patterns. Tested end-to-end: micro run → micro agent list discovers the agent → micro chat routes to it → agent calls service endpoints. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: agents are proper services with RPC Chat endpoint Refactored agent to use server.Server instead of fake registry entries. An agent now: - Creates a real RPC server with server.Name(agentName) - Registers an Agent.Chat handler callable via standard RPC - Sets server metadata type=agent, services=x,y for discovery - No more fake addresses or broker hacks micro chat calls agents via RPC (client.Call) instead of creating local agent instances. The registry stays clean — agents are real services with real endpoints. Removed broker dependency from agent options. Agent-to-agent communication is just RPC like everything else. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: agent uses proto-defined RPC interface Added agent/proto/agent.proto with Agent service definition: rpc Chat(ChatRequest) returns (ChatResponse) Agent now implements the generated AgentHandler interface and registers via pb.RegisterAgentHandler. The Chat endpoint is a standard proto-based RPC callable by any go-micro client. Renamed the programmatic API from Chat() to Ask() to avoid collision with the proto handler method name. micro chat calls agents via standard RPC with JSON-encoded request/response — no special types needed on the caller side. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd * feat: generate agent alongside services, update all docs micro run --prompt now generates an agent binary that manages all the generated services. The agent reads MICRO_AI_PROVIDER and MICRO_AI_API_KEY from the environment. micro run propagates these when started with --prompt. Run banner shows services and agents separately. Updated README, getting-started guide, and landing page to show the complete flow: generate → services + agent start → micro chat routes to agent → agent orchestrates services. https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd --------- Co-authored-by: Claude <noreply@anthropic.com>
275 行
5.8 KiB
Go
275 行
5.8 KiB
Go
// Package agent provides the Agent abstraction for Go Micro.
|
|
//
|
|
// An Agent is a service with an LLM inside it. It registers a Chat
|
|
// RPC endpoint, discovers its assigned services' tools, and
|
|
// orchestrates them intelligently.
|
|
//
|
|
// agent := micro.NewAgent("task-mgr",
|
|
// micro.AgentServices("task"),
|
|
// micro.AgentPrompt("You manage tasks."),
|
|
// micro.AgentProvider("anthropic"),
|
|
// )
|
|
// agent.Run()
|
|
package agent
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
|
|
"go-micro.dev/v5/ai"
|
|
pb "go-micro.dev/v5/agent/proto"
|
|
"go-micro.dev/v5/server"
|
|
"go-micro.dev/v5/store"
|
|
|
|
_ "go-micro.dev/v5/ai/anthropic"
|
|
_ "go-micro.dev/v5/ai/atlascloud"
|
|
_ "go-micro.dev/v5/ai/gemini"
|
|
_ "go-micro.dev/v5/ai/groq"
|
|
_ "go-micro.dev/v5/ai/mistral"
|
|
_ "go-micro.dev/v5/ai/openai"
|
|
_ "go-micro.dev/v5/ai/together"
|
|
)
|
|
|
|
// Agent is the interface for an AI agent that manages services.
|
|
type Agent interface {
|
|
Name() string
|
|
Init(...Option)
|
|
Options() Options
|
|
Ask(ctx context.Context, message string) (*Response, error)
|
|
Run() error
|
|
Stop() error
|
|
String() string
|
|
}
|
|
|
|
// Response is what an agent returns from Chat.
|
|
type Response struct {
|
|
Reply string
|
|
ToolCalls []ai.ToolCall
|
|
Agent string
|
|
}
|
|
|
|
type agentImpl struct {
|
|
opts Options
|
|
model ai.Model
|
|
tools *ai.Tools
|
|
hist *ai.History
|
|
server server.Server
|
|
mu sync.Mutex
|
|
}
|
|
|
|
// New creates a new Agent.
|
|
func New(opts ...Option) Agent {
|
|
return &agentImpl{
|
|
opts: newOptions(opts...),
|
|
}
|
|
}
|
|
|
|
func (a *agentImpl) Name() string {
|
|
return a.opts.Name
|
|
}
|
|
|
|
func (a *agentImpl) Init(opts ...Option) {
|
|
for _, o := range opts {
|
|
o(&a.opts)
|
|
}
|
|
a.setup()
|
|
}
|
|
|
|
func (a *agentImpl) Options() Options {
|
|
return a.opts
|
|
}
|
|
|
|
func (a *agentImpl) String() string {
|
|
return "agent"
|
|
}
|
|
|
|
func (a *agentImpl) setup() {
|
|
var modelOpts []ai.Option
|
|
modelOpts = append(modelOpts, ai.WithAPIKey(a.opts.APIKey))
|
|
if a.opts.Model != "" {
|
|
modelOpts = append(modelOpts, ai.WithModel(a.opts.Model))
|
|
}
|
|
|
|
a.tools = ai.NewTools(a.opts.Registry, ai.ToolClient(a.opts.Client))
|
|
modelOpts = append(modelOpts, ai.WithToolHandler(a.tools.Handler()))
|
|
a.model = ai.New(a.opts.Provider, modelOpts...)
|
|
|
|
a.hist = ai.NewHistory(a.opts.HistoryLimit)
|
|
a.loadHistory()
|
|
}
|
|
|
|
// Ask sends a message and returns the agent's response.
|
|
// This is the programmatic API for direct use.
|
|
func (a *agentImpl) Ask(ctx context.Context, message string) (*Response, error) {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
|
|
if a.model == nil {
|
|
a.setup()
|
|
}
|
|
|
|
toolList, err := a.discoverTools()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("discover tools: %w", err)
|
|
}
|
|
|
|
a.hist.Add("user", message)
|
|
|
|
resp, err := a.model.Generate(ctx, &ai.Request{
|
|
Prompt: message,
|
|
SystemPrompt: a.buildPrompt(),
|
|
Tools: toolList,
|
|
Messages: a.hist.Messages(),
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.Reply != "" {
|
|
a.hist.Add("assistant", resp.Reply)
|
|
}
|
|
if resp.Answer != "" {
|
|
a.hist.Add("assistant", resp.Answer)
|
|
}
|
|
|
|
a.saveHistory()
|
|
|
|
reply := resp.Reply
|
|
if resp.Answer != "" {
|
|
if reply != "" {
|
|
reply += "\n\n"
|
|
}
|
|
reply += resp.Answer
|
|
}
|
|
|
|
return &Response{
|
|
Reply: reply,
|
|
ToolCalls: resp.ToolCalls,
|
|
Agent: a.opts.Name,
|
|
}, nil
|
|
}
|
|
|
|
// Chat implements the proto AgentHandler interface for RPC.
|
|
// @example {"message": "What tasks are overdue?"}
|
|
func (a *agentImpl) Chat(ctx context.Context, req *pb.ChatRequest, rsp *pb.ChatResponse) error {
|
|
resp, err := a.Ask(ctx, req.Message)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rsp.Reply = resp.Reply
|
|
rsp.Agent = resp.Agent
|
|
for _, tc := range resp.ToolCalls {
|
|
input, _ := json.Marshal(tc.Input)
|
|
rsp.ToolCalls = append(rsp.ToolCalls, &pb.ToolCall{
|
|
Id: tc.ID,
|
|
Name: tc.Name,
|
|
Input: string(input),
|
|
Result: tc.Result,
|
|
})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Run starts the agent as a service with a Chat RPC endpoint.
|
|
func (a *agentImpl) Run() error {
|
|
if a.model == nil {
|
|
a.setup()
|
|
}
|
|
|
|
a.server = server.NewServer(
|
|
server.Name(a.opts.Name),
|
|
server.Registry(a.opts.Registry),
|
|
server.Metadata(map[string]string{
|
|
"type": "agent",
|
|
"services": strings.Join(a.opts.Services, ","),
|
|
}),
|
|
)
|
|
|
|
pb.RegisterAgentHandler(a.server, a)
|
|
|
|
if err := a.server.Start(); err != nil {
|
|
return fmt.Errorf("failed to start agent: %w", err)
|
|
}
|
|
|
|
fmt.Printf("Agent %s registered (manages: %s)\n", a.opts.Name, strings.Join(a.opts.Services, ", "))
|
|
|
|
ch := make(chan struct{})
|
|
<-ch
|
|
return nil
|
|
}
|
|
|
|
func (a *agentImpl) Stop() error {
|
|
if a.server != nil {
|
|
return a.server.Stop()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *agentImpl) discoverTools() ([]ai.Tool, error) {
|
|
all, err := a.tools.Discover()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var scoped []ai.Tool
|
|
for _, t := range all {
|
|
if strings.HasPrefix(t.OriginalName, a.opts.Name+".") {
|
|
continue
|
|
}
|
|
if len(a.opts.Services) == 0 {
|
|
scoped = append(scoped, t)
|
|
continue
|
|
}
|
|
for _, svc := range a.opts.Services {
|
|
if strings.HasPrefix(t.OriginalName, svc+".") {
|
|
scoped = append(scoped, t)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return scoped, nil
|
|
}
|
|
|
|
func (a *agentImpl) buildPrompt() string {
|
|
if a.opts.Prompt != "" {
|
|
return a.opts.Prompt
|
|
}
|
|
if len(a.opts.Services) > 0 {
|
|
return fmt.Sprintf("You are the %s agent. You manage these services: %s. Use the available tools to fulfill requests.",
|
|
a.opts.Name, strings.Join(a.opts.Services, ", "))
|
|
}
|
|
return fmt.Sprintf("You are the %s agent. Use the available tools to fulfill requests.", a.opts.Name)
|
|
}
|
|
|
|
func (a *agentImpl) historyKey() string {
|
|
return "agent/" + a.opts.Name + "/history"
|
|
}
|
|
|
|
func (a *agentImpl) loadHistory() {
|
|
recs, err := a.opts.Store.Read(a.historyKey())
|
|
if err != nil || len(recs) == 0 {
|
|
return
|
|
}
|
|
var messages []ai.Message
|
|
if err := json.Unmarshal(recs[0].Value, &messages); err != nil {
|
|
return
|
|
}
|
|
for _, m := range messages {
|
|
a.hist.Add(m.Role, m.Content)
|
|
}
|
|
}
|
|
|
|
func (a *agentImpl) saveHistory() {
|
|
data, err := json.Marshal(a.hist.Messages())
|
|
if err != nil {
|
|
return
|
|
}
|
|
a.opts.Store.Write(&store.Record{
|
|
Key: a.historyKey(),
|
|
Value: data,
|
|
})
|
|
}
|