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

# Server Adapters

> Deploy AI agents as HTTP servers with Express, Hono, Fastify, and more

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Client([Client]) --> HTTP[HTTP Handler]
    HTTP --> Agent[Agent]

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff

    class Agent agent
    class HTTP,Client tool
    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff
```

Deploy Agents as HTTP servers with popular Node.js frameworks.

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import { Agent, createHttpHandler } from 'praisonai-ts';
    import http from 'http';

    const agent = new Agent({
      name: 'APIAgent',
      instructions: 'You are a helpful API assistant.',
    });

    const handler = createHttpHandler({ agent });

    const server = http.createServer(handler);
    server.listen(3000, () => {
      console.log('Server running on http://localhost:3000');
    });
    ```
  </Step>

  <Step title="With Configuration">
    Use Express, Hono, or Fastify handlers — see sections below.
  </Step>
</Steps>

***

## Express

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import express from 'express';
import { Agent, createExpressHandler } from 'praisonai-ts';

const app = express();
app.use(express.json());

const agent = new Agent({
  name: 'ExpressAgent',
  instructions: 'You are a helpful assistant.',
});

const handler = createExpressHandler({ agent });

app.post('/api/chat', handler);
app.post('/api/chat/stream', handler); // Streaming endpoint

app.listen(3000);
```

## Hono

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Hono } from 'hono';
import { Agent, createHonoHandler } from 'praisonai-ts';

const app = new Hono();

const agent = new Agent({
  name: 'HonoAgent',
  instructions: 'You are a helpful assistant.',
});

const handler = createHonoHandler({ agent });

app.post('/api/chat', handler);

export default app;
```

## Fastify

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import Fastify from 'fastify';
import { Agent, createFastifyHandler } from 'praisonai-ts';

const fastify = Fastify();

const agent = new Agent({
  name: 'FastifyAgent',
  instructions: 'You are a helpful assistant.',
});

const handler = createFastifyHandler({ agent });

fastify.post('/api/chat', handler);

fastify.listen({ port: 3000 });
```

## Nest.js

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Controller, Post, Body, Res } from '@nestjs/common';
import { Response } from 'express';
import { Agent, createNestHandler } from 'praisonai-ts';

@Controller('api')
export class ChatController {
  private agent = new Agent({
    name: 'NestAgent',
    instructions: 'You are a helpful assistant.',
  });

  @Post('chat')
  async chat(@Body() body: { message: string }, @Res() res: Response) {
    const handler = createNestHandler({ agent: this.agent });
    return handler(body, res);
  }
}
```

## Configuration Options

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
const handler = createExpressHandler({
  agent: agent,
  
  // Streaming
  streaming: true,           // Enable streaming responses
  
  // CORS
  cors: {
    origin: '*',
    methods: ['POST'],
  },
  
  // Rate limiting
  rateLimit: {
    windowMs: 60000,         // 1 minute
    max: 100,                // 100 requests per window
  },
  
  // Tracing
  tracing: true,             // Enable request tracing
  
  // Custom response format
  formatResponse: (result) => ({
    success: true,
    data: result,
  }),
});
```

## Request Format

```json theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
  "message": "Hello, how are you?",
  "sessionId": "optional-session-id",
  "metadata": {
    "userId": "user-123"
  }
}
```

## Response Format

### Non-Streaming

```json theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
  "response": "I'm doing well, thank you!",
  "sessionId": "session-123",
  "usage": {
    "promptTokens": 10,
    "completionTokens": 8,
    "totalTokens": 18
  }
}
```

### Streaming

Server-Sent Events (SSE) format:

```
data: {"type":"text","content":"I'm"}
data: {"type":"text","content":" doing"}
data: {"type":"text","content":" well"}
data: {"type":"done","usage":{"totalTokens":18}}
```

## With Tools

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
const agent = new Agent({
  name: 'ToolAgent',
  instructions: 'You help with calculations.',
  tools: [
    {
      name: 'calculate',
      description: 'Perform calculations',
      execute: async ({ expression }) => eval(expression),
    },
  ],
});

const handler = createExpressHandler({
  agent,
  streaming: true,
});
```

## Authentication Middleware

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import express from 'express';

const app = express();

// Auth middleware
app.use('/api', (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token || !validateToken(token)) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});

app.post('/api/chat', handler);
```

## Environment Variables

| Variable         | Required | Description                 |
| ---------------- | -------- | --------------------------- |
| `OPENAI_API_KEY` | Yes      | For the agent               |
| `PORT`           | No       | Server port (default: 3000) |

## Best Practices

<AccordionGroup>
  <Accordion title="Enable CORS">
    Configure for your frontend domains
  </Accordion>

  <Accordion title="Add authentication">
    Protect your endpoints
  </Accordion>

  <Accordion title="Rate limit">
    Prevent abuse
  </Accordion>

  <Accordion title="Use streaming">
    Better UX for long responses
  </Accordion>

  <Accordion title="Log requests">
    Track usage and errors
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card title="Next.js" icon="code" href="/docs/js/nextjs">
    Next.js integration
  </Card>

  <Card title="Agent" icon="robot" href="/docs/js/agent">
    Agent configuration
  </Card>
</CardGroup>
