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 Tail/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,  // Required
  apiBaseUrl: process.env.ADMESH_API_BASE_URL  // Optional: defaults to https://api.useadmesh.com
});
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 AdMeshSubscriptionOptions {
  sessionId: string;        // Required: Must be provided by frontend
  messageId: string;        // Required: Must be provided by frontend
  query: string;            // Required: User query for contextual recommendations
  latencyBudgetMs?: number; // Optional: Latency budget for auction processing (milliseconds)
  messages?: Array<{ role: string; content: string; id?: string }>;  // Optional: Conversation history
  locale?: string;          // Optional: User language in BCP 47 format (e.g., "en-US")
  geo?: string;             // Optional: User country code in ISO 3166-1 alpha-2 format (e.g., "US")
  userId?: string;          // Optional: Anonymous hashed user ID
  model?: string;           // Optional: AI model identifier (e.g., "gpt-4o")
  platformId?: string;      // Optional: Platform identifier
  platformSurface?: string; // Optional: Platform surface (e.g., "web")
}

interface AdMeshWaitResult {
  found: boolean;                         // Whether recommendations were found
  recommendations?: AdMeshRecommendation[]; // Array of recommendations
  query?: string;                         // Original query
  requestId?: string;                     // Request ID
  error?: string;                         // Error message if not found
}

interface AdMeshRecommendation {
  recommendation_id: string;              // Recommendation identifier
  ad_id: string;                          // Unique ad identifier
  product_id: string;                     // Product ID
  product_title: string;                  // Product/service title
  click_url: string;                      // Tracking URL for clicks
  exposure_url: string;                   // Tracking URL for exposures
  weave_summary?: string;                 // Weave format summary
  tail_summary?: string;                  // Tail format summary
  creative_input: CreativeInput;          // Creative content with product details
  contextual_relevance_score: number;     // Contextual relevance score (0-100)
  // ... and other fields
}
Example:
const result = await client.getRecommendationsForWeave({
  sessionId: 'session-abc123',  // Required: Must be provided by frontend
  messageId: 'msg-xyz789',      // Required: Must be provided by frontend
  query: 'best project management tools',  // Required
  latencyBudgetMs: 10000  // Optional: 10 second latency budget for auction processing
});

if (result.found) {
  console.log(\`Found \${result.recommendations.length} recommendations\`);
  result.recommendations?.forEach(rec => {
    console.log(\`- \${rec.product_title}: \${rec.click_url}\`);
    console.log(\`  Summary: \${rec.weave_summary || rec.creative_input?.short_description}\`);
  });
} else {
  console.log('No recommendations found:', result.error);
}

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,  // Required: Must be provided by frontend
      messageId: messageId,  // Required: Must be provided by frontend
      query: query,          // Required
      latencyBudgetMs: 10000  // Optional: 10 second latency budget for auction processing
    });

    // 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,
  AdMeshSubscriptionOptions,
  AdMeshWaitResult,
  AdMeshRecommendation
} 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.