267 lines
9.4 KiB
Zig
267 lines
9.4 KiB
Zig
//! 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);
|
|
}
|