Files
zigp2p/examples/a2a/conversation.zig
2026-02-06 21:03:59 -03:00

446 lines
17 KiB
Zig

//! A2A Conversation - Two agents autonomously discussing a topic
//!
//! Start two agents, give them a topic, and watch them converse!
//!
//! Usage:
//! Terminal 1: zig build run-a2a-conversation -- --port 9000 --name "Alice"
//! Terminal 2: zig build run-a2a-conversation -- --port 9001 --name "Bob" --connect 127.0.0.1:9000 --start "What do you think about world peace?"
const std = @import("std");
// Override std.log to suppress library noise
pub const std_options = std.Options{
.log_level = .err, // Only show errors, suppress info/debug/warning
.logFn = silentLog,
};
fn silentLog(
comptime level: std.log.Level,
comptime scope: @Type(.enum_literal),
comptime format: []const u8,
args: anytype,
) void {
// Suppress all logs except errors
_ = scope;
_ = format;
_ = args;
if (level == .err) {
// Could print errors if needed
}
}
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 ConversationMode = enum {
chat, // Regular conversation
ideate, // Novel ideas + technical planning for making money
};
const AgentConfig = struct {
listen_port: u16 = 9000,
ollama_url: []const u8 = "http://localhost:11434",
model: []const u8 = "deepseek-v3.1:671b-cloud",
name: []const u8 = "Agent",
connect_to: ?[]const u8 = null,
start_message: ?[]const u8 = null,
max_turns: u32 = 100,
verbose: bool = false,
mode: ConversationMode = .chat,
};
const ConversationAgent = struct {
allocator: std.mem.Allocator,
config: AgentConfig,
p2p_instance: P2P,
running: std.atomic.Value(bool),
http_client: http.Client,
peer: ?PeerId,
conversation_history: std.ArrayList([]const u8),
turn_count: u32,
pub fn init(allocator: std.mem.Allocator, config: AgentConfig) !ConversationAgent {
var p2p_config = P2PConfig.default();
p2p_config.network.enable_noise_encryption = true;
p2p_config.network.enable_dos_protection = false;
p2p_config.events.enable_logging = false; // Clean chat UI
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 },
.peer = null,
.conversation_history = .{},
.turn_count = 0,
};
}
pub fn deinit(self: *ConversationAgent) void {
self.stop();
self.http_client.deinit();
for (self.conversation_history.items) |msg| {
self.allocator.free(msg);
}
self.conversation_history.deinit(self.allocator);
self.p2p_instance.deinit();
}
pub fn start(self: *ConversationAgent) !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);
// Connect to peer if specified
if (self.config.connect_to) |addr_str| {
self.peer = try self.connectToPeer(addr_str);
}
}
pub fn stop(self: *ConversationAgent) void {
self.running.store(false, .release);
self.p2p_instance.stop() catch {};
}
fn connectToPeer(self: *ConversationAgent, 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 } };
return try self.p2p_instance.connectToPeer(addr);
}
/// Send a message to the peer
fn sendMessage(self: *ConversationAgent, message: []const u8) !void {
const peer = self.peer orelse return error.NoPeer;
var payload = std.ArrayList(u8){};
defer payload.deinit(self.allocator);
// Message format: [type byte][name length byte][name][message]
try payload.append(self.allocator, @intFromEnum(protocol.MessageType.request));
try payload.append(self.allocator, @intCast(self.config.name.len));
try payload.appendSlice(self.allocator, self.config.name);
try payload.appendSlice(self.allocator, message);
_ = try self.p2p_instance.sendMessage(peer, 0x42, payload.items);
}
/// Generate a response using the LLM
fn generateResponse(self: *ConversationAgent, incoming_message: []const u8) ![]u8 {
// Build conversation context
var context = std.ArrayList(u8){};
defer context.deinit(self.allocator);
// System prompt based on mode
const system_prompt = switch (self.config.mode) {
.chat => try std.fmt.allocPrint(self.allocator,
\\You are {s}, an AI agent in a peer-to-peer conversation with another AI agent.
\\You're having a thoughtful discussion. Be concise (2-3 sentences max).
\\Share your perspective and ask a follow-up question to keep the conversation going.
\\Don't repeat what the other agent said. Be creative and engaging.
, .{self.config.name}),
.ideate => try std.fmt.allocPrint(self.allocator,
\\You are {s}, an AI co-founder brainstorming with another AI to create a PROFITABLE business idea.
\\
\\YOUR GOAL: Develop novel, actionable ideas that can MAKE REAL MONEY.
\\
\\RULES:
\\- Be specific and practical, not vague or philosophical
\\- Focus on: market opportunity, revenue model, technical feasibility
\\- Build on the other agent's ideas, don't just agree
\\- Challenge weak points, suggest improvements
\\- Think about: MVP, target customers, pricing, competitive advantage
\\- If discussing tech: specify stack, architecture, implementation steps
\\
\\FORMAT: Keep responses focused (3-5 sentences). End with a specific question or proposal to move forward.
\\
\\Remember: The goal is a REAL business that makes REAL money. Be ruthlessly practical.
, .{self.config.name}),
};
defer self.allocator.free(system_prompt);
// Build messages array for Ollama
try context.appendSlice(self.allocator, "{\"model\":\"");
try context.appendSlice(self.allocator, self.config.model);
try context.appendSlice(self.allocator, "\",\"messages\":[");
// System message
try context.appendSlice(self.allocator, "{\"role\":\"system\",\"content\":\"");
try appendEscaped(self.allocator, &context, system_prompt);
try context.appendSlice(self.allocator, "\"},");
// Add conversation history (last few exchanges)
const history_start = if (self.conversation_history.items.len > 6)
self.conversation_history.items.len - 6 else 0;
for (self.conversation_history.items[history_start..], 0..) |msg, i| {
const role = if ((history_start + i) % 2 == 0) "assistant" else "user";
try context.appendSlice(self.allocator, "{\"role\":\"");
try context.appendSlice(self.allocator, role);
try context.appendSlice(self.allocator, "\",\"content\":\"");
try appendEscaped(self.allocator, &context, msg);
try context.appendSlice(self.allocator, "\"},");
}
// Current incoming message
try context.appendSlice(self.allocator, "{\"role\":\"user\",\"content\":\"");
try appendEscaped(self.allocator, &context, incoming_message);
try context.appendSlice(self.allocator, "\"}");
try context.appendSlice(self.allocator, "],\"stream\":false}");
// Call Ollama
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 = context.items,
.headers = .{ .content_type = .{ .override = "application/json" } },
.response_writer = &response_writer.writer,
}) catch return error.HttpFailed;
if (result.status != .ok) return error.OllamaError;
// Parse response
const parsed = std.json.parseFromSlice(
std.json.Value,
self.allocator,
response_writer.written(),
.{},
) catch return error.ParseError;
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);
}
/// Main conversation loop
pub fn run(self: *ConversationAgent) !void {
// If we have a start message, initiate the conversation
if (self.config.start_message) |start_msg| {
// Wait a moment for the other agent to be ready
std.Thread.sleep(1 * std.time.ns_per_s);
// Send the initial message
try self.sendMessage(start_msg);
try self.conversation_history.append(self.allocator, try self.allocator.dupe(u8, start_msg));
// Print our message
printMessage(self.config.name, start_msg);
} else {
std.debug.print("\n💬 Waiting for conversation to start...\n\n", .{});
}
while (self.running.load(.acquire) and self.turn_count < self.config.max_turns) {
try self.p2p_instance.update();
while (self.p2p_instance.getNextEvent()) |event| {
defer {
var evt = event;
evt.deinit();
}
switch (event.data) {
.message_received => |msg| {
try self.handleIncomingMessage(msg.source, msg.data);
},
.peer_connected => |conn| {
if (self.peer == null) {
self.peer = conn.peer_id;
}
},
.peer_disconnected => {
std.debug.print("\n[Conversation ended - peer disconnected]\n", .{});
self.running.store(false, .release);
},
else => {},
}
}
std.Thread.sleep(50 * std.time.ns_per_ms);
}
if (self.turn_count >= self.config.max_turns) {
std.debug.print("\n[Conversation completed - {d} exchanges]\n", .{self.turn_count});
}
}
fn handleIncomingMessage(self: *ConversationAgent, from_peer: PeerId, data: []const u8) !void {
if (data.len < 3) return;
// Message format: [type byte][name length byte][name][message]
const name_len = data[1];
if (data.len < 2 + name_len) return;
const sender_name = data[2..2 + name_len];
const incoming = data[2 + name_len..];
// Store peer if we don't have one
if (self.peer == null) {
self.peer = from_peer;
}
// Print received message with sender's name
printMessage(sender_name, incoming);
// Store in history
try self.conversation_history.append(self.allocator, try self.allocator.dupe(u8, incoming));
// Generate our response
const response = self.generateResponse(incoming) catch |err| {
std.debug.print("[Error: {}]\n", .{err});
return;
};
defer self.allocator.free(response);
// Small delay to make conversation feel natural
std.Thread.sleep(500 * std.time.ns_per_ms);
// Print and send our response
printMessage(self.config.name, response);
try self.sendMessage(response);
try self.conversation_history.append(self.allocator, try self.allocator.dupe(u8, response));
self.turn_count += 1;
}
};
fn printMessage(name: []const u8, message: []const u8) void {
std.debug.print("\x1b[1m{s}:\x1b[0m {s}\n\n", .{ name, message });
}
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();
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, "--name")) {
if (args.next()) |n| config.name = n;
} else if (std.mem.eql(u8, arg, "--connect")) {
config.connect_to = args.next();
} else if (std.mem.eql(u8, arg, "--start")) {
config.start_message = args.next();
} else if (std.mem.eql(u8, arg, "--turns")) {
if (args.next()) |t| config.max_turns = try std.fmt.parseInt(u32, t, 10);
} else if (std.mem.eql(u8, arg, "--mode")) {
if (args.next()) |m| {
if (std.mem.eql(u8, m, "chat")) {
config.mode = .chat;
} else if (std.mem.eql(u8, m, "ideate")) {
config.mode = .ideate;
}
}
} else if (std.mem.eql(u8, arg, "--help")) {
printUsage();
return;
}
}
var agent = try ConversationAgent.init(allocator, config);
defer agent.deinit();
try agent.start();
try agent.run();
}
fn printUsage() void {
std.debug.print(
\\A2A Conversation - Autonomous Agent-to-Agent Discussion
\\
\\Two AI agents discuss a topic with each other over P2P!
\\
\\MODES:
\\ chat - Regular thoughtful conversation (default)
\\ ideate - Brainstorm business ideas & technical plans to MAKE MONEY
\\
\\Usage:
\\ Terminal 1:
\\ zig build run-a2a-conversation -- --port 9000 --name "Alice" --mode ideate
\\
\\ Terminal 2:
\\ zig build run-a2a-conversation -- --port 9001 --name "Bob" --mode ideate \\
\\ --connect 127.0.0.1:9000 --start "Let's build a SaaS product"
\\
\\Options:
\\ --port <port> P2P listen port (default: 9000)
\\ --name <name> Agent name (default: "Agent")
\\ --model <model> LLM model (default: deepseek-v3.1:671b-cloud)
\\ --connect <addr> Connect to another agent (ip:port)
\\ --start <topic> Start conversation with this message
\\ --turns <n> Max conversation turns (default: 100)
\\ --mode <mode> chat or ideate (default: chat)
\\ --help Show this help
\\
\\IDEATE MODE STARTERS:
\\ --start "Let's build a developer tool that solves a real pain point"
\\ --start "What API product could we build and sell to businesses?"
\\ --start "Find a gap in the AI tooling market we can fill"
\\ --start "Let's create a micro-SaaS with recurring revenue"
\\
\\CHAT MODE STARTERS:
\\ --start "What do you think about artificial consciousness?"
\\ --start "What's the meaning of life?"
\\
, .{});
}