Class: LLM::A2A

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/a2a.rb,
lib/llm/a2a/card.rb,
lib/llm/a2a/error.rb,
lib/llm/a2a/tasks.rb,
lib/llm/a2a/notifications.rb,
lib/llm/a2a/transport/http.rb

Overview

The A2A class provides access to agents that implement the Agent2Agent (A2A) Protocol. A2A defines a standard way for independent AI agents to discover each other's capabilities, negotiate interaction modalities, and collaborate on tasks.

In llm.rb, A2A supports both HTTP+JSON/REST and JSON-RPC 2.0 protocol bindings and focuses on discovering agent skills that can be used through Context and Agent.

Requests can be made concurrently and responses are matched by task id.

Examples:

REST binding (default)

a2a = LLM::A2A.rest(url: "https://agent.example.com")
card = a2a.card
puts card.skills.map(&:name)
task = a2a.send_message("What is the weather in Tokyo?").task
a2a.tasks.get(task.id)

JSON-RPC binding

a2a = LLM::A2A.jsonrpc(url: "https://agent.example.com")

Using skills as tools in a context

llm = LLM.openai(key: ENV["KEY"])
a2a = LLM::A2A.rest(url: "https://agent.example.com")
ctx = LLM::Context.new(llm, tools: a2a.skills)
ctx.talk("Analyze this data using the remote agent.")
ctx.talk(ctx.wait(:call)) while ctx.functions?

Defined Under Namespace

Modules: Transport Classes: Card, Notifications, Tasks

Constant Summary collapse

Error =

Generic A2A protocol error.

Class.new(LLM::Error) do
  ##
  # @return [Integer, nil]
  attr_reader :code

  ##
  # @return [Object, nil]
  attr_reader :data

  ##
  # @param [String] message
  # @param [Integer, nil] code
  # @param [Object, nil] data
  def initialize(message, code = nil, data = nil)
    super(message)
    @code = code
    @data = data
  end
end
AgentCardError =

Raised when the agent card cannot be fetched or parsed.

Class.new(Error)
TaskNotFoundError =

Raised when a task is not found.

Class.new(Error)
TaskNotCancelableError =

Raised when a task cannot be cancelled.

Class.new(Error)
UnsupportedOperationError =

Raised when the agent does not support the requested operation.

Class.new(Error)
ContentTypeNotSupportedError =

Raised when a content type is not supported.

Class.new(Error)
VersionNotSupportedError =

Raised when the A2A protocol version is not supported.

Class.new(Error)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(transport:, binding: :rest, base_path: "", protocol_version: "1.0") ⇒ LLM::A2A

Parameters:

  • binding (Symbol) (defaults to: :rest)

    The protocol binding to use. One of :rest (HTTP+JSON/REST) or :jsonrpc (JSON-RPC 2.0). Defaults to :rest.

  • transport (Object)

    The transport used to communicate with the remote A2A agent

  • base_path (String) (defaults to: "")

    Optional base path prefix for REST endpoints

  • protocol_version (String) (defaults to: "1.0")

    The expected A2A protocol version. Defaults to "1.0".



49
50
51
52
53
54
# File 'lib/llm/a2a.rb', line 49

def initialize(transport:, binding: :rest, base_path: "", protocol_version: "1.0")
  @binding = binding
  @base_path = LLM::Utils.normalize_base_path(base_path)
  @protocol_version = protocol_version
  @transport = transport
end

Instance Attribute Details

#bindingSymbol (readonly)

Returns the active protocol binding.

Returns:

  • (Symbol)


129
130
131
# File 'lib/llm/a2a.rb', line 129

def binding
  @binding
end

Class Method Details

.http(url:, headers: {}, timeout: 30, transport: nil, binding: :rest, base_path: "", protocol_version: "1.0") ⇒ LLM::A2A

Builds an A2A client over HTTP.

Parameters:

  • url (String)

    The base URL of the A2A agent (e.g., "https://agent.example.com")

  • headers (Hash<String, String>) (defaults to: {})

    Extra HTTP headers to include in requests (e.g., Authorization)

  • timeout (Integer, nil) (defaults to: 30)

    The timeout in seconds for HTTP requests

  • transport (LLM::Transport, Class, nil) (defaults to: nil)

    Optional override with any Transport instance or subclass

  • binding (Symbol) (defaults to: :rest)

    The protocol binding to use. One of :rest or :jsonrpc

  • base_path (String) (defaults to: "")

    Optional base path prefix for REST endpoints

  • protocol_version (String) (defaults to: "1.0")

    The expected A2A protocol version. Defaults to "1.0".

