как создать намерения с контекстом из DialogFlow API

#google-cloud-platform #nlp #dialogflow-es

#google-cloud-platform #nlp #диалоговые потоки

Вопрос:

Я пытаюсь пакетно создать кучу намерений, и я хочу назначить контекст ввода

Насколько я могу видеть, для этого не должен требоваться сеанс, поскольку это просто имя контекста строки. Как это в графическом интерфейсе: введите описание изображения здесь

Выполняемый мной вызов API создает намерение, не выдает ошибку, но я не могу отобразить контексты.

Есть ли какой-то странный формат для contexts параметра? Я экспортировал zip-файл и просмотрел файлы JSON, они представляют собой просто массив строк.

Я видел другой код, который, похоже, требует идентификатора сеанса пользовательского диалога для создания контекстов. Но намерения у нас глобальные — не для одного разговора. И я предполагаю, что они предназначены только для отслеживания контекста в рамках одного сеанса разговора (или разработки Google astronaut).

Данные, которые я публикую, выглядят следующим образом

Здесь есть пример Google, который не затрагивает контекстыhttps://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent

Я пробовал контексты в различных форматах, но безуспешно

 
  // this is the part that doesn't work
  // const contexts = [{
  //   // name: `${sessionPath}/contexts/${name}`,
  //   // name: 'test context name'
  // }]

  const contexts = [
    'theater-critics'
  ]
  
 createIntentRequest {
  "parent": "projects/XXXXXXXX-XXXXXXXX/agent",
  "intent": {
    "displayName": "test 4",
    "trainingPhrases": [
      {
        "type": "EXAMPLE",
        "parts": [
          {
            "text": "this is a test phrase"
          }
        ]
      },
      {
        "type": "EXAMPLE",
        "parts": [
          {
            "text": "this is a another test phrase"
          }
        ]
      }
    ],
    "messages": [
      {
        "text": {
          "text": [
            "this is a test response"
          ]
        }
      }
    ],
    "contexts": [
      "theater-critics"
    ]
  }
}
Intent projects/asylum-287516/agent/intents/XXXXXXXX-e852-4c09-bda6-e524b8329db8 created
  

Полный код JS (TS) ниже для всех остальных

 
import { DfConfig } from './DfConfig'
const dialogflow = require('@google-cloud/dialogflow');

const testData = {
  displayName: 'test 4',
  trainingPhrasesParts: [
    "this is a test phrase",
    "this is a another test phrase"
  ],
  messageTexts: [
    'this is a test response'
  ]
}
// const messageTexts = 'Message texts for the agent's response when the intent is detected, e.g. 'Your reservation has been confirmed';

const intentsClient = new dialogflow.IntentsClient();

export const DfCreateIntent = async () => {

  const agentPath = intentsClient.agentPath(DfConfig.projectId);

  const trainingPhrases = [];

  testData.trainingPhrasesParts.forEach(trainingPhrasesPart => {
    const part = {
      text: trainingPhrasesPart,
    };

    // Here we create a new training phrase for each provided part.
    const trainingPhrase = {
      type: 'EXAMPLE',
      parts: [part],
    };

    // @ts-ignore
    trainingPhrases.push(trainingPhrase);
  });

  const messageText = {
    text: testData.messageTexts,
  };

  const message = {
    text: messageText,
  };

  // this is the part that doesn't work
  // const contexts = [{
  //   // name: `${sessionPath}/contexts/${name}`,
  //   // name: 'test context name'
  // }]

  const contexts = [
    'theater-critics'
  ]

  const intent = {
    displayName: testData.displayName,
    trainingPhrases: trainingPhrases,
    messages: [message],
    contexts
  };

  const createIntentRequest = {
    parent: agentPath,
    intent: intent,
  };

  console.log('createIntentRequest', JSON.stringify(createIntentRequest, null, 2))

  // Create the intent
  const [response] = await intentsClient.createIntent(createIntentRequest);
  console.log(`Intent ${response.name} created`);
}

// createIntent();

  

Ответ №1:

обновление, разработанное на основе этого https://cloud.google.com/dialogflow/es/docs/reference/rest/v2/projects.agent.intents#Intent

 
  const contextId = 'runner'
  const contextName = `projects/${DfConfig.projectId}/agent/sessions/-/contexts/${contextId}`
  const inputContextNames = [
    contextName
  ]

  const intent = {
    displayName: testData.displayName,
    trainingPhrases: trainingPhrases,
    messages: [message],
    inputContextNames
  };

  

Комментарии:

1. Просто для завершения вашего ответа, если вы хотите добавить inputContextNames, это должен быть список строк. Однако, если вы хотите добавить outputContexts, это должен быть объект (см. Следующую ссылку cloud.google.com/dialogflow/es/docs/reference/rest/v2 /… )