Dialogflow能否基于用户输入动态创建带上下文的意图?
Great question—this is such a common frustration when working with dynamic data in Dialogflow, and you absolutely don’t need to build hundreds of separate intents to solve this. Here’s how to handle it cleanly:
1. First, extract dynamic features with custom entities & parameters
Instead of hardcoding each feature into an intent, start by creating a custom entity (let’s call it feature) that includes all your possible feature names. If you have hundreds of features, you can even load this entity dynamically via Dialogflow’s API instead of manually entering them one by one.
Next, create a single intent (e.g., PlotFeaturesIntent) and add training phrases like:
- "I want to plot feature_1 and feature_2"
- "Show me a graph of feature_3"
- "Plot feature_5, feature_7, and feature_9"
Then add a parameter to this intent:
- Name it
features - Set the entity type to
@feature - Check the "Allow multiple values" box so Dialogflow can extract all features mentioned in one input.
2. Use Fulfillment to dynamically set output contexts
This is the key part—you can’t set dynamic contexts through the Dialogflow UI alone, but you can do it easily with a webhook (Fulfillment). Here’s a quick example using Node.js:
function handlePlotFeatures(agent) { // Get the array of features extracted from the user's input const requestedFeatures = agent.parameters.features; // Loop through each feature and create a unique output context requestedFeatures.forEach(feature => { agent.context.set({ name: `active_feature_${feature}`, // Use a consistent naming pattern lifespan: 3 // How many turns the context should stick around }); }); // Send a confirmation message to the user agent.add(`Got it! I've set contexts for ${requestedFeatures.join(', ')} so we can work with them next.`); } // Register the intent handler let intentMap = new Map(); intentMap.set('PlotFeaturesIntent', handlePlotFeatures); agent.handleRequest(intentMap);
This code takes every feature the user mentioned, creates a unique output context for each, and sets how long that context should remain active.
3. Use these dynamic contexts in follow-up intents
For follow-up actions (like "Adjust the scale for feature_1"), you can either:
- Reference the context directly in the follow-up intent’s input contexts (e.g.,
active_feature_feature_1), or - In the follow-up intent’s Fulfillment, check which
active_feature_*contexts exist to determine which features the user is referring to.
Bonus tips:
- If your features are constantly changing, use dynamic entity updates via Dialogflow’s API to keep your
featureentity up to date without manual edits. - If you’re using Dialogflow CX instead of ES, the approach is similar—use session parameters and webhooks to dynamically manage context-like state, since CX has more flexible session management tools.
内容的提问来源于stack exchange,提问作者Pedro Silva

