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

# Use with AWS Lambda

> Integrate duohub with AWS Lambda functions

Integrate duohub's memory retrieval capabilities with AWS Lambda functions to query your knowledge graph through serverless functions.

<CardGroup cols={1}>
  <Card title="Examples GitHub Repository" icon="github" href="https://github.com/duohub-ai/examples/tree/main/lambda">
    View the complete implementation of this Lambda function on GitHub
  </Card>
</CardGroup>

## Quick Start

Here's our production-ready TypeScript implementation:

```typescript theme={null}
import { Handler } from "aws-lambda";
import axios from "axios";

interface LambdaEvent {
  query: string;
  memoryID?: string;
}

interface MemoryRetrieverResponse {
  payload: string;
  facts: Array<{
    text: string;
    relevance: number;
  }>;
}

export const handler: Handler<LambdaEvent, LambdaResponse> = async (event) => {
  try {
    const { query, memoryID } = event;

    const params = new URLSearchParams({
      query,
      ...(memoryID && { memoryID }),
      assisted: "true",
      facts: "true",
    });

    const response = await axios.get<MemoryRetrieverResponse>(
      `https://api.duohub.ai/memory/?${params.toString()}`,
      {
        headers: {
          "X-API-KEY": process.env.API_KEY as string,
          "Content-Type": "application/json",
        },
      }
    );

    return {
      success: true,
      message: "Query executed successfully.",
      answer: response.data.payload,
      facts: response.data.facts,
    };
  } catch (err) {
    console.error("Error querying memory retriever:", err);
    return {
      success: false,
      message: `Error: ${err instanceof Error ? err.message : String(err)}`,
      answer: "",
      facts: [],
    };
  }
};
```

## Prerequisites

* AWS Account with Lambda access
* Node.js 18 or later
* duohub API key
* AWS CLI configured (if deploying manually)

## Setup Guide

### 1. Environment Variables

Set up your Lambda environment variable:

```
API_KEY=your-duohub-api-key
```

### 2. Dependencies

Required npm packages:

```json theme={null}
{
  "dependencies": {
    "aws-lambda": "^1.0.7",
    "axios": "^1.7.7"
  }
}
```

### 3. Deployment Options

#### Option A: Serverless Framework (Recommended)

Create a `serverless.yml`:

```yaml theme={null}
service: duohub-memory-service

provider:
  name: aws
  runtime: nodejs18.x
  environment:
    API_KEY: ${env:API_KEY}

functions:
  memoryQuery:
    handler: index.handler
    events:
      - http:
          path: query
          method: post
```

Deploy with:

```bash theme={null}
serverless deploy
```

#### Option B: Manual Deployment

1. Build the TypeScript:

```bash theme={null}
tsc
```

2. Create a ZIP with the compiled code and node\_modules:

```bash theme={null}
zip -r function.zip dist/ node_modules/
```

3. Upload to AWS Lambda through the console or CLI

### 4. IAM Configuration

Minimum required IAM policy:

```json theme={null}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}
```

## Usage

### Request Format

```typescript theme={null}
{
  "query": string,    // Required: Your query
  "memoryID": string  // Optional: Specific memory ID
}
```

### Response Format

```typescript theme={null}
{
  "success": boolean,
  "message": string,
  "answer": string,
  "facts": Array<{
    "text": string,
    "relevance": number
  }>
}
```

### Testing

Test your deployed function with curl:

```bash theme={null}
curl -X POST https://your-lambda-url/query \
  -H "Content-Type: application/json" \
  -d '{"query": "your query", "memoryID": "optional-memory-id"}'
```

## Best Practices

1. **Error Handling**

   * Implement retries for network failures
   * Add detailed logging
   * Return meaningful error messages

2. **Security**

   * Store API key in AWS Secrets Manager
   * Use IAM roles with minimum required permissions
   * Enable AWS X-Ray for request tracing

3. **Performance**

   * Keep dependencies minimal
   * Use connection pooling in axios
   * Consider implementing caching if appropriate

4. **Monitoring**
   * Set up CloudWatch alarms
   * Monitor error rates and latency
   * Set up logging for debugging

## Troubleshooting

Common issues and solutions:

1. **Timeout Issues**

   * Increase Lambda timeout in configuration
   * Check duohub API response times
   * Implement request timeouts in axios

2. **Memory Issues**

   * Increase Lambda memory allocation
   * Check for memory leaks
   * Monitor memory usage patterns

3. **Authorization Errors**
   * Verify API key is set
