You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS调用DialogFlow v2用户实体接口传递自定义数据示例代码求助

Hey there, I've put together a complete Node.js example to help you create and pass custom user entities to Dialogflow v2, plus key explanations to make sure it fits your needs:

Node.js Implementation for Dialogflow v2 User Entities

First, let's cover the prerequisites: you'll need to have the Dialogflow Node.js client set up, and authenticate your project using a service account key JSON file (this is the standard, recommended method for server-side code).

Step 1: Install Required Dependencies

Start by installing the official Dialogflow client package:

npm install @google-cloud/dialogflow

You'll also need uuid to generate unique session IDs (if you don't already have a session tracking system in place):

npm install uuid

Step 2: Full Working Code Example

Here's a ready-to-use script that creates a session-specific user entity with custom entries:

const dialogflow = require('@google-cloud/dialogflow');
const uuid = require('uuid');

// Async function to create a session entity type
async function createCustomUserEntity(projectId, sessionId) {
  // Initialize the Dialogflow session entity client
  const client = new dialogflow.SessionEntityTypesClient({
    keyFilename: '/absolute/path/to/your/service-account-key.json' // Replace with your key's path
  });

  // Build the unique path for your session entity
  const sessionEntityTypePath = client.sessionEntityTypePath(
    projectId,
    sessionId,
    'your-custom-entity-name' // Name your user entity here (matches what you'll reference in intents)
  );

  // Define your custom entity entries: canonical value + user-facing synonyms
  const customEntityEntries = [
    {
      value: 'premium-laptop-pro', // The internal value Dialogflow will use
      synonyms: ['ProBook X', 'Premium Pro Laptop', 'X Series Pro'] // Phrases users might type/say
    },
    {
      value: 'budget-tablet',
      synonyms: ['Entry-Level Tab', 'Budget Pad', 'Affordable Tablet']
    }
  ];

  // Choose how this entity interacts with existing ones:
  // - 'OVERRIDE': Replaces any existing user entities for this session
  // - 'SUPPLEMENT': Adds new entries alongside existing entities
  const entityOverrideMode = 'OVERRIDE';

  // Construct the API request
  const request = {
    parent: client.sessionPath(projectId, sessionId),
    sessionEntityType: {
      name: sessionEntityTypePath,
      entityOverrideMode: entityOverrideMode,
      entities: customEntityEntries
    }
  };

  try {
    const [response] = await client.createSessionEntityType(request);
    console.log('✅ Custom user entity created successfully:');
    console.log(response);
  } catch (error) {
    console.error('❌ Error creating user entity:', error);
  }
}

// Configure your project details
const YOUR_PROJECT_ID = 'your-google-cloud-project-id';
const SESSION_ID = uuid.v4(); // Generate a unique session ID (or use your existing session tracker)

// Run the function
createCustomUserEntity(YOUR_PROJECT_ID, SESSION_ID);

Key Details to Keep in Mind:

  • Authentication: The service account key must have permissions like Dialogflow API Admin or Dialogflow Session Entity Editor to modify session entities.
  • Session-Specific Scope: User entities are tied to a single session, so they won't affect other users or your global Dialogflow entities.
  • Override vs Supplement: Use SUPPLEMENT if you want to add custom entries without replacing existing ones (great for dynamic context, like user-specific preferences).
  • Session ID: Always use a unique session ID per user interaction to maintain context consistency.

内容的提问来源于stack exchange,提问作者Rainmaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:31:43