Returns:



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/llm/a2a.rb', line 73

def self.http(url:, headers: {}, timeout: 30, transport: nil, binding: :rest, base_path: "", protocol_version: "1.0")
  new(
    binding:,
    base_path:,
    protocol_version:,
    transport: Transport::HTTP.new(
      url:,
      headers:,
      timeout:,
      transport:,
      protocol_version:
    )
  )
end

.rest(url:, headers: {}, timeout: 30, transport: nil, base_path: "", protocol_version: "1.0") ⇒ LLM::A2A

Builds an A2A client over HTTP+JSON/REST.

Parameters:

  • url (String)
  • headers (Hash<String, String>) (defaults to: {})
  • timeout (Integer, nil) (defaults to: 30)
  • transport (LLM::Transport, Class, nil) (defaults to: nil)

Returns:



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/llm/a2a.rb', line 95

def self.rest(url:, headers: {}, timeout: 30, transport: nil, base_path: "", protocol_version: "1.0")
  http(
    url:,
    headers:,
    timeout:,
    transport:,
    binding: :rest,
    base_path:,
    protocol_version:
  )
end

.jsonrpc(url:, headers: {}, timeout: 30, transport: nil, base_path: "", protocol_version: "1.0") ⇒ LLM::A2A

Builds an A2A client over HTTP+JSON with JSON-RPC 2.0.

Parameters:

  • url (String)
  • headers (Hash<String, String>) (defaults to: {})
  • timeout (Integer, nil) (defaults to: 30)
  • transport (LLM::Transport, Class, nil) (defaults to: nil)

Returns:



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/llm/a2a.rb', line 114

def self.jsonrpc(url:, headers: {}, timeout: 30, transport: nil, base_path: "", protocol_version: "1.0")
  http(
    url:,
    headers:,
    timeout:,
    transport:,
    binding: :jsonrpc,
    base_path:,
    protocol_version:
  )
end

Instance Method Details

#inspectString

Returns:

  • (String)


399
400
401
# File 'lib/llm/a2a.rb', line 399

def inspect
  "#<#{LLM::Utils.object_id(self)} @binding=#{@binding.inspect}>"
end

#cardLLM::A2A::Card Also known as: agent_card

Returns the remote agent card.

The agent card is fetched from /.well-known/agent-card.json and cached for the lifetime of this client instance.

Returns:



137
138
139
140
# File 'lib/llm/a2a.rb', line 137

def card
  return @card if defined?(@card)
  @card = LLM::A2A::Card.new(transport.get("/.well-known/agent-card.json"))
end

#skillsArray<Class<LLM::Tool>> Also known as: tools

Returns the agent's skills adapted as callable tools.

Each skill in the agent card is mapped to an Tool subclass that wraps a #send_message call. When the tool is called, it sends a message to the remote agent and returns the task artifacts as the result.

Returns:



151
152
153
# File 'lib/llm/a2a.rb', line 151

def skills
  @skills ||= card.skills.map { LLM::Tool.a2a(self, _1) }
end

#tasksLLM::A2A::Tasks

Returns task-oriented A2A operations.

Returns:



159
160
161
# File 'lib/llm/a2a.rb', line 159

def tasks
  @tasks ||= LLM::A2A::Tasks.new(self)
end

#notificationsLLM::A2A::Notifications

Returns push notification configuration operations.



166
167
168
# File 'lib/llm/a2a.rb', line 166

def notifications
  @notifications ||= LLM::A2A::Notifications.new(self)
end

#send_message(text, configuration = {}, metadata: nil) ⇒ LLM::Object

Sends a message to the agent and returns the response.

Parameters:

  • text (String)

    The message text to send

  • config (Hash)

    Optional configuration (accepted_output_modes, return_immediately)

  • metadata (Hash, nil) (defaults to: nil)

    Optional metadata to attach to the request

Returns:



