//! LLM Agent - P2P Agent that wraps Ollama/OpenAI-compatible LLM //! //! This agent: //! 1. Listens for A2A chat requests over P2P //! 2. Forwards requests to Ollama //! 3. Returns LLM responses to requesting peer //! //! Usage: //! zig build run-llm-agent -- --port 9000 --model deepseek-v3.1:671b-cloud 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", }; const LLMAgent = struct { allocator: std.mem.Allocator, config: AgentConfig, p2p_instance: P2P, running: std.atomic.Value(bool), http_client: http.Client, pub fn init(allocator: std.mem.Allocator, config: AgentConfig) !LLMAgent { var p2p_config = P2PConfig.default(); p2p_config.network.enable_noise_encryption = true; p2p_config.network.enable_dos_protection = false; // Disabled for simpler handshake 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 }, }; } pub fn deinit(self: *LLMAgent) void { self.stop(); self.http_client.deinit(); self.p2p_instance.deinit(); } pub fn start(self: *LLMAgent) !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("LLM Agent started on port {d}\n", .{self.config.listen_port}); std.debug.print("Model: {s}\n", .{self.config.model}); std.debug.print("Ollama: {s}\n", .{self.config.ollama_url}); } pub fn stop(self: *LLMAgent) void { self.running.store(false, .release); self.p2p_instance.stop() catch {}; } pub fn handleRequest(self: *LLMAgent, from_peer: PeerId, request: protocol.A2ARequest) !protocol.A2AResponse { std.debug.print("Request from {x}: model={s}\n", .{ from_peer.bytes[0..8].*, request.model, }); // Call Ollama const response_content = self.callOllama(request) catch |err| { std.debug.print("Ollama error: {}\n", .{err}); return .{ .request_id = request.request_id, .success = false, .content = "LLM call failed", .error_message = @errorName(err), .model = request.model, .agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32, }; }; return .{ .request_id = request.request_id, .success = true, .content = response_content, .model = try self.allocator.dupe(u8, request.model), .agent_id = if (self.p2p_instance.getLocalPeerId()) |id| id.bytes else [_]u8{0} ** 32, }; } fn callOllama(self: *LLMAgent, request: protocol.A2ARequest) ![]u8 { // Build Ollama request JSON var body: std.ArrayList(u8) = .{}; defer body.deinit(self.allocator); try body.appendSlice(self.allocator, "{\"model\":\""); try body.appendSlice(self.allocator, request.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}"); // Build URL const url = try std.fmt.allocPrint(self.allocator, "{s}/api/chat", .{self.config.ollama_url}); defer self.allocator.free(url); std.debug.print("Calling Ollama: {s}\n", .{url}); // Allocating writer for response body var response_writer: std.Io.Writer.Allocating = .init(self.allocator); defer response_writer.deinit(); // Make HTTP request 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) { std.debug.print("Ollama returned status: {}\n", .{result.status}); return error.OllamaError; } const response_data = response_writer.written(); std.debug.print("Ollama response: {d} bytes\n", .{response_data.len}); // Parse JSON response const parsed = std.json.parseFromSlice( std.json.Value, self.allocator, response_data, .{}, ) catch |err| { std.debug.print("JSON parse error: {}\n", .{err}); return error.InvalidJson; }; defer parsed.deinit(); // Extract content from response 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); } pub fn run(self: *LLMAgent) !void { while (self.running.load(.acquire)) { // Process network events (required for handling incoming connections!) try self.p2p_instance.update(); while (self.p2p_instance.getNextEvent()) |event| { defer { var evt = event; evt.deinit(); } switch (event.data) { .message_received => |msg| { self.processMessage(msg.source, msg.data) catch |err| { std.debug.print("Process error: {}\n", .{err}); }; }, .peer_connected => |conn| { std.debug.print("Peer connected: {x}\n", .{conn.peer_id.bytes[0..8].*}); }, .peer_disconnected => |disc| { std.debug.print("Peer disconnected: {x}\n", .{disc.peer_id.bytes[0..8].*}); }, else => {}, } } std.Thread.sleep(10 * std.time.ns_per_ms); } } fn processMessage(self: *LLMAgent, from_peer: PeerId, data: []const u8) !void { if (data.len < 2) return; const msg_type: protocol.MessageType = @enumFromInt(data[0]); switch (msg_type) { .request => { const request = try protocol.A2ARequest.fromJson(self.allocator, data[1..]); const response = try self.handleRequest(from_peer, request); var response_data: std.ArrayList(u8) = .{}; defer response_data.deinit(self.allocator); try response_data.append(self.allocator, @intFromEnum(protocol.MessageType.response)); const json = try response.toJson(self.allocator); defer self.allocator.free(json); try response_data.appendSlice(self.allocator, json); _ = try self.p2p_instance.sendMessage(from_peer, 0x42, response_data.items); }, else => {}, } } }; 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, "--ollama-url")) { if (args.next()) |u| config.ollama_url = u; } else if (std.mem.eql(u8, arg, "--help")) { printUsage(); return; } } var agent = try LLMAgent.init(allocator, config); defer agent.deinit(); try agent.start(); std.debug.print("Ready. Waiting for requests...\n\n", .{}); try agent.run(); } fn printUsage() void { std.debug.print( \\LLM Agent - P2P Agent wrapping Ollama \\ \\Usage: llm_agent [options] \\ \\Options: \\ --port P2P listen port (default: 9000) \\ --model LLM model (default: llama3.2) \\ --ollama-url Ollama URL (default: http://localhost:11434) \\ --help Show this help \\ \\Example: \\ zig build run-llm-agent -- --port 9000 --model deepseek-v3.1:671b-cloud \\ , .{}); }