217 lines
7.1 KiB
Zig
217 lines
7.1 KiB
Zig
//! Client Agent - Connects to LLM agents over P2P
|
|
//!
|
|
//! Usage:
|
|
//! zig build run-client-agent -- --connect 127.0.0.1:9000 --message "Hello!"
|
|
|
|
const std = @import("std");
|
|
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 ClientConfig = struct {
|
|
listen_port: u16 = 9100,
|
|
connect_addr: ?[]const u8 = null,
|
|
model: []const u8 = "deepseek-v3.1:671b-cloud",
|
|
message: ?[]const u8 = null,
|
|
};
|
|
|
|
const ClientAgent = struct {
|
|
allocator: std.mem.Allocator,
|
|
config: ClientConfig,
|
|
p2p_instance: P2P,
|
|
llm_peer: ?PeerId,
|
|
response_received: std.atomic.Value(bool),
|
|
response_content: ?[]const u8,
|
|
|
|
pub fn init(allocator: std.mem.Allocator, config: ClientConfig) !ClientAgent {
|
|
var p2p_config = P2PConfig.default();
|
|
p2p_config.network.enable_noise_encryption = true;
|
|
|
|
return .{
|
|
.allocator = allocator,
|
|
.config = config,
|
|
.p2p_instance = try P2P.init(allocator, p2p_config),
|
|
.llm_peer = null,
|
|
.response_received = std.atomic.Value(bool).init(false),
|
|
.response_content = null,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *ClientAgent) void {
|
|
self.p2p_instance.stop() catch {};
|
|
self.p2p_instance.deinit();
|
|
}
|
|
|
|
pub fn start(self: *ClientAgent) !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);
|
|
|
|
std.debug.print("Client started on port {d}\n", .{self.config.listen_port});
|
|
|
|
if (self.config.connect_addr) |addr_str| {
|
|
std.debug.print("Connecting to {s}...\n", .{addr_str});
|
|
|
|
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.llm_peer = peer_id;
|
|
std.debug.print("Connected: {x}\n", .{peer_id.bytes[0..8].*});
|
|
}
|
|
}
|
|
|
|
pub fn sendChat(self: *ClientAgent, user_message: []const u8) ![]const u8 {
|
|
const peer = self.llm_peer orelse return error.NotConnected;
|
|
|
|
const messages = [_]protocol.ChatMessage{
|
|
.{ .role = .system, .content = "You are helpful." },
|
|
.{ .role = .user, .content = user_message },
|
|
};
|
|
|
|
const request = protocol.A2ARequest{
|
|
.request_id = protocol.generateRequestId(),
|
|
.model = self.config.model,
|
|
.messages = &messages,
|
|
.temperature = 0.7,
|
|
};
|
|
|
|
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, waiting...\n", .{});
|
|
|
|
// Wait for response
|
|
const timeout_ns: i128 = 30 * std.time.ns_per_s;
|
|
const start_time = std.time.nanoTimestamp();
|
|
|
|
while (!self.response_received.load(.acquire)) {
|
|
self.processEvents();
|
|
if (std.time.nanoTimestamp() - start_time > timeout_ns) {
|
|
return error.Timeout;
|
|
}
|
|
std.Thread.sleep(10 * std.time.ns_per_ms);
|
|
}
|
|
|
|
return self.response_content orelse error.NoResponse;
|
|
}
|
|
|
|
fn processEvents(self: *ClientAgent) void {
|
|
// Process network I/O (required to receive messages!)
|
|
self.p2p_instance.update() catch {};
|
|
|
|
while (self.p2p_instance.getNextEvent()) |event| {
|
|
defer {
|
|
var evt = event;
|
|
evt.deinit();
|
|
}
|
|
switch (event.data) {
|
|
.message_received => |msg| {
|
|
self.handleMessage(msg.data) catch {};
|
|
},
|
|
else => {},
|
|
}
|
|
}
|
|
}
|
|
|
|
fn handleMessage(self: *ClientAgent, data: []const u8) !void {
|
|
if (data.len < 2) return;
|
|
|
|
const msg_type: protocol.MessageType = @enumFromInt(data[0]);
|
|
if (msg_type == .response) {
|
|
const response = try protocol.A2AResponse.fromJson(self.allocator, data[1..]);
|
|
// Free model (we don't need it), keep content for returning
|
|
self.allocator.free(response.model);
|
|
self.response_content = response.content;
|
|
self.response_received.store(true, .release);
|
|
}
|
|
}
|
|
};
|
|
|
|
pub fn main() !void {
|
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
defer _ = gpa.deinit();
|
|
const allocator = gpa.allocator();
|
|
|
|
var config = ClientConfig{};
|
|
var args = try std.process.argsWithAllocator(allocator);
|
|
defer args.deinit();
|
|
|
|
_ = args.skip();
|
|
|
|
while (args.next()) |arg| {
|
|
if (std.mem.eql(u8, arg, "--connect")) {
|
|
config.connect_addr = args.next();
|
|
} else if (std.mem.eql(u8, arg, "--message")) {
|
|
config.message = args.next();
|
|
} else if (std.mem.eql(u8, arg, "--model")) {
|
|
if (args.next()) |model| config.model = model;
|
|
} else if (std.mem.eql(u8, arg, "--help")) {
|
|
printUsage();
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (config.connect_addr == null or config.message == null) {
|
|
std.debug.print("Error: --connect and --message required\n\n", .{});
|
|
printUsage();
|
|
return;
|
|
}
|
|
|
|
var client = try ClientAgent.init(allocator, config);
|
|
defer client.deinit();
|
|
|
|
try client.start();
|
|
|
|
const response = try client.sendChat(config.message.?);
|
|
defer allocator.free(response);
|
|
std.debug.print("\nResponse: {s}\n", .{response});
|
|
}
|
|
|
|
fn printUsage() void {
|
|
const usage =
|
|
\\A2A Client - Connect to LLM agents over P2P
|
|
\\
|
|
\\Usage:
|
|
\\ client_agent --connect <ip:port> --message <msg>
|
|
\\
|
|
\\Options:
|
|
\\ --connect <addr> LLM agent address (required)
|
|
\\ --message <msg> Message to send (required)
|
|
\\ --model <model> Model name (default: llama3.2)
|
|
\\ --help Show this help
|
|
\\
|
|
\\Example:
|
|
\\ zig build run-client-agent -- --connect 127.0.0.1:9000 --message "Hello!"
|
|
\\
|
|
;
|
|
std.debug.print("{s}", .{usage});
|
|
}
|