Skip to main content
The Agent module provides streaming AI-powered recommendations based on natural language user intents. It uses Server-Sent Events (SSE) to deliver real-time results.
The Agent module replaces the deprecated Assistant module and provides enhanced functionality for intent-based recommendations.

Getting Started

The agent module is available on your Constructor.io client instance:
const ConstructorioClient = require('@constructor-io/constructorio-client-javascript');

const constructorio = new ConstructorioClient({
  apiKey: 'YOUR_API_KEY',
});

// Access the agent module
const stream = constructorio.agent.getAgentResultsStream('I want to get shoes', {
  domain: 'nike_sportswear'
});

Methods

getAgentResultsStream

Retrieve a stream of AI-powered recommendations based on natural language intent.
const stream = constructorio.agent.getAgentResultsStream(
  'I want to get shoes for running',
  { domain: 'nike_sportswear' }
);

const reader = stream.getReader();

while (true) {
  const { value, done } = await reader.read();
  
  if (done) break;
  
  console.log('Event type:', value.type);
  console.log('Event data:', value.data);
}

Parameters

intent
string
required
Natural language intent describing what the user wantsExamples:
  • “I want to get shoes for running”
  • “Show me red dresses for a wedding”
  • “Find me comfortable office chairs”
parameters
object
required
Parameters to configure the request

Return Value

Returns a ReadableStream that emits events as they arrive from the server.

Event Types

The stream emits different event types as data becomes available. Access these via Agent.EventTypes:
START
start
Denotes the start of the stream
GROUP
group
Represents a semantic grouping of search results, optionally with textual explanation
{
  "type": "group",
  "data": {
    "group_id": "running-shoes",
    "display_name": "Running Shoes",
    "explanation": "Based on your request for comfortable running shoes"
  }
}
SEARCH_RESULT
search_result
Represents a set of results with metadata (used to show results with search refinements)
{
  "type": "search_result",
  "data": {
    "results": [...],
    "refinements": {...},
    "total_num_results": 45
  }
}
ARTICLE_REFERENCE
article_reference
Represents content or article references with metadata
RECIPE_INFO
recipe_info
Contains recipes’ auxiliary information like cooking times and serving sizes
RECIPE_INSTRUCTIONS
recipe_instructions
Contains step-by-step recipe instructions
IMAGE_META
image_meta
Used for enhancing recommendations with media content such as images
SERVER_ERROR
server_error
Indicates a server error occurred
{
  "type": "server_error",
  "data": {
    "message": "An error occurred processing your request"
  }
}
END
end
Represents the end of the data stream

Complete Implementation Example

class AgentResultsHandler {
  constructor(constructorio) {
    this.constructorio = constructorio;
  }
  
  async streamResults(intent, domain) {
    const stream = this.constructorio.agent.getAgentResultsStream(intent, {
      domain,
      numResultsPerPage: 20
    });
    
    const reader = stream.getReader();
    
    try {
      while (true) {
        const { value, done } = await reader.read();
        
        if (done) {
          this.handleStreamEnd();
          break;
        }
        
        await this.handleEvent(value);
      }
    } catch (error) {
      this.handleError(error);
    }
  }
  
  async handleEvent(event) {
    const { type, data } = event;
    
    switch (type) {
      case 'start':
        console.log('Stream started');
        this.showLoadingIndicator();
        break;
        
      case 'group':
        console.log('Group:', data.display_name);
        if (data.explanation) {
          this.displayExplanation(data.explanation);
        }
        break;
        
      case 'search_result':
        console.log('Results:', data.results.length);
        this.displayResults(data.results);
        if (data.refinements) {
          this.displayRefinements(data.refinements);
        }
        break;
        
      case 'article_reference':
        this.displayArticle(data);
        break;
        
      case 'image_meta':
        this.displayImages(data);
        break;
        
      case 'server_error':
        this.handleError(new Error(data.message));
        break;
    }
  }
  
  handleStreamEnd() {
    console.log('Stream complete');
    this.hideLoadingIndicator();
  }
  
  handleError(error) {
    console.error('Error:', error);
    this.showErrorMessage(error.message);
  }
  
  showLoadingIndicator() {
    // Implementation
  }
  
  hideLoadingIndicator() {
    // Implementation
  }
  
  displayExplanation(text) {
    // Implementation
  }
  
  displayResults(results) {
    // Implementation
  }
  
  displayRefinements(refinements) {
    // Implementation
  }
  
  displayArticle(data) {
    // Implementation
  }
  
  displayImages(data) {
    // Implementation
  }
  
  showErrorMessage(message) {
    // Implementation
  }
}

// Usage
const handler = new AgentResultsHandler(constructorio);
await handler.streamResults(
  'I need comfortable shoes for running marathons',
  'athletic_footwear'
);

Stream Management

Canceling a Stream

You can cancel a stream at any time:
const stream = constructorio.agent.getAgentResultsStream(
  'show me laptops',
  { domain: 'electronics' }
);

const reader = stream.getReader();

// Later, cancel the stream
reader.cancel();

Error Handling

Always implement proper error handling:
const stream = constructorio.agent.getAgentResultsStream(intent, { domain });
const reader = stream.getReader();

try {
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    
    // Handle server errors within the stream
    if (value.type === 'server_error') {
      console.error('Server error:', value.data.message);
      break;
    }
    
    // Process other events
    processEvent(value);
  }
} catch (error) {
  // Handle network errors or stream errors
  console.error('Stream error:', error);
} finally {
  reader.releaseLock();
}

Use Cases

1

Natural Language Search

Let users search using conversational language:
const intent = 'I need a gift for my wife who loves gardening';
const stream = constructorio.agent.getAgentResultsStream(intent, {
  domain: 'gifts_and_hobbies'
});
2

Context-Aware Recommendations

Provide recommendations based on detailed user context:
const intent = 'Show me running shoes for trail running in wet conditions';
const stream = constructorio.agent.getAgentResultsStream(intent, {
  domain: 'outdoor_sports'
});
3

Progressive Loading

Display results as they stream in for better UX:
const reader = stream.getReader();

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  
  if (value.type === 'search_result') {
    // Append results progressively
    appendResults(value.data.results);
  }
}

Browser Compatibility

The Agent module requires:
  • EventSource API for Server-Sent Events
  • ReadableStream API for stream handling
These are supported in all modern browsers. For React Native support, see the React Native guide.

Build docs developers (and LLMs) love