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

如何在基于Python、词袋模型与TensorFlow的上下文聊天机器人中添加动作?

Hey there! Let's break down how to add actions to your contextual chatbot, fitting right into the bag-of-words + TensorFlow setup you're working with. Here's a practical, step-by-step approach:

Step 1: Extend Your Intents JSON with Action Metadata

First, update your intents file to add an action key for any intent tag that needs to trigger a specific task. This acts as a hook to link the intent to your Python logic. For example:

{"intents": [
  {"tag": "greeting", "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day"], "responses": ["Hello, thanks for visiting", "Good to see you again", "Hi there, how can I help?"], "context_set": "", "action": "" },
  {"tag": "goodbye", "patterns": ["Bye", "See you later"], "responses": ["See you soon!", "Have a great day!"], "context_set": "", "action": "cleanup_session" },
  {"tag": "check_weather", "patterns": ["What's the weather like?", "Is it raining today?"], "responses": ["Let me pull that up for you..."], "context_set": "", "action": "get_current_weather" }
]}

The action value should be a string that matches the name of the Python function you'll write next.

Step 2: Write Your Action Functions

Create Python functions that handle the actual work for each action. These can range from simple session cleanup to external API calls. For example:

def cleanup_session():
    # Example: Reset user context or clear temporary data
    print("Clearing user session context...")
    # Add your custom cleanup logic here (e.g., reset context variables)
    return "Your session has been reset."

def get_current_weather():
    # Example: Call a weather API (replace with real API logic)
    # For demo purposes, return mock data
    weather_info = {"temp": 24, "condition": "Partly Cloudy"}
    return f"It's {weather_info['temp']}°C and {weather_info['condition']} right now."

Feel free to expand these—you could add database queries, third-party API integrations, or any other task your bot needs to perform.

Step 3: Map Actions to Functions

Create a dictionary to map the action strings from your JSON to the actual Python functions. This makes it easy to look up and execute the right action when an intent is matched:

action_map = {
    "cleanup_session": cleanup_session,
    "get_current_weather": get_current_weather
}
Step 4: Modify Chatbot Logic to Trigger Actions

In the part of your code where you predict the intent tag (after running your TensorFlow model and selecting the highest-confidence tag), add logic to check for and execute the action:

import random

# Assume you've already loaded your intents into a variable called `intents`
# Assume `predicted_tag` is the tag your model output for the user's input

# Find the matching intent from your JSON
matched_intent = next(intent for intent in intents["intents"] if intent["tag"] == predicted_tag)

bot_response = ""

# Check if the intent has an action to run
if matched_intent.get("action"):
    action_func = action_map.get(matched_intent["action"])
    if action_func:
        # Run the action and get its result
        action_output = action_func()
        # Combine the action result with a bot response
        bot_response = f"{random.choice(matched_intent['responses'])} {action_output}"
    else:
        # Fallback if the action isn't mapped
        bot_response = random.choice(matched_intent["responses"])
else:
    # No action needed—just send a random response
    bot_response = random.choice(matched_intent["responses"])

print(bot_response)
Step 5: Handle Context-Aware Actions (Optional)

Since you're building a contextual bot, you might want actions to depend on previous conversation context. For example, if a user asks "What's the weather in London?", you'll need to pass the location to your weather function. To do this:

  • Use the context_set and context_filter fields from the tutorial to track relevant context
  • Modify your action functions to accept context parameters, like:
def get_current_weather(location):
    return f"The weather in {location} is sunny with a high of 26°C."

Then, extract the location from the user's input or stored context and pass it to the function when executing the action.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:55:03