Agent Protocol

repository·main·Indexed 20 days ago

https://github.com/langchain-ai/agent-protocol

A standardized, framework-agnostic API specification for serving LLM agents in production. It provides a unified way to handle runs (ephemeral and background), multi-turn threads for stateful interactions, long-term memory via a Store API, and real-time streaming. The protocol includes the ap-client Python package (v1.0.0) for interacting with Agent Protocol servers.

Tokens
43.5K
Snippets
116
Records
168
Agent score
70%

What's inside Agent Protocol

  1. What is included in langchain-protocol

    main

    The langchain-protocol package includes the following for Python developers:

    • TypedDict definitions for commands, events, results, and payload shapes.
    • Literal and union aliases for protocol enums and tagged unions.
    • A py.typed marker to ensure type checkers (like mypy) recognize the bundled annotations.
  2. Overview of Agent Protocol

    main

    Agent Protocol is a framework-agnostic API specification designed to serve LLM agents in production. It provides a standardized way to manage agent lifecycles, multi-turn conversations, and long-term memory. The protocol is centered around three core pillars:

    1. Runs: APIs for executing an agent (both ephemeral and background).
    2. Threads: APIs to organize and manage multi-turn, stateful interactions.
    3. Store: APIs for managing long-term memory across different scopes (users, threads, etc.).

    Implementations like LangGraph Platform use a superset of this protocol.

  3. Overview of the Agent Streaming Protocol

    main

    The Agent Streaming Protocol is a thread-centric event and command protocol designed for observing and controlling long-running agent executions. It is built to support multiple transport models (SSE/HTTP, WebSocket, in-process) and allows clients to subscribe to specific data streams using channels and namespaces.

    Core Primitives:

    • Threads: The durable routing key for commands, events, state, and history.
    • Connections: Ephemeral transport scopes (e.g., an SSE connection).
    • Channels: Partition the event stream by concern (e.g., messages, tools, lifecycle).
    • Namespaces: Path-based identifiers (e.g., ['supervisor', 'worker_a']) used to subscribe to specific parts of an agent or graph tree.
    • Content Blocks: The universal carrier for model output (text, reasoning, tool calls, etc.) using explicit append/merge semantics.
    • Events: Carry explicit lifecycle boundaries so clients don't have to infer when a process starts or finishes.
    • Replay: Sequence-based mechanism allowing clients to reconnect and request missed events via sequence numbers.
  4. How the Store manages long-term memory

    main

    The Store provides APIs for agents to access long-term memory across different scopes (e.g., user, thread, assistant, or company). It supports both simple text and structured data.

    Key Capabilities:

    • Scoped Memory: Store and retrieve memory against specific namespaces and keys.
    • Search: List or search memory items based on namespace, content, or time.

    Key Endpoints:

    • PUT /store/items: Create or update a memory item at a specific namespace and key.
    • GET /store/items: Retrieve a memory item.
    • DELETE /store/items: Delete a memory item.
    • POST /store/items/search: Search for memory items.
    • POST /store/namespaces: List available namespaces.
  5. How Stateless Runs work

    main

    Stateless runs are used for one-shot, ephemeral interactions where you do not need to persist the thread's state after the execution concludes. This is ideal for simple request-response patterns.

    Key endpoints for stateless interactions:

    • POST /runs/wait: Creates an ephemeral run and blocks until the final output is produced, returning it in the response.
    • POST /runs/stream: Creates an ephemeral run and streams the output as it is generated.
  6. How Agent Introspection works

    main

    Introspection endpoints allow clients to discover the capabilities of an agent before execution. This is useful for determining what inputs an agent accepts and what its output structure looks like.

    Key Endpoints:

    • POST /agents/search: List agents, optionally filtered by name or metadata.
    • GET /agents/{agent_id}: Get basic info (name, description, metadata).
    • GET /agents/{agent_id}/schemas: Retrieve the JSON Schemas for the agent's input, output, state, and config.
  7. Handle Replay and Reconnection in Agent Streaming

    main

    To ensure reliability during network interruptions, the protocol supports event replay using sequence numbers. Servers may maintain a ring buffer of recent events per thread to allow clients to recover missed data.

    • SSE Clients: Include the since parameter in an EventStreamRequest to request events starting from a specific sequence number.
    • WebSocket Clients: Call subscription.reconnect providing the lastEventId and a list of the subscriptions you wish to restore.

    Behavioral Note: The server will replay buffered events matching the requested point and then switch to live delivery. If the requested event is no longer in the server's buffer, the server will report that events were missed, at which point the client should perform a full resync using state commands.

  8. Understand the AgentSchema structure

    main

    The AgentSchema defines the structural properties and data contracts of an agent. It uses JSON Schema format to specify the expected shapes for inputs, outputs, internal state, and configuration. This allows clients to validate interactions with the agent before execution.

    ## Properties
    
    | Name | Type | Description |
    | :--- | :--- | :--- |
    | **agent_id** | **str** | The ID of the agent. |
    | **input_schema** | **object** | The schema for the agent input (JSON Schema format). |
    | **output_schema** | **object** | The schema for the agent output (JSON Schema format). |
    | **state_schema** | **object** | The schema for the agent's internal state (JSON Schema format). [optional] |
    | **config_schema** | **object** | The schema for the agent config (JSON Schema format). [optional] |
  9. Understand Top-Level Message Framing

    main

    The protocol uses a consistent framing for all messages.

    Client Commands: Clients send commands containing an id, a method, and params.

    {
      "id": 1,
      "method": "run.start",
      "params": {
        "assistantId": "agent",
        "input": {
          "messages": [{ "role": "user", "content": "Hello" }]
        }
      }
    }

    Server Responses:

    • Success: Includes the original command id and a result object.
    • Error: Includes the original command id and an error code/message.

    Server Events: Unsolicited pushes that include an eventId (for SSE reconnection) and a seq (monotonic sequence number for ordering/replay).

    {
      "type": "event",
      "eventId": "evt_123",
      "seq": 43,
      "method": "messages",
      "params": {
        "namespace": [],
        "timestamp": 1710000000000,
        "data": {
          "event": "message-start",
          "role": "ai",
          "id": "msg_123"
        }
      }
    }
    {
      "id": 1,
      "method": "run.start",
      "params": {
        "assistantId": "agent",
        "input": {
          "messages": [{ "role": "user", "content": "Hello" }]
        }
      }
    }
  10. How Streaming Primitives work

    main

    Agent Protocol defines a thread-centric streaming protocol for observing and controlling live agent executions. It supports various transport methods and complex event types.

    Streaming Capabilities:

    • Transport: Supports Server-Sent Events (SSE) for filtered subscriptions and WebSockets for bidirectional communication.
    • Observability: Provides primitives for tool lifecycle events, run lifecycle events, human-in-the-loop input, state snapshots, and content-block message deltas.
    • Control: Allows sending commands (e.g., via WebSocket in-band or via HTTP sidecar for SSE) to interact with a running agent.

    Key Endpoints:

    • POST /threads/{thread_id}/stream: Open a filtered SSE stream. The request body allows selecting channels, namespace prefixes, depth, and replay position.
    • GET /threads/{thread_id}/stream: Upgrade to a WebSocket connection for bidirectional streaming.
    • POST /threads/{thread_id}/commands: Send a command over HTTP for SSE clients (WebSocket clients use the connection directly).
  11. Understand AgentCapabilities properties

    main

    The AgentCapabilities model describes which protocol features an agent supports. Capabilities are categorized into standard protocol features (prefixed with ap.) and custom capabilities (using reverse domain notation, e.g., com.example.some.capability).

    Standard properties include:

    • ap_io_messages (bool, optional): Indicates if the agent supports Messages as input, output, or state. When true, the agent utilizes the messages key in threads and runs endpoints.
    • ap_io_streaming (bool, optional): Indicates if the agent supports streaming output.