> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portkey.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced code snippets and examples

> Advanced code snippets and examples for the Agent Gateway

> [!NOTE]
>
> Modify the API key permissions and turn on the **Agent Gateway** toggle for your API key. See the [Quickstart](https://docs.portkey.ai/docs/aigw/product/agent-gateway/quickstart.md) for where to configure this in the app. Make sure the `agents.invoke` scope is enabled.

## Introduction

The [Quickstart](https://docs.portkey.ai/docs/aigw/product/agent-gateway/quickstart.md) guide provides a basic example of how to use the Agent Gateway.

This guide provides more examples and code snippets to help you get started.

## Fetching the agent card

```shell cURL theme={"system"}
curl --location --request POST 'https://aigw.portkey.ai/agent/{agent-slug}/.well-known/agent.json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {PORTKEY_API_KEY}'
```

```python python theme={"system"}
import asyncio
import json

from a2a.client import A2ACardResolver
import httpx

BASE_URL = "https://aigw.portkey.ai/agent/{agent-slug}"
API_KEY = "{PORTKEY_API_KEY}"

async def log_httpx_request(request: httpx.Request) -> None:
    try:
        body = request.content.decode("utf-8") if request.content else "<empty>"
    except Exception:
        body = "<streaming or unreadable body>"
    print(f"[httpx] {request.method} {request.url}")
    print(f"[httpx] body: {body}\n")

async def main() -> None:
    print(f"Fetching agent card from {BASE_URL}...")
    async with httpx.AsyncClient(
        base_url=BASE_URL,
        headers={"Authorization": f"Bearer {API_KEY}"},
        event_hooks={"request": [log_httpx_request]},
    ) as client:
        resolver = A2ACardResolver(httpx_client=client, base_url=BASE_URL)
        agent_card = await resolver.get_agent_card()
        print(json.dumps(agent_card.model_dump(mode="json", exclude_none=True), indent=2))

if __name__ == "__main__":
    asyncio.run(main())
```

```javascript JavaScript theme={"system"}
import {
  DefaultAgentCardResolver,
  ClientFactory,
  ClientFactoryOptions,
} from "@a2a-js/sdk/client";

const BASE_URL = "https://aigw.portkey.ai/agent/{agent-slug}";
const API_KEY = "{PORTKEY_API_KEY}";

class HeaderAuthInterceptor {
  async before(args) {
    args.options = {
      ...args.options,
      serviceParameters: {
        ...(args.options?.serviceParameters || {}),
        "Authorization": `Bearer ${API_KEY}`,
      },
    };
  }

  async after() {}
}

function createAuthenticatedFetch() {
  return async (input, init = {}) => {
    const headers = new Headers(init.headers || {});
    headers.set("Authorization", `Bearer ${API_KEY}`);
    return fetch(input, { ...init, headers });
  };
}

async function main() {
  console.log(`Fetching agent card from ${BASE_URL}...`);

  const authFetch = createAuthenticatedFetch();
  const resolverBaseUrl = BASE_URL.endsWith("/") ? BASE_URL : `${BASE_URL}/`;

  const options = ClientFactoryOptions.createFrom(
    ClientFactoryOptions.default,
    {
      cardResolver: new DefaultAgentCardResolver({
        fetchImpl: authFetch,
      }),
      clientConfig: { interceptors: [new HeaderAuthInterceptor()] },
    },
  );

  const factory = new ClientFactory(options);
  const client = await factory.createFromUrl(resolverBaseUrl);

  const card = client.agentCard;

  if (!card) {
    throw new Error("Unable to read agent card from SDK client instance.");
  }

  console.log(JSON.stringify(card, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
```

## Invoking the agent

### JSON-RPC examples

```shell cURL theme={"system"}
curl --location 'https://aigw.portkey.ai/agent/{agent-slug}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {PORTKEY_API_KEY}' \
--data '{
    "jsonrpc": "2.0",
    "id": "req-1",
    "method": "tasks/send",
    "params": {
        "id": "task-header-1",
        "message": {
            "role": "user",
            "parts": [
                {
                    "type": "text",
                    "text": "echo Hello from header auth"
                }
            ]
        }
    }
}'
```

```python python theme={"system"}
import asyncio
import json
from uuid import uuid4

import httpx

BASE_URL = "https://aigw.portkey.ai/agent/header-based-authentication"
API_KEY = "+/gW5Oclr7Y9z01jEOVBaAfKZxfz"

async def log_httpx_request(request: httpx.Request) -> None:
    try:
        body = request.content.decode("utf-8") if request.content else "<empty>"
    except Exception:
        body = "<streaming or unreadable body>"
    print(f"[httpx] {request.method} {request.url}")
    print(f"[httpx] body: {body}\n")

async def main() -> None:
    print(f"Connecting to A2A agent at {BASE_URL}...")
    message_text = "echo Hello from header auth"
    task_id = f"task-{uuid4().hex[:12]}"
    request_id = f"req-{uuid4().hex[:8]}"
    payload = {
        "jsonrpc": "2.0",
        "id": request_id,
        "method": "tasks/send",
        "params": {
            "id": task_id,
            "message": {
                "role": "user",
                "parts": [
                    {
                        "type": "text",
                        "text": message_text,
                    }
                ],
            },
        },
    }

    async with httpx.AsyncClient(
        base_url=BASE_URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        event_hooks={"request": [log_httpx_request]},
    ) as httpx_client:
        print(f"Sending task with message: {message_text}")
        response = await httpx_client.post("", json=payload)
        response.raise_for_status()
        print(json.dumps(response.json(), indent=2))

if __name__ == "__main__":
    asyncio.run(main())
```

```javascript JavaScript theme={"system"}
const BASE_URL =
  process.env.BASE_URL || "https://aigw.portkey.ai/agent/{agent-slug}";
const API_KEY = process.env.API_KEY || "{PORTKEY_API_KEY}";
const MESSAGE_TEXT = process.env.MESSAGE_TEXT || "echo Hello from header auth";

async function main() {
  console.log(`Connecting to A2A agent at ${BASE_URL}...`);
  console.log(`Sending task with message: ${MESSAGE_TEXT}`);

  const payload = {
    jsonrpc: "2.0",
    id: `req-${crypto.randomUUID().slice(0, 8)}`,
    method: "tasks/send",
    params: {
      id: `task-${crypto.randomUUID().slice(0, 12)}`,
      message: {
        role: "user",
        parts: [{ type: "text", text: MESSAGE_TEXT }],
      },
    },
  };

  const response = await fetch(BASE_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${API_KEY}`,
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(
      `HTTP ${response.status}: ${response.statusText} while calling tasks/send`,
    );
  }

  const result = await response.json();
  console.log(JSON.stringify(result, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
```

## Further reading

> **[Quickstart](https://docs.portkey.ai/docs/aigw/product/agent-gateway/quickstart.md)**
>
> Get started with the Agent Gateway by registering your first agent.

> **[Agent Registry](https://docs.portkey.ai/docs/aigw/product/agent-gateway/registry.md)**
>
> Manage your agent integrations and control access to agents and their skills.

> **[Agent Servers](https://docs.portkey.ai/docs/aigw/product/agent-gateway/servers.md)**
>
> Learn how virtual agent servers work and how to host your own.


## Related topics

- [Agent Gateway](https://docs.portkey.ai/docs/aigw/product/agent-gateway.md)
- [Agent Servers](https://docs.portkey.ai/docs/aigw/product/agent-gateway/servers.md)
- [Quickstart](https://docs.portkey.ai/docs/aigw/product/agent-gateway/quickstart.md)
- [Agent Catalog](https://docs.portkey.ai/docs/aigw/product/catalogs/agents.md)
- [Mistral AI](https://docs.portkey.ai/docs/aigw/integrations/llms/mistral-ai.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.