178
179
180
181
182
183
184
185
# File 'lib/llm/a2a.rb', line 178

def send_message(text, configuration = {}, metadata: nil)
  body = build_request("SendMessage",
    message: {role: "ROLE_USER", parts: [{text:}], messageId: SecureRandom.uuid},
    configuration:,
    metadata:)
  res = execute_request(body)
  LLM::Object.from(res)
end

#send_streaming_message(text, configuration = {}) {|event| ... } ⇒ void

This method returns an undefined value.

Sends a streaming message to the agent.

The block is called for each Object event in the stream (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent).

Parameters:

  • text (String)

    The message text to send

  • config (Hash)

    Optional configuration

Yield Parameters:



196
197
198
199
200
201
# File 'lib/llm/a2a.rb', line 196

def send_streaming_message(text, configuration = {}, &on_event)
  body = build_request("SendStreamingMessage",
    message: {role: "ROLE_USER", parts: [{text:}], messageId: SecureRandom.uuid},
    configuration:)
  execute_stream(body, &on_event)
end

#get_task(task_id, history_length: nil) ⇒ LLM::Object

Gets the current state of a task.

Parameters:

  • task_id (String)

    The task ID to retrieve

  • history_length (Integer, nil) (defaults to: nil)

    Optional limit on recent messages to include

Returns:



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/llm/a2a.rb', line 209

def get_task(task_id, history_length: nil)
  case @binding
  when :rest
    path = rest_path("/tasks/#{task_id}")
    path = "#{path}?historyLength=#{history_length}" if history_length
    res = transport.get(path)
  when :jsonrpc
    body = build_request("GetTask", id: task_id, historyLength: history_length)
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#cancel_task(task_id, metadata: nil) ⇒ LLM::Object

Cancels a task in progress.

Parameters:

  • task_id (String)

    The task ID to cancel

  • metadata (Hash, nil) (defaults to: nil)

    Optional metadata to attach to the request

Returns:



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/llm/a2a.rb', line 229

def cancel_task(task_id, metadata: nil)
  body = build_request("CancelTask", id: task_id, metadata:)
  case @binding
  when :rest
    res = transport.post(rest_path("/tasks/#{task_id}:cancel"), body)
  when :jsonrpc
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#subscribe_to_task(task_id) {|event| ... } ⇒ void

This method returns an undefined value.

Subscribes to streaming updates for an existing task.

Parameters:

  • task_id (String)

    The task ID to subscribe to

Yield Parameters:



247
248
249
250
251
252
253
254
255
256
257
# File 'lib/llm/a2a.rb', line 247

def subscribe_to_task(task_id, &on_event)
  case @binding
  when :rest
    transport.get_stream(rest_path("/tasks/#{task_id}:subscribe"), &on_event)
  when :jsonrpc
    body = build_request("SubscribeToTask", id: task_id)
    transport.post_stream("/", body, &on_event)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
end

#list_tasks(context_id: nil, status: nil, history_length: nil, status_timestamp_after: nil, include_artifacts: nil, page_size: 20, page_token: nil) ⇒ LLM::Object

Lists tasks with optional filtering.

Parameters:

  • context_id (String, nil) (defaults to: nil)

    Optional context ID to filter by

  • status (String, nil) (defaults to: nil)

    Optional task state to filter by

  • history_length (Integer, nil) (defaults to: nil)

    Optional limit on recent messages to include

  • status_timestamp_after (String, nil) (defaults to: nil)

    Optional lower bound for status timestamp filtering

  • include_artifacts (Boolean, nil) (defaults to: nil)

    Whether to include task artifacts

  • page_size (Integer) (defaults to: 20)

    Maximum number of tasks to return

  • page_token (String, nil) (defaults to: nil)

    Pagination cursor

Returns:



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/llm/a2a.rb', line 269

