ab ovo
This commit is contained in:
1114
examples/a2a/MULTI_AGENT_ORCHESTRATION.md
Normal file
1114
examples/a2a/MULTI_AGENT_ORCHESTRATION.md
Normal file
File diff suppressed because it is too large
Load Diff
162
examples/a2a/README.md
Normal file
162
examples/a2a/README.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# A2A: Agent-to-Agent Communication over P2P
|
||||
|
||||
Decentralized LLM agent communication using OpenAI-compatible protocol over encrypted P2P network.
|
||||
|
||||
## Features
|
||||
|
||||
- **OpenAI API Compatible**: Works with Ollama, OpenAI, and any compatible provider
|
||||
- **End-to-End Encrypted**: Noise Protocol (same as WireGuard)
|
||||
- **NAT Traversal**: STUN/TURN/hole punching built-in
|
||||
- **Zero Central Server**: True peer-to-peer, no intermediaries
|
||||
- **DHT Discovery**: Agents discover each other via Kademlia DHT
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Start Ollama
|
||||
|
||||
```bash
|
||||
# Install Ollama: https://ollama.ai
|
||||
ollama pull deepseek-v3.1:671b-cloud # or any model you have
|
||||
ollama serve # Runs on http://localhost:11434
|
||||
```
|
||||
zig build run-a2a-agent -- --port 9001 --model deepseek-v3.1:671b-cloud --connect 127.0.0.1:9000
|
||||
### 2. Start LLM Agent
|
||||
|
||||
```bash
|
||||
# Terminal 1: Start an LLM agent that wraps Ollama
|
||||
zig build run-llm-agent -- --port 9000
|
||||
# Default model: deepseek-v3.1:671b-cloud (can override with --model)
|
||||
```
|
||||
|
||||
### 3. Connect Client
|
||||
|
||||
```bash
|
||||
# Terminal 2: Send a message
|
||||
zig build run-client-agent -- --connect 127.0.0.1:9000 --message "What is 2+2?"
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ P2P (Encrypted) ┌─────────────────┐
|
||||
│ Client Agent │◄──────────────────────────────►│ LLM Agent │
|
||||
│ │ Noise Protocol + DHT │ │
|
||||
│ - Chat REPL │ │ - Ollama API │
|
||||
│ - Multi-agent │ │ - OpenAI API │
|
||||
└─────────────────┘ └─────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────┐
|
||||
│ Ollama │
|
||||
│ llama3.2 │
|
||||
│ mistral │
|
||||
│ codellama │
|
||||
└───────────────┘
|
||||
```
|
||||
|
||||
## Protocol
|
||||
|
||||
### Request (OpenAI-compatible)
|
||||
```json
|
||||
{
|
||||
"request_id": "a1b2c3d4...",
|
||||
"model": "llama3.2",
|
||||
"capability": "chat",
|
||||
"temperature": 0.7,
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hello!"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Response
|
||||
```json
|
||||
{
|
||||
"request_id": "a1b2c3d4...",
|
||||
"success": true,
|
||||
"model": "llama3.2",
|
||||
"content": "Hello! How can I help you today?",
|
||||
"agent_id": "peer_id_hex...",
|
||||
"tokens_used": 42
|
||||
}
|
||||
```
|
||||
|
||||
## Multi-Agent Setup
|
||||
|
||||
Run multiple specialized agents:
|
||||
|
||||
```bash
|
||||
# Terminal 1: General chat agent
|
||||
zig build run-llm-agent -- --port 9000 --model llama3.2 --capability chat
|
||||
|
||||
# Terminal 2: Code agent
|
||||
zig build run-llm-agent -- --port 9001 --model codellama --capability code
|
||||
|
||||
# Terminal 3: Summarization agent
|
||||
zig build run-llm-agent -- --port 9002 --model mistral --capability summarize
|
||||
```
|
||||
|
||||
Connect to any:
|
||||
|
||||
```bash
|
||||
zig build run-client-agent -- --connect 127.0.0.1:9001 --model codellama
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### LLM Agent Options
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `--port` | 9000 | P2P listen port |
|
||||
| `--model` | llama3.2 | Default LLM model |
|
||||
| `--ollama-url` | http://localhost:11434 | Ollama API endpoint |
|
||||
| `--capability` | chat | Agent capability name |
|
||||
| `--bootstrap` | - | Bootstrap peer address |
|
||||
|
||||
### Client Options
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `--connect` | (required) | LLM agent address |
|
||||
| `--port` | 9100 | Our listen port |
|
||||
| `--model` | llama3.2 | Model to request |
|
||||
| `--message` | - | Single message (non-interactive) |
|
||||
| `--system` | "You are helpful..." | System prompt |
|
||||
|
||||
## Security
|
||||
|
||||
- **Encryption**: ChaCha20-Poly1305 (via Noise Protocol)
|
||||
- **Authentication**: Mutual peer authentication
|
||||
- **Key Exchange**: X25519 ECDH
|
||||
- **DoS Protection**: Cookie challenge + rate limiting
|
||||
|
||||
All traffic is encrypted end-to-end. No plaintext messages on the wire.
|
||||
|
||||
## Use Cases
|
||||
|
||||
1. **Private LLM Network**: Run LLMs on-premise, access from anywhere
|
||||
2. **Multi-Agent Systems**: Specialized agents collaborate over P2P
|
||||
3. **Federated Inference**: Distribute load across multiple LLM servers
|
||||
4. **Edge AI**: LLM agents at the edge, discovered via DHT
|
||||
5. **Censorship Resistance**: No central server to block
|
||||
|
||||
## Comparison
|
||||
|
||||
| Feature | A2A (zig-p2p) | OpenAI API | Ollama Direct |
|
||||
|---------|---------------|------------|---------------|
|
||||
| Decentralized | ✅ | ❌ | ❌ |
|
||||
| E2E Encrypted | ✅ | TLS only | ❌ |
|
||||
| NAT Traversal | ✅ | N/A | ❌ |
|
||||
| Multi-Agent | ✅ | ❌ | ❌ |
|
||||
| Discovery | DHT | N/A | Manual |
|
||||
| Dependencies | 0 | SDK | None |
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- [ ] Agent capability negotiation
|
||||
- [ ] Load balancing across agents
|
||||
- [ ] Streaming responses
|
||||
- [ ] Tool use / function calling
|
||||
- [ ] Agent-to-agent delegation
|
||||
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!
|
||||
\\
|
||||
, .{});
|
||||
}
|
||||
216
examples/a2a/client_agent.zig
Normal file
216
examples/a2a/client_agent.zig
Normal file
@@ -0,0 +1,216 @@
|
||||
//! 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});
|
||||
}
|
||||
445
examples/a2a/conversation.zig
Normal file
445
examples/a2a/conversation.zig
Normal file
@@ -0,0 +1,445 @@
|
||||
//! 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?"
|
||||
\\
|
||||
, .{});
|
||||
}
|
||||
291
examples/a2a/llm_agent.zig
Normal file
291
examples/a2a/llm_agent.zig
Normal file
@@ -0,0 +1,291 @@
|
||||
//! 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 <port> P2P listen port (default: 9000)
|
||||
\\ --model <model> LLM model (default: llama3.2)
|
||||
\\ --ollama-url <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
|
||||
\\
|
||||
, .{});
|
||||
}
|
||||
266
examples/a2a/protocol.zig
Normal file
266
examples/a2a/protocol.zig
Normal file
@@ -0,0 +1,266 @@
|
||||
//! A2A Protocol - OpenAI API Compatible Message Format
|
||||
//!
|
||||
//! This module defines the wire protocol for agent-to-agent communication
|
||||
//! using OpenAI-compatible chat completion format. Works with Ollama, OpenAI,
|
||||
//! and any OpenAI-compatible LLM provider.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
/// Chat message role (OpenAI standard)
|
||||
pub const Role = enum {
|
||||
system,
|
||||
user,
|
||||
assistant,
|
||||
tool,
|
||||
|
||||
pub fn toString(self: Role) []const u8 {
|
||||
return switch (self) {
|
||||
.system => "system",
|
||||
.user => "user",
|
||||
.assistant => "assistant",
|
||||
.tool => "tool",
|
||||
};
|
||||
}
|
||||
|
||||
pub fn fromString(s: []const u8) ?Role {
|
||||
if (std.mem.eql(u8, s, "system")) return .system;
|
||||
if (std.mem.eql(u8, s, "user")) return .user;
|
||||
if (std.mem.eql(u8, s, "assistant")) return .assistant;
|
||||
if (std.mem.eql(u8, s, "tool")) return .tool;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/// Single chat message (OpenAI standard)
|
||||
pub const ChatMessage = struct {
|
||||
role: Role,
|
||||
content: []const u8,
|
||||
name: ?[]const u8 = null,
|
||||
};
|
||||
|
||||
/// A2A Request - wraps OpenAI chat completion request
|
||||
pub const A2ARequest = struct {
|
||||
request_id: [16]u8,
|
||||
model: []const u8,
|
||||
messages: []const ChatMessage,
|
||||
temperature: f32 = 0.7,
|
||||
max_tokens: ?u32 = null,
|
||||
capability: []const u8 = "chat",
|
||||
|
||||
pub fn toJson(self: *const A2ARequest, allocator: std.mem.Allocator) ![]u8 {
|
||||
var string: std.ArrayList(u8) = .{};
|
||||
errdefer string.deinit(allocator);
|
||||
|
||||
try string.appendSlice(allocator, "{\"request_id\":\"");
|
||||
try appendHex(allocator, &string, &self.request_id);
|
||||
try string.appendSlice(allocator, "\",\"model\":\"");
|
||||
try appendEscaped(allocator, &string, self.model);
|
||||
try string.appendSlice(allocator, "\",\"capability\":\"");
|
||||
try appendEscaped(allocator, &string, self.capability);
|
||||
try string.appendSlice(allocator, "\",\"temperature\":");
|
||||
|
||||
var temp_buf: [32]u8 = undefined;
|
||||
const temp_str = std.fmt.bufPrint(&temp_buf, "{d:.2}", .{self.temperature}) catch "0.7";
|
||||
try string.appendSlice(allocator, temp_str);
|
||||
|
||||
if (self.max_tokens) |mt| {
|
||||
try string.appendSlice(allocator, ",\"max_tokens\":");
|
||||
var mt_buf: [16]u8 = undefined;
|
||||
const mt_str = std.fmt.bufPrint(&mt_buf, "{d}", .{mt}) catch "0";
|
||||
try string.appendSlice(allocator, mt_str);
|
||||
}
|
||||
try string.appendSlice(allocator, ",\"messages\":[");
|
||||
|
||||
for (self.messages, 0..) |msg, i| {
|
||||
if (i > 0) try string.append(allocator, ',');
|
||||
try string.appendSlice(allocator, "{\"role\":\"");
|
||||
try string.appendSlice(allocator, msg.role.toString());
|
||||
try string.appendSlice(allocator, "\",\"content\":\"");
|
||||
try appendEscaped(allocator, &string, msg.content);
|
||||
try string.appendSlice(allocator, "\"}");
|
||||
}
|
||||
|
||||
try string.appendSlice(allocator, "]}");
|
||||
return string.toOwnedSlice(allocator);
|
||||
}
|
||||
|
||||
pub fn fromJson(allocator: std.mem.Allocator, json: []const u8) !A2ARequest {
|
||||
const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
|
||||
defer parsed.deinit();
|
||||
|
||||
const root = parsed.value.object;
|
||||
|
||||
var request_id: [16]u8 = undefined;
|
||||
if (root.get("request_id")) |rid| {
|
||||
const hex = rid.string;
|
||||
if (hex.len == 32) {
|
||||
for (0..16) |i| {
|
||||
request_id[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const messages_arr = root.get("messages").?.array;
|
||||
const messages = try allocator.alloc(ChatMessage, messages_arr.items.len);
|
||||
for (messages_arr.items, 0..) |msg_val, i| {
|
||||
const msg_obj = msg_val.object;
|
||||
messages[i] = .{
|
||||
.role = Role.fromString(msg_obj.get("role").?.string) orelse .user,
|
||||
.content = try allocator.dupe(u8, msg_obj.get("content").?.string),
|
||||
};
|
||||
}
|
||||
|
||||
return .{
|
||||
.request_id = request_id,
|
||||
.model = try allocator.dupe(u8, root.get("model").?.string),
|
||||
.messages = messages,
|
||||
.temperature = if (root.get("temperature")) |t| @floatCast(t.float) else 0.7,
|
||||
.max_tokens = if (root.get("max_tokens")) |mt| @intCast(mt.integer) else null,
|
||||
.capability = try allocator.dupe(u8, if (root.get("capability")) |c| c.string else "chat"),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// A2A Response - wraps OpenAI chat completion response
|
||||
pub const A2AResponse = struct {
|
||||
request_id: [16]u8,
|
||||
success: bool,
|
||||
content: []const u8,
|
||||
error_message: ?[]const u8 = null,
|
||||
model: []const u8,
|
||||
tokens_used: ?u32 = null,
|
||||
agent_id: [32]u8 = [_]u8{0} ** 32,
|
||||
|
||||
pub fn toJson(self: *const A2AResponse, allocator: std.mem.Allocator) ![]u8 {
|
||||
var string: std.ArrayList(u8) = .{};
|
||||
errdefer string.deinit(allocator);
|
||||
|
||||
try string.appendSlice(allocator, "{\"request_id\":\"");
|
||||
try appendHex(allocator, &string, &self.request_id);
|
||||
try string.appendSlice(allocator, "\",\"success\":");
|
||||
try string.appendSlice(allocator, if (self.success) "true" else "false");
|
||||
try string.appendSlice(allocator, ",\"model\":\"");
|
||||
try appendEscaped(allocator, &string, self.model);
|
||||
try string.appendSlice(allocator, "\",\"content\":\"");
|
||||
try appendEscaped(allocator, &string, self.content);
|
||||
try string.append(allocator, '"');
|
||||
|
||||
if (self.error_message) |err| {
|
||||
try string.appendSlice(allocator, ",\"error\":\"");
|
||||
try appendEscaped(allocator, &string, err);
|
||||
try string.append(allocator, '"');
|
||||
}
|
||||
if (self.tokens_used) |t| {
|
||||
try string.appendSlice(allocator, ",\"tokens_used\":");
|
||||
var t_buf: [16]u8 = undefined;
|
||||
const t_str = std.fmt.bufPrint(&t_buf, "{d}", .{t}) catch "0";
|
||||
try string.appendSlice(allocator, t_str);
|
||||
}
|
||||
try string.appendSlice(allocator, ",\"agent_id\":\"");
|
||||
try appendHex(allocator, &string, self.agent_id[0..16]);
|
||||
try string.appendSlice(allocator, "\"}");
|
||||
|
||||
return string.toOwnedSlice(allocator);
|
||||
}
|
||||
|
||||
pub fn fromJson(allocator: std.mem.Allocator, json: []const u8) !A2AResponse {
|
||||
const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
|
||||
defer parsed.deinit();
|
||||
|
||||
const root = parsed.value.object;
|
||||
|
||||
var request_id: [16]u8 = undefined;
|
||||
if (root.get("request_id")) |rid| {
|
||||
const hex = rid.string;
|
||||
if (hex.len >= 32) {
|
||||
for (0..16) |i| {
|
||||
request_id[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var agent_id: [32]u8 = [_]u8{0} ** 32;
|
||||
if (root.get("agent_id")) |aid| {
|
||||
const hex = aid.string;
|
||||
const len = @min(hex.len / 2, 32);
|
||||
for (0..len) |i| {
|
||||
agent_id[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch 0;
|
||||
}
|
||||
}
|
||||
|
||||
return .{
|
||||
.request_id = request_id,
|
||||
.success = root.get("success").?.bool,
|
||||
.content = try allocator.dupe(u8, root.get("content").?.string),
|
||||
.error_message = if (root.get("error")) |e| try allocator.dupe(u8, e.string) else null,
|
||||
.model = try allocator.dupe(u8, root.get("model").?.string),
|
||||
.tokens_used = if (root.get("tokens_used")) |t| @intCast(t.integer) else null,
|
||||
.agent_id = agent_id,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// A2A message type byte (first byte of payload)
|
||||
pub const MessageType = enum(u8) {
|
||||
request = 0x01,
|
||||
response = 0x02,
|
||||
discover = 0x03,
|
||||
announce = 0x04,
|
||||
heartbeat = 0x05,
|
||||
};
|
||||
|
||||
/// Generate a random request ID
|
||||
pub fn generateRequestId() [16]u8 {
|
||||
var id: [16]u8 = undefined;
|
||||
std.crypto.random.bytes(&id);
|
||||
return id;
|
||||
}
|
||||
|
||||
// Helper: append hex string
|
||||
fn appendHex(allocator: std.mem.Allocator, list: *std.ArrayList(u8), bytes: []const u8) !void {
|
||||
const hex = "0123456789abcdef";
|
||||
for (bytes) |b| {
|
||||
try list.append(allocator, hex[b >> 4]);
|
||||
try list.append(allocator, hex[b & 0x0f]);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: append escaped JSON 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests
|
||||
test "request serialization roundtrip" {
|
||||
const allocator = std.testing.allocator;
|
||||
|
||||
const messages = [_]ChatMessage{
|
||||
.{ .role = .system, .content = "You are helpful." },
|
||||
.{ .role = .user, .content = "Hello!" },
|
||||
};
|
||||
|
||||
const req = A2ARequest{
|
||||
.request_id = generateRequestId(),
|
||||
.model = "llama3.2",
|
||||
.messages = &messages,
|
||||
.temperature = 0.8,
|
||||
};
|
||||
|
||||
const json = try req.toJson(allocator);
|
||||
defer allocator.free(json);
|
||||
|
||||
// Verify it's valid JSON
|
||||
const parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
|
||||
defer parsed.deinit();
|
||||
|
||||
try std.testing.expectEqualStrings("llama3.2", parsed.value.object.get("model").?.string);
|
||||
}
|
||||
Reference in New Issue
Block a user