2 min read 2 days ago

Modify a Query

If you want your chatbot to be aware of certain information that might change (such as time, events, last news, etc.) or that might differ from user to user (such as name, location, interests, etc.) dynamically, then you can use the mwai_ai_query filter. This filter allows you to modify the query before it’s sent, which is basically the opposite of what we did when modifying the reply.

This lets us modify the instructions, the user’s message, and the model context, and run processes before the query is handled by the AI.

For instance, we could use placeholders in our instructions and modify them based on the current situation.

add_filter( 'mwai_ai_query', function ( $query ) {

  // Check if the $query object is an instance of Meow_MWAI_Query_Text
  if ( $query instanceof Meow_MWAI_Query_Text ) {
    // Replace the {CLIENT_NAME} placeholder with the user's name
    $name = get_user_meta( get_current_user_id(), 'name', true );
    $query->set_instructions( str_replace( '{CLIENT_NAME}', $name, $query->instructions ) );

    // Replace the {CLIENT_LOCATION} placeholder with the user's location
    $location = get_user_meta( get_current_user_id(), 'location', true );
    $query->set_instructions( str_replace( '{CLIENT_LOCATION}', $location, $query->instructions ) );

    // Replace the {CLIENT_LAST_DELIVERY} placeholder with the user's last delivery
    $last_delivery = get_user_meta( get_current_user_id(), 'last_delivery', true );
    $query->set_instructions( str_replace( '{CLIENT_LAST_DELIVERY}', $last_delivery, $query->instructions ) );

    // Call a weather API to replace {WEATHER} with current weather
    $api_url = 'https://api.weather.com/current?location=' . urlencode($location);
    $response = wp_remote_get( $api_url );

    if ( is_array( $response ) && ! is_wp_error( $response ) ) {
      $weather_data = json_decode( wp_remote_retrieve_body( $response ) );
      $current_weather = $weather_data->current->temperature;

      // Replace the {WEATHER} placeholder with the current weather
      $query->set_instructions( str_replace( '{WEATHER}', $current_weather . '°C', $query->instructions ) );
    }
  }

  return $query;
}, 10, 2 );