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)


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

def binding
  @binding
end

Class Method Details

.http(url:, headers: {}, timeout: 30, persistent: false, 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., “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

  • persistent (Boolean) (defaults to: false)

    Whether to use persistent HTTP connections

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

    Optional override with any Transport instance, subclass, or shortcut

  • 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:



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

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

.jsonrpc(url:, headers: {}, timeout: 30, persistent: false, 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)
  • persistent (Boolean) (defaults to: false)
  • transport (LLM::Transport, Class, Symbol, nil) (defaults to: nil)

Returns:



120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/llm/a2a.rb', line 120

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

.rest(url:, headers: {}, timeout: 30, persistent: false, 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)
  • persistent (Boolean) (defaults to: false)
  • transport (LLM::Transport, Class, Symbol, nil) (defaults to: nil)

Returns:



99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/llm/a2a.rb', line 99

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

Instance Method Details

#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:



239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/llm/a2a.rb', line 239

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

#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:



144
145
146
147
# File 'lib/llm/a2a.rb', line 144

def card
  return @card if defined?(@card)
  @card = LLM::A2A::Card.new(transport.get("/.well-known/agent-card.json"))
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:



316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/llm/a2a.rb', line 316

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

#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:



377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/llm/a2a.rb', line 377

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:



393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/llm/a2a.rb', line 393

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

#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:



219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/llm/a2a.rb', line 219

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

#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:



334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/llm/a2a.rb', line 334

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

#inspectString

Returns:

  • (String)


409
410
411
# File 'lib/llm/a2a.rb', line 409

def inspect
  "#<#{LLM::Utils.object_id(self)} @binding=#{@binding.inspect}>"
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:



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/llm/a2a.rb', line 353

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

#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:



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/llm/a2a.rb', line 279

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

#notificationsLLM::A2A::Notifications

Returns push notification configuration operations.



173
174
175
# File 'lib/llm/a2a.rb', line 173

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:



185
186
187
188
189
190
191
192
193
# File 'lib/llm/a2a.rb', line 185

def send_message(text, configuration = {}, metadata: nil)
  body = build_request(
    "SendMessage",
    message: {role: "ROLE_USER", parts: [{text:}], messageId: SecureRandom.uuid},
    configuration:,
    metadata:
  )
  execute_request(body)
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:



204
205
206
207
208
209
210
211
# File 'lib/llm/a2a.rb', line 204

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

#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:



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

def skills
  @skills ||= card.skills.map { LLM::Tool.a2a(self, _1) }
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:



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/llm/a2a.rb', line 257

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

#tasksLLM::A2A::Tasks

Returns task-oriented A2A operations.

Returns:



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

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