Guida rapida: interazioni con l'API

Per ogni turno di conversazione, ha luogo un'interazione. Durante un'interazione, un utente finale invia un input a Dialogflow, e Dialogflow invia una risposta. Hai due opzioni per implementare il sistema per gestire le interazioni, ad esempio tramite l'API o un'integrazione.

Quando utilizzando l'API, il sistema deve gestire quanto segue:

  • Crea un agente.
  • Fornisci un'interfaccia utente per gli utenti finali.
  • Chiama l'API Dialogflow per ogni svolta di conversazione per inviare input utente finale all'API.
  • A meno che le risposte dell'agente non siano puramente statiche (non comuni), devi ospitare un servizio webhook per gestire i webhook abilitati fulfillment.

Se utilizzi un integrazione, il sistema deve gestire solo quanto segue:

  • Crea un agente.
  • Facoltativamente, implementa un servizio webhook.

Il seguente diagramma mostra i passaggi che vengono eseguiti per un solo turno di conversazione durante una sessione.

Diagramma di flusso dell'API.

  1. L'utente finale digita o dice qualcosa, noto come input dell'utente finale.
  2. L'interfaccia utente o il sistema di integrazione riceve l'input. e la inoltra all'API Dialogflow in una richiesta di rilevamento dell'intento.
  3. L'API Dialogflow riceve la richiesta di rilevamento di intent. Corrisponde all'input di un intent o a un parametro del modulo imposta i parametri in base alle esigenze e aggiorna lo stato della sessione. Se deve chiamare un fulfillment abilitato per webhook, invia una richiesta webhook al tuo servizio webhook altrimenti vai al passaggio 6.
  4. Il tuo servizio webhook riceve la richiesta di webhook. Il servizio esegue le azioni necessarie, come le chiamate ad API esterne, eseguire query o aggiornare un database e così via.
  5. Il servizio webhook crea una risposta e invia un la risposta webhook a Dialogflow.
  6. Dialogflow crea una risposta di rilevamento dell'intento. Se è stato chiamato un webhook, utilizza la risposta fornita. nella risposta webhook. Se non è stato chiamato alcun webhook, utilizza la risposta statica. definiti nell'agente. Dialogflow invia una risposta di rilevamento dell'intento all'interfaccia utente o al sistema di integrazione.
  7. L'interfaccia utente o il sistema di integrazione riceve la risposta di rilevamento dell'intento e inoltra il testo o la risposta audio all'utente finale.
  8. L'utente finale vede o sente la risposta.

Scopo della guida

Questa guida mostra come chiamare l'API per un turno di conversazione per un agente che non utilizza un'integrazione (passaggio 2 del diagramma precedente). Questa guida non mostra come implementare un'interfaccia utente per il tuo utente finale.

Prima di iniziare

Prima di leggere questa guida, devi procedere nel seguente modo:

  1. Leggi le nozioni di base su Dialogflow CX.
  2. Esegui la procedura di configurazione.
  3. Crea un nuovo agente o continua a utilizzare quello creato Crea un agente.

Raccogli ID

Gli esempi riportati di seguito richiedono diversi ID come input. Per trovare l'ID progetto, l'ID regione e l'ID agente:

  1. Apri la console Dialogflow CX.
  2. Seleziona il tuo progetto Google Cloud per aprire il selettore di agenti.
  3. Fai clic sull'opzione per un agente nell'elenco.
  4. Fai clic sul nome della copia .
  5. Viene copiato il nome identificativo completo dell'agente, che include l'ID progetto, l'ID regione e l'ID agente nel formato:
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

È necessario anche un ID sessione. R sessione rappresenta una conversazione tra un agente Dialogflow e un utente finale. Puoi creare un ID sessione univoco all'inizio di una conversazione e utilizzarlo per ogni turno della conversazione. Per provare l'API, puoi usare qualsiasi ID stringa di massimo 36 byte, come test-session-123.

Rilevamento dell'intenzione di chiamata

Gli esempi riportati di seguito chiamano il metodo Sessions.detectIntent.

Seleziona un protocollo e una versione per il riferimento sessione:

Protocollo V3 V3beta1
REST Risorsa di sessione Risorsa di sessione
RPC Interfaccia di sessione Interfaccia di sessione
C++ SessionsClient Non disponibile
C# SessionsClient Non disponibile
Vai SessionsClient Non disponibile
Java SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP Non disponibile Non disponibile
Python SessionsClient SessionsClient
Ruby Non disponibile Non disponibile

REST

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud
  • AGENT_ID: il tuo ID agente
  • REGION_ID: il tuo ID regione
  • SESSION_ID: il tuo ID sessione
  • END_USER_INPUT: l'input utente finale

Metodo HTTP e URL:

POST https://REGION_ID-dialogflow.googleapis.com/v3/projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID/sessions/SESSION_ID:detectIntent

Corpo JSON della richiesta:

