Watson Assistant使用Java SDK维护对话

时间:2018-08-16 11:00:31

标签: ibm-cloud ibm-watson watson-conversation

我正在尝试实现一个聊天助手,使用angular作为客户端并从Java端调用Watson Assistant API。

对于第一个呼叫,我发送了一个空的输入消息,当我在响应中收到上下文时,将其设置为下一个消息输入,以保持对话上下文。

这是Java代码

import javax.annotation.PostConstruct;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xxxx.repapp.assistant.MessageInput;
import com.ibm.watson.developer_cloud.assistant.v1.Assistant;
import com.ibm.watson.developer_cloud.assistant.v1.model.InputData;
import com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions;
import com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse;
import com.ibm.watson.developer_cloud.service.exception.NotFoundException;
import com.ibm.watson.developer_cloud.service.exception.RequestTooLargeException;
import com.ibm.watson.developer_cloud.service.exception.ServiceResponseException;

@RestController
@RequestMapping("/app")
public class ConversationResource {

    private static final String WORKSPACE_ID = "";
    private static final String USERNAME = "";
    private static final String PASSWORD = "";

    Assistant service = new Assistant("2018-02-16");

    @PostConstruct
    public void init() {
        service.setUsernameAndPassword(USERNAME, PASSWORD);
    }

    @RequestMapping(value = "rest/conversation/message", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public MessageResponse consecutiveMessages(@RequestBody MessageInput messageInput) {
        try {
            InputData input = new InputData.Builder(messageInput.getText()).build();
            MessageOptions options = new MessageOptions.Builder(WORKSPACE_ID).input(input)
                    .context(messageInput.getContext()).build();
            MessageResponse response = service.message(options).execute();
            return response;
        } catch (NotFoundException e) {
            // Handle Not Found (404) exception
        } catch (RequestTooLargeException e) {
            // Handle Request Too Large (413) exception
        } catch (ServiceResponseException e) {
            // Base class for all exceptions caused by error responses from the
            // service
            System.out.println("Service returned status code " + e.getStatusCode() + ": " + e.getMessage());
        }
        return null;
    }

    @RequestMapping(value = "rest/conversation/initialMessage", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public MessageResponse initialMessage() {
        InputData input = new InputData.Builder("").build();
        MessageOptions options = new MessageOptions.Builder(WORKSPACE_ID).input(input).build();

        // sync way
        MessageResponse response = service.message(options).execute();
        return response;

        // async way
        /*
         * service.message(options).enqueue(new
         * ServiceCallback<MessageResponse>() {
         * 
         * @Override public void onResponse(MessageResponse response) {
         * System.out.println(response); }
         * 
         * @Override public void onFailure(Exception e) { } });
         */
    }

}

MessageInput类为

import com.ibm.watson.developer_cloud.assistant.v1.model.Context;

public class MessageInput extends com.ibm.watson.developer_cloud.assistant.v1.model.MessageInput{

    private Context context;

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = contextId;
    }   
}

当我必须继续对话时,对话将在不保持上下文的情况下重新开始。请查看下面的对话流程。

欢迎意图响应

{
  "output": {
    "text": [
      "Hello I am foo assistant. How can I help you?"
    ],
    "nodes_visited": [
      "Welcome"
    ],
    "log_messages": []
  },
  "input": {
    "text": ""
  },
  "intents": [],
  "entities": [],
  "context": {
    "conversation_id": "b935786e-7e9d-499e-bb65-b6ddd23605a0",
    "system": {
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1.0,
      "dialog_request_counter": 1.0,
      "_node_output_map": {
        "Welcome": {
          "0": [
            0.0
          ]
        }
      },
      "branch_exited": true,
      "branch_exited_reason": "completed"
    }
  }
}
设置输入文本和上下文后,在下一个请求中设置

MessageOptions

{
  "workspaceId": "*************",
  "input": {
    "text": "submit meter read"
  },
  "context": {
    "output": {
      "text": [
        "Hello I am foo assistant. How can I help you?"
      ],
      "nodes_visited": [
        "Welcome"
      ],
      "log_messages": []
    },
    "input": {
      "text": ""
    },
    "intents": [],
    "entities": [],
    "context": {
      "conversation_id": "b935786e-7e9d-499e-bb65-b6ddd23605a0",
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "root"
          }
        ],
        "dialog_turn_counter": 1,
        "dialog_request_counter": 1,
        "_node_output_map": {
          "Welcome": {
            "0": [
              0
            ]
          }
        },
        "branch_exited": true,
        "branch_exited_reason": "completed"
      }
    }
  }
}
null
{
  "output": {
    "text": [
      "Hello I am foo assistant. How can I help you?"
    ],
    "nodes_visited": [
      "Welcome"
    ],
    "log_messages": []
  },
  "input": {
    "text": ""
  },
  "intents": [],
  "entities": [],
  "context": {
    "conversation_id": "b935786e-7e9d-499e-bb65-b6ddd23605a0",
    "system": {
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1,
      "dialog_request_counter": 1,
      "_node_output_map": {
        "Welcome": {
          "0": [
            0
          ]
        }
      },
      "branch_exited": true,
      "branch_exited_reason": "completed"
    }
  }
}
null
{
  "text": "submit meter read"
}
输入读表日期后下一次

