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

# Endpoints (Python)

> Programmatic access to PraisonAI recipe endpoints using Python and HTTP

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="endpoint-agent", instructions="Route requests to the right LLM endpoint.")
agent.start("Send this request to the OpenAI-compatible endpoint.")
```

Run recipe endpoints from Python or any HTTP client — list recipes, execute runs, and stream progress.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai import recipe

result = recipe.run(
    "my-recipe",
    input={"query": "Hello, world!"},
    options={"timeout_sec": 60},
)
print(result.output if result.ok else result.error)
```

The user names a recipe and input; `recipe.run` or HTTP returns structured output or streaming progress.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Client[📋 Client] --> SDK[🔌 recipe.run / HTTP]
    SDK --> Server[🚀 Endpoint server]
    Server --> Agent[🧠 Recipe agent]
    Agent --> Out[✅ RecipeResult]

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class Client input
    class SDK process
    class Server,Agent agent
    class Out output

    classDef tool fill:#189AB4,color:#fff

    classDef agent fill:#8B0000,color:#fff
```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as Endpoints (Python)

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result    Agent-->>User: Response
```

## Quick Start

<Steps>
  <Step title="Run a recipe">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import recipe

    recipes = recipe.list_recipes()
    info = recipe.describe("my-recipe")

    result = recipe.run(
        "my-recipe",
        input={"query": "Hello, world!"},
        options={"timeout_sec": 60},
    )

    if result.ok:
        print(f"Output: {result.output}")
    else:
        print(f"Error: {result.error}")
    ```
  </Step>

  <Step title="Stream and handle errors">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import os
    from praisonai import recipe
    from praisonai.recipe.exceptions import (
        RecipeError,
        RecipeNotFoundError,
        RecipeTimeoutError,
    )

    for event in recipe.run_stream(
        "my-recipe",
        input={"query": "Generate a story"},
    ):
        if event.event_type == "completed":
            print(event.data)

    try:
        recipe.run("my-recipe", input={"query": "test"})
    except RecipeNotFoundError as e:
        print(f"Recipe not found: {e.recipe}")
    except RecipeTimeoutError as e:
        print(f"Timeout after {e.timeout_sec}s")
    except RecipeError as e:
        print(f"Recipe error: {e}")
    ```
  </Step>
</Steps>

***

## HTTP Client

Use the REST API from any language when the endpoint server is running (`praisonai serve`).

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import os
import requests

BASE_URL = os.getenv("PRAISON_ENDPOINT_URL", "http://localhost:8765")
API_KEY = os.getenv("PRAISON_API_KEY")  # optional when auth is enabled

headers = {"Content-Type": "application/json"}
if API_KEY:
    headers["X-API-Key"] = API_KEY

response = requests.post(
    f"{BASE_URL}/v1/recipes/run",
    headers=headers,
    json={
        "recipe": "my-recipe",
        "input": {"query": "Hello"},
        "options": {"dry_run": False},
    },
)
result = response.json()
print(result["output"])
```

<Tabs>
  <Tab title="curl">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    curl -X POST http://localhost:8765/v1/recipes/run \
      -H "Content-Type: application/json" \
      -H "X-API-Key: $PRAISON_API_KEY" \
      -d '{"recipe": "my-recipe", "input": {"query": "Hello"}}'
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    const baseUrl = process.env.PRAISON_ENDPOINT_URL ?? "http://localhost:8765";
    const apiKey = process.env.PRAISON_API_KEY;

    const res = await fetch(`${baseUrl}/v1/recipes/run`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(apiKey ? { "X-API-Key": apiKey } : {}),
      },
      body: JSON.stringify({ recipe: "my-recipe", input: { query: "Hello" } }),
    });
    console.log(await res.json());
    ```
  </Tab>
</Tabs>

***

## Response Models

| Field    | Type          | Description                                          |
| -------- | ------------- | ---------------------------------------------------- |
| `ok`     | `bool`        | Success status                                       |
| `run_id` | `str`         | Unique run identifier                                |
| `output` | `Any`         | Recipe output                                        |
| `error`  | `str \| None` | Error message when failed                            |
| `trace`  | `dict`        | `run_id`, `session_id`, `trace_id` for observability |

Streaming events use `event_type`: `started`, `progress`, `completed`, or `error`.

***

## Best Practices

<AccordionGroup>
  <Accordion title="Always set timeouts">
    Pass `options={"timeout_sec": 30}` (or higher) so long-running recipes fail predictably instead of hanging.
  </Accordion>

  <Accordion title="Use session IDs for stateful workflows">
    Reuse `session_id` across calls so conversation recipes retain context between requests.
  </Accordion>

  <Accordion title="Read trace IDs from results">
    Log `result.trace["trace_id"]` for debugging and observability correlation.
  </Accordion>

  <Accordion title="Prefer the Python SDK in-process">
    Use `from praisonai import recipe` when running in the same environment; use HTTP for remote or polyglot clients.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Endpoint Provider Registry" icon="plug" href="/docs/features/endpoint-provider-registry">
    Register custom endpoint providers for serve and discovery
  </Card>

  <Card title="CLI Endpoints" icon="terminal" href="/docs/cli/endpoints">
    Run and manage endpoints from the command line
  </Card>
</CardGroup>
