Endpoints (Python)

Programmatic access to PraisonAI recipe endpoints using Python and HTTP

python
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
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.

Diagram

📋 Client

🔌 recipe.run / HTTP

🚀 Endpoint server

🧠 Recipe agent

✅ RecipeResult

How It Works

Diagram
Endpoints (Python)AgentUserEndpoints (Python)AgentUserRequestProcess requestResult Agent–>>User: Response

Quick Start

  1. Run a recipe
    python
    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}")
  2. Stream and handle errors
    python
    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}")

HTTP Client

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

python
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"])

curl

bash
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"}}'

JavaScript

javascript
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());

Response Models

FieldTypeDescription
okboolSuccess status
run_idstrUnique run identifier
outputAnyRecipe output
error`str \None`Error message when failed
tracedictrun_id, session_id, trace_id for observability

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


Best Practices

Always set timeouts

Pass options={"timeout_sec": 30} (or higher) so long-running recipes fail predictably instead of hanging.

Use session IDs for stateful workflows

Reuse session_id across calls so conversation recipes retain context between requests.

Read trace IDs from results

Log result.trace["trace_id"] for debugging and observability correlation.

Prefer the Python SDK in-process

Use from praisonai import recipe when running in the same environment; use HTTP for remote or polyglot clients.


Related