Code Examples

Complete, runnable examples for integrating with Relex A2A.

Python Example

A minimal agent that registers with Relex and sends a case analysis request.

import httpx
import json
import time
import uuid

BASE_URL = "https://relex.you"

class RelexClient:
    """Minimal Relex A2A client."""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.token = None
        self.expires_at = 0

    def _ensure_token(self):
        """Exchange API key for bearer token, with caching."""
        if self.token and time.time() < self.expires_at - 300:
            return
        resp = httpx.post(
            f"{BASE_URL}/v1/auth/token",
            json={"api_key": self.api_key},
        )
        resp.raise_for_status()
        data = resp.json()
        self.token = data["bearer_token"]
        self.expires_at = data["expires_at"]

    def _headers(self) -> dict:
        self._ensure_token()
        return {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json",
        }

    def create_case(self, title: str, description: str) -> dict:
        """Create a new legal case."""
        resp = httpx.post(
            f"{BASE_URL}/v1/cases",
            headers=self._headers(),
            json={"title": title, "description": description},
        )
        resp.raise_for_status()
        return resp.json()

    def send_to_agent(
        self,
        case_id: str,
        prompt: str,
        request_type: str = "eval_req",
    ):
        """Send a prompt to the Relex agent and stream the response."""
        session_id = str(uuid.uuid4())
        phase_id = str(uuid.uuid4())

        with httpx.stream(
            "POST",
            f"{BASE_URL}/v1/agent",
            headers=self._headers(),
            json={
                "sessionId": session_id,
                "seedPhase": {"phaseId": phase_id},
                "containerId": case_id,
                "containerType": "case",
                "requestType": request_type,
                "prompt": prompt,
            },
            timeout=120.0,
        ) as response:
            response.raise_for_status()
            for line in response.iter_lines():
                if line.startswith("data: "):
                    data = json.loads(line[6:])
                    yield data
                elif line.startswith("event: "):
                    event_type = line[7:]
                    # You can filter by event type here


# Usage
if __name__ == "__main__":
    client = RelexClient(api_key="rlx_sk_your_api_key")

    # Create a case
    case = client.create_case(
        title="Employment Contract Review",
        description="Review a standard employment contract for a German company",
    )
    print(f"Created case: {case['caseId']}")

    # Send to agent for evaluation
    print("\nAgent response:")
    for event in client.send_to_agent(
        case_id=case["caseId"],
        prompt="Please evaluate this employment contract case.",
        request_type="eval_req",
    ):
        if "text" in event:
            print(event["text"], end="", flush=True)
        elif "response" in event:
            print(f"\n\nFull response: {event['response'][:200]}...")
    print()

JavaScript / TypeScript Example

const BASE_URL = "https://relex.you";

class RelexClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.token = null;
    this.expiresAt = 0;
  }

  async ensureToken() {
    if (this.token && Date.now() / 1000 < this.expiresAt - 300) return;

    const resp = await fetch(`${BASE_URL}/v1/auth/token`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ api_key: this.apiKey }),
    });
    const data = await resp.json();
    this.token = data.bearer_token;
    this.expiresAt = data.expires_at;
  }

  async headers() {
    await this.ensureToken();
    return {
      Authorization: `Bearer ${this.token}`,
      "Content-Type": "application/json",
    };
  }

  async createCase(title, description) {
    const resp = await fetch(`${BASE_URL}/v1/cases`, {
      method: "POST",
      headers: await this.headers(),
      body: JSON.stringify({ title, description }),
    });
    return resp.json();
  }

  async *sendToAgent(caseId, prompt, requestType = "eval_req") {
    const sessionId = crypto.randomUUID();
    const phaseId = crypto.randomUUID();

    const resp = await fetch(`${BASE_URL}/v1/agent`, {
      method: "POST",
      headers: await this.headers(),
      body: JSON.stringify({
        sessionId,
        seedPhase: { phaseId },
        containerId: caseId,
        containerType: "case",
        requestType,
        prompt,
      }),
    });

    const reader = resp.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          try {
            yield JSON.parse(line.slice(6));
          } catch {
            // skip malformed lines
          }
        }
      }
    }
  }
}

// Usage
async function main() {
  const client = new RelexClient("rlx_sk_your_api_key");

  const caseData = await client.createCase(
    "Contract Review",
    "Review a SaaS subscription agreement"
  );
  console.log("Created case:", caseData.caseId);

  for await (const event of client.sendToAgent(
    caseData.caseId,
    "Please evaluate this contract review case.",
    "eval_req"
  )) {
    if (event.text) process.stdout.write(event.text);
    if (event.response) console.log("\nResponse:", event.response.slice(0, 200));
  }
}

main().catch(console.error);

Agent Registration Example (Python)

Complete flow for registering your agent with Relex:

import httpx

BASE_URL = "https://relex.you"

def register_agent(
    user_firebase_token: str,
    your_agent_card_url: str,
) -> dict:
    """Complete agent registration flow."""

    # Step 1: Generate registration token
    resp = httpx.post(
        f"{BASE_URL}/v1/agents/registration-token",
        headers={"Authorization": f"Bearer {user_firebase_token}"},
    )
    resp.raise_for_status()
    reg_token = resp.json()["registration_token"]
    print(f"Got registration token (expires in 10 min)")

    # Step 2: Register your agent
    resp = httpx.post(
        f"{BASE_URL}/v1/agents/register",
        json={
            "registration_token": reg_token,
            "agent_card_url": your_agent_card_url,
        },
    )
    resp.raise_for_status()
    result = resp.json()

    print(f"Agent registered: {result['name']}")
    print(f"Agent ID: {result['agent_id']}")
    print(f"API Key: {result['shared_api_key']}")
    print("SAVE THIS API KEY — it will not be shown again!")

    return result