def list_tasks(context_id: nil, status: nil, history_length: nil, status_timestamp_after: nil,
               include_artifacts: nil, page_size: 20, page_token: nil)
  case @binding
  when :rest
    params = {}
    params[:contextId] = context_id if context_id
    params[:status] = status if status
    params[:historyLength] = history_length if history_length
    params[:statusTimestampAfter] = status_timestamp_after if status_timestamp_after
    params[:includeArtifacts] = include_artifacts unless include_artifacts.nil?
    params[:pageSize] = page_size if page_size
    params[:pageToken] = page_token if page_token
    query = URI.encode_www_form(params)
    path = rest_path("/tasks")
    path = "#{path}?#{query}" unless query.empty?
    res = transport.get(path)
  when :jsonrpc
    body = build_request("ListTasks", contextId: context_id, status: status,
                                      historyLength: history_length,
                                      statusTimestampAfter: status_timestamp_after,
                                      includeArtifacts: include_artifacts,
                                      pageSize: page_size, pageToken: page_token)
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#create_task_push_notification_config(task_id, url:, token: nil, authentication: nil, id: nil) ⇒ LLM::Object

Creates a push notification configuration for a task.

Parameters:

  • task_id (String)

    The parent task ID

  • url (String)

    The callback URL

  • token (String, nil) (defaults to: nil)

    Optional token to include with notifications

  • authentication (Hash, nil) (defaults to: nil)

    Optional authentication information

  • id (String, nil) (defaults to: nil)

    Optional configuration ID

Returns:



306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/llm/a2a.rb', line 306

def create_task_push_notification_config(task_id, url:, token: nil, authentication: nil, id: nil)
  body = build_request("CreateTaskPushNotificationConfig", taskId: task_id, url:, token:, authentication:, id:)
  case @binding
  when :rest
    res = transport.post(rest_path("/tasks/#{task_id}/pushNotificationConfigs"), body)
  when :jsonrpc
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#get_task_push_notification_config(task_id, id) ⇒ LLM::Object

Retrieves a push notification configuration for a task.

Parameters:

  • task_id (String)

    The parent task ID

  • id (String)

    The configuration ID

Returns:



324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/llm/a2a.rb', line 324

def get_task_push_notification_config(task_id, id)
  case @binding
  when :rest
    res = transport.get(rest_path("/tasks/#{task_id}/pushNotificationConfigs/#{id}"))
  when :jsonrpc
    body = build_request("GetTaskPushNotificationConfig", taskId: task_id, id:)
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#list_task_push_notification_configs(task_id, page_size: nil, page_token: nil) ⇒ LLM::Object

Lists push notification configurations for a task.

Parameters:

  • task_id (String)

    The parent task ID

  • page_size (Integer, nil) (defaults to: nil)

    Maximum number of configurations to return

  • page_token (String, nil) (defaults to: nil)

    Pagination cursor

Returns:



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/llm/a2a.rb', line 343

def list_task_push_notification_configs(task_id, page_size: nil, page_token: nil)
  case @binding
  when :rest
    params = {}
    params[:pageSize] = page_size if page_size
    params[:pageToken] = page_token if page_token
    query = URI.encode_www_form(params)
    path = rest_path("/tasks/#{task_id}/pushNotificationConfigs")
    path = "#{path}?#{query}" unless query.empty?
    res = transport.get(path)
  when :jsonrpc
    body = build_request("ListTaskPushNotificationConfigs", taskId: task_id, pageSize: page_size, pageToken: page_token)
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#delete_task_push_notification_config(task_id, id) ⇒ LLM::Object

Deletes a push notification configuration for a task.

Parameters:

  • task_id (String)

    The parent task ID

  • id (String)

    The configuration ID

Returns:



367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/llm/a2a.rb', line 367

def delete_task_push_notification_config(task_id, id)
  case @binding
  when :rest
    res = transport.delete(rest_path("/tasks/#{task_id}/pushNotificationConfigs/#{id}"))
  when :jsonrpc
    body = build_request("DeleteTaskPushNotificationConfig", taskId: task_id, id:)
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::Object.from(res)
end

#extended_cardLLM::A2A::Card Also known as: get_extended_agent_card

Returns the authenticated extended agent card.

Returns:



383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/llm/a2a.rb', line 383

def extended_card
  case @binding
  when :rest
    res = transport.get(rest_path("/extendedAgentCard"))
  when :jsonrpc
    body = build_request("GetExtendedAgentCard")
    res = transport.post("/", body)
  else
    raise LLM::A2A::Error, "Invalid A2A binding: #{@binding.inspect}"
  end
  LLM::A2A::Card.new(res)
end