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

Quick Start

Here’s our production-ready TypeScript implementation:

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:

{
  "dependencies": {
    "aws-lambda": "^1.0.7",
    "axios": "^1.7.7"
  }
}

3. Deployment Options

Create a serverless.yml:

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:

serverless deploy

Option B: Manual Deployment

  1. Build the TypeScript:
tsc
  1. Create a ZIP with the compiled code and node_modules:
zip -r function.zip dist/ node_modules/
  1. Upload to AWS Lambda through the console or CLI

4. IAM Configuration

Minimum required IAM policy:

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

Usage

Request Format

{
  "query": string,    // Required: Your query
  "memoryID": string  // Optional: Specific memory ID
}

Response Format

{
  "success": boolean,
  "message": string,
  "answer": string,
  "facts": Array<{
    "text": string,
    "relevance": number
  }>
}

Testing

Test your deployed function with curl:

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