Create an agent with the API

Normally, you create agents using the console. However, in certain advanced scenarios, you may find it easier to create agents with the API.

The following examples show how to call the SetAgent method for the Agent.

Java


import com.google.cloud.dialogflow.v2.Agent;
import com.google.cloud.dialogflow.v2.Agent.Builder;
import com.google.cloud.dialogflow.v2.AgentsClient;
import com.google.cloud.dialogflow.v2.AgentsSettings;
import java.io.IOException;

public class SetAgent {

  public static void main(String[] args) throws IOException {
    String projectId = "my-project-id";

    // The display name will set the name of your agent
    String displayName = "my-display-name";

    setAgent(projectId, displayName);
  }

  public static Agent setAgent(String parent, String displayName) throws IOException {

    AgentsSettings agentsSettings = AgentsSettings.newBuilder().build();
    try (AgentsClient client = AgentsClient.create(agentsSettings)) {
      // Set the details of the Agent to create
      Builder build = Agent.newBuilder();

      build.setDefaultLanguageCode("en");
      build.setDisplayName(displayName);

      Agent agent = build.build();

      // Make API request to create agent
      Agent response = client.setAgent(agent);
      System.out.println(response);
      return response;
    }
  }
}

Node.js

const {AgentsClient} = require('@google-cloud/dialogflow');

const parent = 'projects/' + parentId + '/locations/global';

const agent = {
  parent: parent,
  displayName: displayName,
  defaultLanguageCode: 'en',
  timeZone: 'America/Los_Angeles',
};

const client = new AgentsClient();

async function setAgent() {
  const request = {
    agent,
  };

  const [response] = await client.setAgent(request);
  console.log(`response: ${JSON.stringify(response, null, 2)}`);
}
await setAgent();

Python


from google.cloud.dialogflow_v2 import Agent
from google.cloud.dialogflow_v2 import AgentsClient


def set_agent(project_id, display_name):

    agents_client = AgentsClient()

    parent = agents_client.common_project_path(project_id)

    agent = Agent(
        parent=parent,
        display_name=display_name,
        default_language_code="en",
        time_zone="America/Los_Angeles",
    )

    response = agents_client.set_agent(request={"agent": agent})

    return response