消息选项

{
  "workspaceId": "*************",
  "input": {
    "text": "2018-09-09"
  },
  "context": {
    "output": {
      "text": [
        "Please enter meter read date"
      ],
      "nodes_visited": [
        "node_1_1534239058536",
        "handler_4_1534239240239",
        "slot_2_1534239240239"
      ],
      "log_messages": []
    },
    "input": {
      "text": "submit meter read"
    },
    "intents": [
      {
        "intent": "submit_meter_read",
        "confidence": 0.9712400913238526
      }
    ],
    "entities": [],
    "context": {
      "output": {
        "text": [
          "Hello I am foo assistant. How can I help you?"
        ],
        "nodes_visited": [
          "Welcome"
        ],
        "log_messages": []
      },
      "input": {
        "text": ""
      },
      "intents": [],
      "entities": [],
      "context": {
        "conversation_id": "b935786e-7e9d-499e-bb65-b6ddd23605a0",
        "system": {
          "dialog_stack": [
            {
              "dialog_node": "root"
            }
          ],
          "dialog_turn_counter": 1,
          "dialog_request_counter": 1,
          "_node_output_map": {
            "Welcome": {
              "0": [
                0
              ]
            }
          },
          "branch_exited": true,
          "branch_exited_reason": "completed"
        }
      },
      "conversation_id": "ccfba8ad-06e2-4a74-95e3-20f8251c264c",
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "slot_2_1534239240239",
            "state": "in_progress"
          }
        ],
        "dialog_turn_counter": 1,
        "dialog_request_counter": 1,
        "_node_output_map": {}
      }
    }
  }
}

现在,如果您观察到以下响应,则预期的响应应继续询问另外一个空位,但该位置将被重置。

{
  "output": {
    "text": [
      "I didn't understand. You can try rephrasing. I can help you with things like meter read submission, raising a complaint, and giving some general information."
    ],
    "nodes_visited": [
      "Anything else"
    ],
    "log_messages": []
  },
  "input": {
    "text": "2018-09-09"
  },
  "intents": [],
  "entities": [
    {
      "entity": "sys-number",
      "location": [
        0.0,
        4.0
      ],
      "value": "2018",
      "confidence": 1.0,
      "metadata": {
        "numeric_value": 2018.0
      }
    },
    {
      "entity": "sys-date",
      "location": [
        0.0,
        10.0
      ],
      "value": "2018-09-09",
      "confidence": 1.0,
      "metadata": {
        "calendar_type": "GREGORIAN",
        "timezone": "GMT"
      }
    },
    {
      "entity": "sys-number",
      "location": [
        4.0,
        7.0
      ],
      "value": "-9",
      "confidence": 1.0,
      "metadata": {
        "numeric_value": -9.0
      }
    },
    {
      "entity": "sys-number",
      "location": [
        7.0,
        10.0
      ],
      "value": "-9",
      "confidence": 1.0,
      "metadata": {
        "numeric_value": -9.0
      }
    }
  ],
  "context": {
    "output": {
      "text": [
        "Please enter meter read date"
      ],
      "nodes_visited": [
        "node_1_1534239058536",
        "handler_4_1534239240239",
        "slot_2_1534239240239"
      ],
      "log_messages": []
    },
    "input": {
      "text": "submit meter read"
    },
    "intents": [
      {
        "intent": "submit_meter_read",
        "confidence": 0.9712400913238526
      }
    ],
    "entities": [],
    "context": {
      "output": {
        "text": [
          "Hello I am foo assistant. How can I help you?"
        ],
        "nodes_visited": [
          "Welcome"
        ],
        "log_messages": []
      },
      "input": {
        "text": ""
      },
      "intents": [],
      "entities": [],
      "context": {
        "conversation_id": "b935786e-7e9d-499e-bb65-b6ddd23605a0",
        "system": {
          "dialog_stack": [
            {
              "dialog_node": "root"
            }
          ],
          "dialog_turn_counter": 1.0,
          "dialog_request_counter": 1.0,
          "_node_output_map": {
            "Welcome": {
              "0": [
                0.0
              ]
            }
          },
          "branch_exited": true,
          "branch_exited_reason": "completed"
        }
      },
      "conversation_id": "ccfba8ad-06e2-4a74-95e3-20f8251c264c",
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "slot_2_1534239240239",
            "state": "in_progress"
          }
        ],
        "dialog_turn_counter": 1.0,
        "dialog_request_counter": 1.0,
        "_node_output_map": {}
      }
    },
    "conversation_id": "39f82cb9-e0f1-47b9-845e-892c0d589aed",
    "system": {
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1.0,
      "dialog_request_counter": 1.0,
      "_node_output_map": {
        "Anything else": {
          "0": [
            0.0,
            0.0,
            2.0,
            1.0
          ]
        }
      },
      "branch_exited": true,
      "branch_exited_reason": "completed"
    }
  }
}

上面的代码中缺少的地方,请帮助我保持对话流程。谢谢

1 个答案:

答案 0 :(得分:0)

您需要发送从响应获得的上下文。您似乎从输入对象中检索了上下文。上下文信息从响应转移到您的MessageInput对象的哪里?

您可能已经看到此示例显示了两个连续的消息:https://github.com/watson-developer-cloud/java-sdk/tree/master/assistant