{
  "queryInput": {
    "text": {
      "text": "END_USER_INPUT"
    },
    "languageCode": "en"
  },
  "queryParams": {
    "timeZone": "America/Los_Angeles"
  }
}

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "responseId": "38e8f23d-eed2-445e-a3e7-149b242dd669",
  "queryResult": {
    "text": "I want to buy a shirt",
    "languageCode": "en",
    "responseMessages": [
      {
        "text": {
          "text": [
            "Ok, let's start a new order."
          ]
        }
      },
      {
        "text": {
          "text": [
            "I'd like to collect a bit more information from you."
          ]
        }
      },
      {
        "text": {
          "text": [
            "What color would you like?"
          ]
        }
      },
      {}
    ],
    "currentPage": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/flows/00000000-0000-0000-0000-000000000000/pages/ce0b88c4-9292-455c-9c59-ec153dad94cc",
      "displayName": "New Order"
    },
    "intent": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
      "displayName": "order.new"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": { ... },
    "match": {
      "intent": {
        "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
        "displayName": "order.new"
      },
      "resolvedInput": "I want to buy a shirt",
      "matchType": "INTENT",
      "confidence": 1
    }
  }
}

Java

Per eseguire l'autenticazione in Dialogflow, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest;
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse;
import com.google.cloud.dialogflow.cx.v3beta1.QueryInput;
import com.google.cloud.dialogflow.cx.v3beta1.QueryResult;
import com.google.cloud.dialogflow.cx.v3beta1.SessionName;
import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient;
import com.google.cloud.dialogflow.cx.v3beta1.SessionsSettings;
import com.google.cloud.dialogflow.cx.v3beta1.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntent {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntent(
      String projectId,
      String locationId,
      String agentId,
      String sessionId,
      List<String> texts,
      String languageCode)
      throws IOException, ApiException {
    SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder();
    if (locationId.equals("global")) {
      sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443");
    } else {
      sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443");
    }
    SessionsSettings sessionsSettings = sessionsSettingsBuilder.build();

    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client.

    // Note: close() needs to be called on the SessionsClient object to clean up resources
    // such as threads. In the example below, try-with-resources is used,
    // which automatically calls close().
    try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
      // Set the session name using the projectID (my-project-id), locationID (global), agentID
      // (UUID), and sessionId (UUID).
      SessionName session =
          SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId);

      // TODO : Uncomment if you want to print session path
      // System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input.
      for (String text : texts) {
        // Set the text (hello) for the query.
        TextInput.Builder textInput = TextInput.newBuilder().setText(text);

        // Build the query with the TextInput and language code (en-US).
        QueryInput queryInput =
            QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build();

        // Build the DetectIntentRequest with the SessionName and QueryInput.
        DetectIntentRequest request =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .build();

        // Performs the detect intent request.
        DetectIntentResponse response = sessionsClient.detectIntent(request);

        // Display the query result.
        QueryResult queryResult = response.getQueryResult();

        // TODO : Uncomment if you want to print queryResult
        // System.out.println("====================");
        // System.out.format("Query Text: '%s'\n", queryResult.getText());
        // System.out.format(
        //     "Detected Intent: %s (confidence: %f)\n",
        //     queryResult.getIntent().getDisplayName(),
        //         queryResult.getIntentDetectionConfidence());

        queryResults.put(text, queryResult);
      }
    }
    return queryResults;
  }
}

Node.js

Per eseguire l'autenticazione in Dialogflow, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const location = 'global';
// const agentId = 'my-agent';
// const query = 'Hello';
// const languageCode = 'en'

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const location = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient();

async function detectIntentText() {
  const sessionId = Math.random().toString(36).substring(7);
  const sessionPath = client.projectLocationAgentSessionPath(
    projectId,
    location,
    agentId,
    sessionId
  );
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  for (const message of response.queryResult.responseMessages) {
    if (message.text) {
      console.log(`Agent Response: ${message.text.text}`);
    }
  }
  if (response.queryResult.match.intent) {
    console.log(
      `Matched Intent: ${response.queryResult.match.intent.displayName}`
    );
  }
  console.log(
    `Current Page: ${response.queryResult.currentPage.displayName}`
  );
}

detectIntentText();

Python

Per eseguire l'autenticazione in Dialogflow, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.

def run_sample():
    # TODO(developer): Replace these values when running the function
    project_id = "YOUR-PROJECT-ID"
    # For more information about regionalization see https://cloud.google.com/dialogflow/cx/docs/how/region
    location_id = "YOUR-LOCATION-ID"
    # For more info on agents see https://cloud.google.com/dialogflow/cx/docs/concept/agent
    agent_id = "YOUR-AGENT-ID"
    agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
    # For more information on sessions see https://cloud.google.com/dialogflow/cx/docs/concept/session
    session_id = uuid.uuid4()
    texts = ["Hello"]
    # For more supported languages see https://cloud.google.com/dialogflow/es/docs/reference/language
    language_code = "en-us"

    detect_intent_texts(agent, session_id, texts, language_code)


def detect_intent_texts(agent, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    for text in texts:
        text_input = session.TextInput(text=text)
        query_input = session.QueryInput(text=text_input, language_code=language_code)
        request = session.DetectIntentRequest(
            session=session_path, query_input=query_input
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print(f"Query text: {response.query_result.text}")
        response_messages = [
            " ".join(msg.text.text) for msg in response.query_result.response_messages
        ]
        print(f"Response text: {' '.join(response_messages)}\n")

Produzione

Prima di eseguire l'agente in produzione, assicurati di implementare best practice per la produzione.