Dialogflow CX 将实体导入为 CSV

Dialogflow CX import entities as CSV

我想创建一个自定义实体类型来保存包含 100 个产品名称的列表。在 Dialogflow ES 中,这很容易做到,因为您只需导入一个包含自定义实体所有条目的 csv。

例如:

"New York City", "New York City", "NYC", "New York City, USA"
"Philadelphia", "Philadelphia", "Philly", "Philadelphia, USA"

可以导入为 csv。

必须为每个自定义实体手动执行此操作将非常繁琐且耗时,因为有数百个这样的项目。

为此查看官方 Dialogflow CX REST API 文档。 https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3/projects.locations.agents.entityTypes/create

下面是一个示例代码,它使用 pandas 读取 sample.csv 中的列 City 并创建一个实体。 Python

import requests
import pandas as pd
from google.oauth2 import service_account
from google.cloud.dialogflowcx_v3beta1.types import entity_type
from google.auth.transport.requests import AuthorizedSession

# sample csv data
# Name,City
# John,New York City
# Alice,Philadelphia

data = pd.read_csv("sample.csv") 
cities = data['City'].tolist()
entity_json = []
for each in cities:
    each_entity_value = {}
    each_entity_value['value'] = each
    each_entity_value['synonyms'] = [each]
    entity_json.append(each_entity_value)
print(entity_json)
print('***************************************')

# download the service account json with the required permissions to call the cx agent
credentials = service_account.Credentials.from_service_account_file(
    'credentials.json')
scoped_credentials = credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(scoped_credentials)
kind = entity_type.EntityType.Kind.KIND_MAP

# configure these variables before running the script
project_id = #YOUR-PROJECT-ID
agent_id = #YOUR-CX-AGENT-ID
location = #AGENT-LOCATION-ID
response = authed_session.post('https://dialogflow.googleapis.com/v3/projects/'+ project_id + '/locations/' + location + '/agents/' + agent_id + '/entityTypes',
                                json={
                                        "kind": kind,
                                        "displayName": "city-names",
                                        "entities": entity_json
                                    }
                                )                        

response_txt = response.text
print(response_txt)

这是要求。

# requirements.txt
# google-cloud-dialogflow-cx==0.5.0
# pandas==1.1.5
# requests==2.21.0
# requests-oauthlib==1.3.0

您始终可以先在 API 资源管理器上尝试,方法是提供所需的参数。

parent: projects/<project-id>/locations/<location>/agents/<agent-id>
languageCode: en
Request body: {
  "displayName": "test",
  "entities": [
    {
      "value": "string",
      "synonyms": [
        "string",
        "str"
      ]
    }
  ],
  "kind": "KIND_MAP"
}

启用凭据并执行。您将获得 200 成功响应,并且将在 CX 代理控制台中创建一个新实体。