ab ovo
This commit is contained in:
470
examples/a2a/agent.zig
Normal file
470
examples/a2a/agent.zig
Normal file
@@ -0,0 +1,470 @@
|
||||
//! A2A Agent - Symmetric peer-to-peer LLM agent
|
||||
//!
|
||||
//! Each agent can both send and receive requests - true A2A communication.
|
||||
//! Agents discover each other and can request capabilities from any peer.
|
||||
//!
|
||||
//! Usage:
|
||||
//! zig build run-a2a-agent -- --port 9000 --model deepseek-v3.1:671b-cloud
|
||||
//! zig build run-a2a-agent -- --port 9001 --model llama3.2 --connect 127.0.0.1:9000
|
||||
|
||||
const std = @import("std");
|
||||
const http = std.http;
|
||||
const p2p_lib = @import("p2p");
|
||||
const network = @import("network");
|
||||
const protocol = @import("protocol");
|
||||
|
||||
const P2P = p2p_lib.P2P;
|
||||
const P2PConfig = p2p_lib.P2PConfig;
|
||||
const PeerId = network.PeerId;
|
||||
const Address = p2p_lib.Address;
|
||||
|
||||
const AgentConfig = struct {
|
||||
listen_port: u16 = 9000,
|
||||
ollama_url: []const u8 = "http://localhost:11434",
|
||||
model: []const u8 = "deepseek-v3.1:671b-cloud",
|
||||
capability: []const u8 = "chat",
|
||||
connect_to: ?[]const u8 = null, // Optional peer to connect to
|
||||
};
|
||||
|
||||
const PendingRequest = struct {
|
||||
request_id: [16]u8,
|
||||
callback: ?*const fn ([]const u8) void,
|
||||
};
|
||||
|
||||
const A2AAgent = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
config: AgentConfig,
|
||||
p2p_instance: P2P,
|
||||
running: std.atomic.Value(bool),
|
||||
http_client: http.Client,
|
||||
connected_peers: std.ArrayList(PeerId),
|
||||
pending_responses: std.AutoHashMap([16]u8, []const u8),
|
||||
mutex: std.Thread.Mutex,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator, config: AgentConfig) !A2AAgent {
|
||||
var p2p_config = P2PConfig.default();
|
||||
p2p_config.network.enable_noise_encryption = true;
|
||||
p2p_config.network.enable_dos_protection = false;
|
||||
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.config = config,
|
||||
.p2p_instance = try P2P.init(allocator, p2p_config),
|
||||
.running = std.atomic.Value(bool).init(false),
|
||||
.http_client = http.Client{ .allocator = allocator },
|
||||
.connected_peers = .{},
|
||||
.pending_responses = std.AutoHashMap([16]u8, []const u8).init(allocator),
|
||||
.mutex = .{},
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *A2AAgent) void {
|
||||
self.stop();
|
||||
self.http_client.deinit();
|
||||
self.connected_peers.deinit(self.allocator);
|
||||
|
||||
// Clean up pending responses
|
||||
var it = self.pending_responses.valueIterator();
|
||||
while (it.next()) |v| {
|
||||
self.allocator.free(v.*);
|
||||
}
|
||||
self.pending_responses.deinit();
|
||||
|
||||
self.p2p_instance.deinit();
|
||||
}
|
||||
|
||||
pub fn start(self: *A2AAgent) !void {
|
||||
try self.p2p_instance.start();
|
||||
|
||||
var listen_addr = Address.init();
|
||||
listen_addr.port = self.config.listen_port;
|
||||
listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 0, 0, 0, 0 } } };
|
||||
try self.p2p_instance.startListening(listen_addr);
|
||||
|
||||
self.running.store(true, .release);
|
||||
|
||||
std.debug.print("\n=== A2A Agent Started ===\n", .{});
|
||||
std.debug.print("Port: {d}\n", .{self.config.listen_port});
|
||||
std.debug.print("Model: {s}\n", .{self.config.model});
|
||||
std.debug.print("Capability: {s}\n", .{self.config.capability});
|
||||
std.debug.print("Ollama: {s}\n\n", .{self.config.ollama_url});
|
||||
|
||||
// Connect to peer if specified
|
||||
if (self.config.connect_to) |addr_str| {
|
||||
std.debug.print("Connecting to peer: {s}...\n", .{addr_str});
|
||||
const peer_id = try self.connectToPeer(addr_str);
|
||||
std.debug.print("Connected to peer: {x}\n\n", .{peer_id.bytes[0..8].*});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(self: *A2AAgent) void {
|
||||
self.running.store(false, .release);
|
||||
self.p2p_instance.stop() catch {};
|
||||
}
|
||||
|
||||
fn connectToPeer(self: *A2AAgent, addr_str: []const u8) !PeerId {
|
||||
var it = std.mem.splitScalar(u8, addr_str, ':');
|
||||
const ip_str = it.next() orelse return error.InvalidAddress;
|
||||
const port_str = it.next() orelse return error.InvalidAddress;
|
||||
const port = try std.fmt.parseInt(u16, port_str, 10);
|
||||
|
||||
var ip_parts: [4]u8 = undefined;
|
||||
var ip_it = std.mem.splitScalar(u8, ip_str, '.');
|
||||
for (&ip_parts) |*part| {
|
||||
const part_str = ip_it.next() orelse return error.InvalidAddress;
|
||||
part.* = try std.fmt.parseInt(u8, part_str, 10);
|
||||
}
|
||||
|
||||
var addr = Address.init();
|
||||
addr.port = port;
|
||||
addr.data = .{ .ipv4 = .{ .bytes = ip_parts } };
|
||||
|
||||
const peer_id = try self.p2p_instance.connectToPeer(addr);
|
||||
|
||||
self.mutex.lock();
|
||||
defer self.mutex.unlock();
|
||||
try self.connected_peers.append(self.allocator, peer_id);
|
||||
|
||||
return peer_id;
|
||||
}
|
||||
|
||||
/// Send a chat request to another agent and wait for response
|
||||
pub fn askAgent(self: *A2AAgent, peer: PeerId, message: []const u8) ![]const u8 {
|
||||
const request_id = protocol.generateRequestId();
|
||||
|
||||
const messages = [_]protocol.ChatMessage{
|
||||
.{ .role = .user, .content = message },
|
||||
};
|
||||
|
||||
const request = protocol.A2ARequest{
|
||||
.request_id = request_id,
|
||||
.model = self.config.model,
|
||||
.messages = &messages,
|
||||
.temperature = 0.7,
|
||||
.capability = self.config.capability,
|
||||
};
|
||||
|
||||
// Send request
|
||||
var payload = std.ArrayList(u8){};
|
||||
defer payload.deinit(self.allocator);
|
||||
|
||||
try payload.append(self.allocator, @intFromEnum(protocol.MessageType.request));
|
||||
const json = try request.toJson(self.allocator);
|
||||
defer self.allocator.free(json);
|
||||
try payload.appendSlice(self.allocator, json);
|
||||
|
||||
_ = try self.p2p_instance.sendMessage(peer, 0x42, payload.items);
|
||||
std.debug.print("Sent request to peer {x}: \"{s}\"\n", .{peer.bytes[0..8].*, message});
|
||||
|
||||
// Wait for response
|
||||
const timeout_ns: i128 = 60 * std.time.ns_per_s;
|
||||
const start_time = std.time.nanoTimestamp();
|
||||
|
||||
while (std.time.nanoTimestamp() - start_time < timeout_ns) {
|
||||
self.processOnce() catch {};
|
||||
|
||||
self.mutex.lock();
|
||||
if (self.pending_responses.get(request_id)) |response| {
|
||||
_ = self.pending_responses.remove(request_id);
|
||||
self.mutex.unlock();
|
||||
return response;
|
||||
}
|
||||
self.mutex.unlock();
|
||||
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
return error.Timeout;
|
||||
}
|
||||
|
||||
/// Get list of connected peers
|
||||
pub fn getPeers(self: *A2AAgent) []const PeerId {
|
||||
self.mutex.lock();
|
||||
defer self.mutex.unlock();
|
||||
return self.connected_peers.items;
|
||||
}
|
||||
|
||||
/// Process one iteration of the event loop
|
||||
pub fn processOnce(self: *A2AAgent) !void {
|
||||
try self.p2p_instance.update();
|
||||
|
||||
while (self.p2p_instance.getNextEvent()) |event| {
|
||||
defer {
|
||||
var evt = event;
|
||||
evt.deinit();
|
||||
}
|
||||
switch (event.data) {
|
||||
.message_received => |msg| {
|
||||
self.handleMessage(msg.source, msg.data) catch |err| {
|
||||
std.debug.print("Message handling error: {}\n", .{err});
|
||||
};
|
||||
},
|
||||
.peer_connected => |conn| {
|
||||
std.debug.print("Peer connected: {x}\n", .{conn.peer_id.bytes[0..8].*});
|
||||
self.mutex.lock();
|
||||
self.connected_peers.append(self.allocator, conn.peer_id) catch {};
|
||||
self.mutex.unlock();
|
||||
},
|
||||
.peer_disconnected => |disc| {
|
||||
std.debug.print("Peer disconnected: {x}\n", .{disc.peer_id.bytes[0..8].*});
|
||||
self.mutex.lock();
|
||||
for (self.connected_peers.items, 0..) |p, i| {
|
||||
if (std.mem.eql(u8, &p.bytes, &disc.peer_id.bytes)) {
|
||||
_ = self.connected_peers.swapRemove(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.mutex.unlock();
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the agent's main loop
|
||||
pub fn run(self: *A2AAgent) !void {
|
||||
std.debug.print("Agent running. Waiting for messages...\n\n", .{});
|
||||
while (self.running.load(.acquire)) {
|
||||
try self.processOnce();
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
}
|
||||
}
|
||||
|
||||
fn handleMessage(self: *A2AAgent, from_peer: PeerId, data: []const u8) !void {
|
||||
if (data.len < 2) return;
|
||||
|
||||
const msg_type: protocol.MessageType = @enumFromInt(data[0]);
|
||||
|
||||
switch (msg_type) {
|
||||
.request => {
|
||||
// Another agent is asking us something
|
||||
const request = try protocol.A2ARequest.fromJson(self.allocator, data[1..]);
|
||||
defer {
|
||||
self.allocator.free(request.model);
|
||||
self.allocator.free(request.capability);
|
||||
for (request.messages) |msg| {
|
||||
self.allocator.free(msg.content);
|
||||
}
|
||||
self.allocator.free(request.messages);
|
||||
}
|
||||
|
||||
std.debug.print("\nRequest from {x}: \"{s}\"\n", .{
|
||||
from_peer.bytes[0..8].*,
|
||||
if (request.messages.len > 0) request.messages[request.messages.len - 1].content else "(empty)",
|
||||
});
|
||||
|
||||
const response = try self.handleRequest(from_peer, request);
|
||||
defer self.allocator.free(response.content);
|
||||
defer self.allocator.free(response.model);
|
||||
|
||||
// Send response back
|
||||
var response_data = std.ArrayList(u8){};
|
||||
defer response_data.deinit(self.allocator);
|
||||
|
||||
try response_data.append(self.allocator, @intFromEnum(protocol.MessageType.response));
|
||||
const resp_json = try response.toJson(self.allocator);
|
||||
defer self.allocator.free(resp_json);
|
||||
try response_data.appendSlice(self.allocator, resp_json);
|
||||
|
||||
_ = try self.p2p_instance.sendMessage(from_peer, 0x42, response_data.items);
|
||||
std.debug.print("Sent response to {x}\n\n", .{from_peer.bytes[0..8].*});
|
||||
},
|
||||
.response => {
|
||||
// Response to our request
|
||||
const response = try protocol.A2AResponse.fromJson(self.allocator, data[1..]);
|
||||
defer self.allocator.free(response.model);
|
||||
|
||||
std.debug.print("\nResponse from {x}: \"{s}\"\n\n", .{
|
||||
from_peer.bytes[0..8].*,
|
||||
response.content,
|
||||
});
|
||||
|
||||
// Store response for askAgent to pick up
|
||||
self.mutex.lock();
|
||||
self.pending_responses.put(response.request_id, response.content) catch {};
|
||||
self.mutex.unlock();
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn handleRequest(self: *A2AAgent, from_peer: PeerId, request: protocol.A2ARequest) !protocol.A2AResponse {
|
||||
// Call our local LLM
|
||||
const response_content = self.callOllama(request) catch |err| {
|
||||
std.debug.print("Ollama error: {}\n", .{err});
|
||||
return .{
|
||||
.request_id = request.request_id,
|
||||
.success = false,
|
||||
.content = try self.allocator.dupe(u8, "LLM call failed"),
|
||||
.error_message = @errorName(err),
|
||||
.model = try self.allocator.dupe(u8, self.config.model),
|
||||
.agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32,
|
||||
};
|
||||
};
|
||||
|
||||
_ = from_peer;
|
||||
return .{
|
||||
.request_id = request.request_id,
|
||||
.success = true,
|
||||
.content = response_content,
|
||||
.model = try self.allocator.dupe(u8, self.config.model),
|
||||
.agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32,
|
||||
};
|
||||
}
|
||||
|
||||
fn callOllama(self: *A2AAgent, request: protocol.A2ARequest) ![]u8 {
|
||||
var body = std.ArrayList(u8){};
|
||||
defer body.deinit(self.allocator);
|
||||
|
||||
try body.appendSlice(self.allocator, "{\"model\":\"");
|
||||
try body.appendSlice(self.allocator, self.config.model);
|
||||
try body.appendSlice(self.allocator, "\",\"messages\":[");
|
||||
|
||||
for (request.messages, 0..) |msg, i| {
|
||||
if (i > 0) try body.append(self.allocator, ',');
|
||||
try body.appendSlice(self.allocator, "{\"role\":\"");
|
||||
try body.appendSlice(self.allocator, msg.role.toString());
|
||||
try body.appendSlice(self.allocator, "\",\"content\":\"");
|
||||
try appendEscaped(self.allocator, &body, msg.content);
|
||||
try body.appendSlice(self.allocator, "\"}");
|
||||
}
|
||||
|
||||
try body.appendSlice(self.allocator, "],\"stream\":false}");
|
||||
|
||||
const url = try std.fmt.allocPrint(self.allocator, "{s}/api/chat", .{self.config.ollama_url});
|
||||
defer self.allocator.free(url);
|
||||
|
||||
var response_writer: std.Io.Writer.Allocating = .init(self.allocator);
|
||||
defer response_writer.deinit();
|
||||
|
||||
const result = self.http_client.fetch(.{
|
||||
.location = .{ .url = url },
|
||||
.method = .POST,
|
||||
.payload = body.items,
|
||||
.headers = .{
|
||||
.content_type = .{ .override = "application/json" },
|
||||
},
|
||||
.response_writer = &response_writer.writer,
|
||||
}) catch |err| {
|
||||
std.debug.print("HTTP error: {}\n", .{err});
|
||||
return error.HttpRequestFailed;
|
||||
};
|
||||
|
||||
if (result.status != .ok) {
|
||||
return error.OllamaError;
|
||||
}
|
||||
|
||||
const response_data = response_writer.written();
|
||||
|
||||
const parsed = std.json.parseFromSlice(
|
||||
std.json.Value,
|
||||
self.allocator,
|
||||
response_data,
|
||||
.{},
|
||||
) catch return error.InvalidJson;
|
||||
defer parsed.deinit();
|
||||
|
||||
const message = parsed.value.object.get("message") orelse return error.InvalidResponse;
|
||||
const content = message.object.get("content") orelse return error.InvalidResponse;
|
||||
|
||||
return try self.allocator.dupe(u8, content.string);
|
||||
}
|
||||
};
|
||||
|
||||
fn appendEscaped(allocator: std.mem.Allocator, list: *std.ArrayList(u8), s: []const u8) !void {
|
||||
for (s) |c| {
|
||||
switch (c) {
|
||||
'"' => try list.appendSlice(allocator, "\\\""),
|
||||
'\\' => try list.appendSlice(allocator, "\\\\"),
|
||||
'\n' => try list.appendSlice(allocator, "\\n"),
|
||||
'\r' => try list.appendSlice(allocator, "\\r"),
|
||||
'\t' => try list.appendSlice(allocator, "\\t"),
|
||||
else => try list.append(allocator, c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
var config = AgentConfig{};
|
||||
var args = try std.process.argsWithAllocator(allocator);
|
||||
defer args.deinit();
|
||||
|
||||
_ = args.skip();
|
||||
|
||||
var interactive_message: ?[]const u8 = null;
|
||||
|
||||
while (args.next()) |arg| {
|
||||
if (std.mem.eql(u8, arg, "--port")) {
|
||||
if (args.next()) |p| config.listen_port = try std.fmt.parseInt(u16, p, 10);
|
||||
} else if (std.mem.eql(u8, arg, "--model")) {
|
||||
if (args.next()) |m| config.model = m;
|
||||
} else if (std.mem.eql(u8, arg, "--ollama-url")) {
|
||||
if (args.next()) |u| config.ollama_url = u;
|
||||
} else if (std.mem.eql(u8, arg, "--connect")) {
|
||||
config.connect_to = args.next();
|
||||
} else if (std.mem.eql(u8, arg, "--ask")) {
|
||||
interactive_message = args.next();
|
||||
} else if (std.mem.eql(u8, arg, "--help")) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var agent = try A2AAgent.init(allocator, config);
|
||||
defer agent.deinit();
|
||||
|
||||
try agent.start();
|
||||
|
||||
// If --ask was provided, send a message to connected peer and print response
|
||||
if (interactive_message) |message| {
|
||||
const peers = agent.getPeers();
|
||||
if (peers.len == 0) {
|
||||
std.debug.print("No peers connected. Use --connect to connect to another agent.\n", .{});
|
||||
return;
|
||||
}
|
||||
|
||||
const response = try agent.askAgent(peers[0], message);
|
||||
defer allocator.free(response);
|
||||
std.debug.print("\n=== Response ===\n{s}\n", .{response});
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise run as a daemon, accepting requests from other agents
|
||||
try agent.run();
|
||||
}
|
||||
|
||||
fn printUsage() void {
|
||||
std.debug.print(
|
||||
\\A2A Agent - Symmetric P2P LLM Agent
|
||||
\\
|
||||
\\Each agent can both SEND and RECEIVE requests - true A2A communication.
|
||||
\\
|
||||
\\Usage: a2a_agent [options]
|
||||
\\
|
||||
\\Options:
|
||||
\\ --port <port> P2P listen port (default: 9000)
|
||||
\\ --model <model> LLM model (default: deepseek-v3.1:671b-cloud)
|
||||
\\ --ollama-url <url> Ollama URL (default: http://localhost:11434)
|
||||
\\ --connect <addr> Connect to another agent (ip:port)
|
||||
\\ --ask <message> Send message to connected peer and exit
|
||||
\\ --help Show this help
|
||||
\\
|
||||
\\Examples:
|
||||
\\
|
||||
\\ # Start Agent A (with deepseek model)
|
||||
\\ zig build run-a2a-agent -- --port 9000 --model deepseek-v3.1:671b-cloud
|
||||
\\
|
||||
\\ # Start Agent B (with different model), connect to A
|
||||
\\ zig build run-a2a-agent -- --port 9001 --model llama3.2 --connect 127.0.0.1:9000
|
||||
\\
|
||||
\\ # Agent B asks Agent A a question
|
||||
\\ zig build run-a2a-agent -- --port 9002 --connect 127.0.0.1:9000 --ask "What is 2+2?"
|
||||
\\
|
||||
\\Both agents can send requests to each other - symmetric A2A communication!
|
||||
\\
|
||||
, .{});
|
||||
}
|
||||
Reference in New Issue
Block a user