Skip to main content

Overview

The admesh-weave-node SDK is a backend Node.js package that fetches personalized recommendations from AdMesh. Use it to retrieve recommendations that your LLM can naturally weave into responses. When to use this SDK:
  • You want to embed recommendations directly in LLM responses (Weave Ad Format)
  • You need backend control over recommendation fetching
  • You’re building a custom LLM integration
When NOT to use this SDK:
  • You only need frontend recommendations (use admesh-ui-sdk instead)
  • You want a separate recommendations panel (use Citation/Product Format with admesh-ui-sdk)

Quick Start

Install the package:
npm install @admesh/weave-node@latest
Initialize the client:
import { AdMeshClient } from '@admesh/weave-node';

const client = new AdMeshClient({
  apiKey: process.env.ADMESH_API_KEY
});
Fetch recommendations:
const result = await client.getRecommendationsForWeave({
  sessionId: sessionId,
  messageId: messageId,
  query: userQuery
});

if (result.found) {
  const context = result.recommendations
    .map(r => \`- \${r.product_title}: \${r.click_url}\`)
    .join('\\n');
}

Requirements

  • Node.js 16.x or higher (LTS recommended)
  • API key from AdMesh dashboard
  • TypeScript support included
  • Works with Express, Fastify, Next.js API routes, etc.

Installation Methods

npm (recommended):
npm install @admesh/weave-node@latest
Yarn:
yarn add @admesh/weave-node@latest
pnpm:
pnpm add @admesh/weave-node@latest

Core Concepts

AdMeshClient

The main client for fetching recommendations. Initialize once and reuse across your application.
import { AdMeshClient } from '@admesh/weave-node';

const client = new AdMeshClient({
  apiKey: process.env.ADMESH_API_KEY
});
Security: Never hardcode your API key. Always use environment variables or a secrets manager.

Session and Message IDs

AdMesh uses IDs to track user interactions:
  • Session ID: Unique identifier for a user’s conversation session
  • Message ID: Unique identifier for each individual message/query
// Your application generates these IDs
const sessionId = crypto.randomBytes(16).toString('hex');
const messageId = crypto.randomBytes(7).toString('hex');
Your backend is responsible for generating and managing session and message IDs. The SDK accepts these IDs but does not generate them.

API Methods

getRecommendationsForWeave()

Fetches recommendations for a given query that can be woven into LLM responses.
interface GetRecommendationsForWeaveRequest {
  sessionId: string;  // User's session ID
  messageId: string;  // Current message ID
  query: string;      // User's query
}

interface GetRecommendationsForWeaveResponse {
  found: boolean;
  recommendations: Recommendation[];
}

interface Recommendation {
  ad_id: string;           // Unique ad identifier
  product_title: string;   // Product/service title
  product_description: string; // Product description
  click_url: string;       // Tracking URL for clicks
  exposure_url: string;    // Tracking URL for exposures
}
Example:
const result = await client.getRecommendationsForWeave({
  sessionId: 'session-abc123',
  messageId: 'msg-xyz789',
  query: 'best project management tools'
});

if (result.found) {
  console.log(\`Found \${result.recommendations.length} recommendations\`);
  result.recommendations.forEach(rec => {
    console.log(\`- \${rec.product_title}: \${rec.click_url}\`);
  });
}

Integration Example

Here’s a complete example showing how to fetch recommendations and pass them to your LLM:
import express from 'express';
import { AdMeshClient } from '@admesh/weave-node';

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

const client = new AdMeshClient({
  apiKey: process.env.ADMESH_API_KEY
});

app.post('/api/chat', async (req, res) => {
  const { sessionId, messageId, query } = req.body;

  try {
    // Step 1: Fetch AdMesh recommendations
    const result = await client.getRecommendationsForWeave({
      sessionId: sessionId,
      messageId: messageId,
      query: query
    });

    // Step 2: Format recommendations for your LLM
    let recommendationsContext = '';
    if (result.found) {
      recommendationsContext = result.recommendations
        .map(r => \`- \${r.product_title}: \${r.click_url}\`)
        .join('\\n');
    }

    // Step 3: Pass to your LLM with recommendations
    const llmPrompt = \`\${query}\\n\\nRecommendations:\\n\${recommendationsContext}\`;
    const llmResponse = await callYourLLM(llmPrompt);

    // Step 4: Return response (LLM has woven AdMesh links into the text)
    res.json({ response: llmResponse });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Failed to process request' });
  }
});

app.listen(3000);
Complete Integration: This example shows backend integration only. For frontend integration to detect and track the embedded links, see the Weave Ad Format guide.

Error Handling

Always wrap API calls in try-catch blocks:
try {
  const result = await client.getRecommendationsForWeave({
    sessionId,
    messageId,
    query
  });
  
  if (result.found) {
    // Process recommendations
  } else {
    // No recommendations found for this query
    console.log('No recommendations available');
  }
} catch (error) {
  console.error('Error fetching recommendations:', error.message);
  // Handle error appropriately
}
Common scenarios:
  • result.found === false: No recommendations available for the query (not an error)
  • Network errors: Retry with exponential backoff
  • Invalid API key: Check environment variables

TypeScript Support

The SDK is written in TypeScript and includes full type definitions:
import type {
  AdMeshClient,
  GetRecommendationsForWeaveRequest,
  GetRecommendationsForWeaveResponse,
  Recommendation
} from '@admesh/weave-node';
All methods and interfaces are fully typed for the best developer experience.

Troubleshooting

No recommendations returned

Possible causes:
  • Query is too generic (try more specific queries)
  • No active campaigns match the query
  • API key is invalid
Solution:
  • Use more specific queries (e.g., “best CRM for startups” instead of “software”)
  • Check that your AdMesh account has active campaigns
  • Verify API key in environment variables

API key errors

Check:
  • ADMESH_API_KEY is set in environment variables
  • API key is valid (check dashboard)
  • No extra whitespace in the key value
Example:
# .env
ADMESH_API_KEY=your-api-key-here

TypeScript errors

Solution:
  • Ensure TypeScript 4.0 or higher
  • Import types explicitly: import type from ‘@admesh/weave-node’
  • Check tsconfig.json includes “moduleResolution”: “node”

Network/timeout errors

Check:
  • Server has internet access
  • No firewall blocking outbound requests
  • Network is stable
Solution:
  • Implement retry logic with exponential backoff
  • Check server network configuration

Next Steps

Weave Ad Format Guide: Complete integration guide for embedding recommendations in LLM responses - /platforms/weave-ad-format Frontend SDK: Install admesh-ui-sdk to detect and track embedded links on the frontend - /ui-sdk/installation
You’re ready to start integrating.
Install @admesh/weave-node, fetch recommendations, and pass them to your LLM for natural weaving into responses.