Orientar o comportamento do agente com contexto criado

Esta página descreve a estrutura recomendada para escrever comandos eficazes para seus agentes de dados da API Conversational Analytics. Esses comandos são contextos criados por você e definidos como strings usando o parâmetro system_instruction. Instruções de sistema bem estruturadas podem melhorar a acurácia e a relevância das respostas fornecidas pela API.

O que são instruções do sistema?

As instruções do sistema são orientações definidas pelo usuário que os desenvolvedores podem fornecer para moldar o comportamento de um agente de dados e refinar as respostas da API. As instruções do sistema fazem parte do contexto que a API usa para responder a perguntas. Esse contexto também inclui fontes de dados conectadas (tabelas do BigQuery, análises do Looker, fontes de dados do Looker Studio) e histórico de conversas (para conversas em várias etapas).

Ao fornecer orientações claras e estruturadas por meio de instruções do sistema, você pode melhorar a capacidade do agente de interpretar as perguntas dos usuários e gerar respostas úteis e precisas. Instruções de sistema bem definidas são especialmente úteis se você estiver se conectando a dados, como tabelas do BigQuery, em que pode não haver uma camada semântica predefinida, como acontece com uma análise do Looker.

Por exemplo, é possível usar instruções do sistema para fornecer os seguintes tipos de orientação a um agente:

  • Lógica específica da empresa: defina um cliente "fiel" como aquele que fez mais de cinco compras em um determinado período.
  • Formatação da resposta: resuma todas as respostas do seu agente de dados em 20 palavras ou menos para economizar tempo dos usuários.
  • Apresentação de dados: formate todos os números de acordo com o guia de estilo da empresa.

Fornecer instruções do sistema

É possível fornecer instruções do sistema à API Conversational Analytics como uma string formatada em YAML usando o parâmetro system_instruction. Embora o parâmetro system_instruction seja opcional, recomendamos fornecer instruções de sistema bem estruturadas para respostas precisas e relevantes.

Você pode definir a string formatada em YAML no seu código durante a configuração inicial, conforme mostrado em Determinar as configurações iniciais e a autenticação (HTTP) ou Especificar o projeto de faturamento e as instruções do sistema (SDK do Python). Em seguida, inclua o parâmetro system_instruction nas seguintes chamadas de API:

Modelo YAML para instruções do sistema

O modelo a seguir mostra a estrutura YAML recomendada para a string que você fornece ao parâmetro system_instruction, incluindo as chaves disponíveis e os tipos de dados esperados. Para ver um exemplo de instrução do sistema com valores preenchidos, consulte Exemplo: instruções do sistema.

Use o modelo YAML a seguir para fornecer suas próprias instruções do sistema:

- system_instruction: str # A description of the expected behavior of the agent. For example: You are a sales agent.
- tables: # A list of tables to describe for the agent.
    - table: # Details about a single table that is relevant for the agent.
        - name: str # The name of the table.
        - description: str # A description of the table.
        - synonyms: list[str] # Alternative terms for referring to the table.
        - tags: list[str] # Keywords or tags that are associated with the table.
        - fields: # Details about columns (fields) within the table.
            - field: # Details about a single column within the current table.
                - name: str # The name of the column.
                - description: str # A description of the column.
                - synonyms: list[str] # Alternative terms for referring to the column.
                - tags: list[str] # Keywords or tags that are associated with the column.
                - sample_values: list[str] # Sample values that are present within the column.
                - aggregations: list[str] # Commonly used or default aggregations for the column.
        - measures: # A list of calculated metrics (measures) for the table.
            - measure: # Details about a single measure within the table.
                - name: str # The name of the measure.
                - description: str # A description of the measure.
                - exp: str # The expression that is used to construct the measure.
                - synonyms: list[str] # Alternative terms for referring to the measure.
        - golden_queries: # A list of important or popular ("golden") queries for the table.
            - golden_query: # Details about a single golden query.
                - natural_language_query: str # The natural language query.
                - sql_query: str # The SQL query that corresponds to the natural language query.
        - golden_action_plans: # A list of suggested multi-step plans for answering specific queries.
            - golden_action_plan: # Details about a single action plan.
                - natural_language_query: str # The natural language query.
                - action_plan: # A list of the steps for this action plan.
                    - step: str # A single step within the action plan.
    - relationships: # A list of join relationships between tables.
        - relationship: # Details about a single join relationship.
            - name: str # The name of this join relationship.
            - description: str # A description of the relationship.
            - relationship_type: str # The join relationship type: one-to-one, one-to-many, many-to-one, or many-to-many.
            - join_type: str # The join type: inner, outer, left, right, or full.
            - left_table: str # The name of the left table in the join.
            - right_table: str # The name of the right table in the join.
            - relationship_columns: # A list of columns that are used for the join.
                - left_column: str # The join column from the left table.
                - right_column: str # The join column from the right table.
- glossaries: # A list of definitions for glossary business terms, jargon, and abbreviations.
    - glossary: # The definition for a single glossary item.
        - term: str # The term, phrase, or abbreviation to define.
        - description: str # A description or definition of the term.
        - synonyms: list[str] # Alternative terms for the glossary entry.
- additional_descriptions: # A list of any other general instructions or content.
    - text: str # Any additional general instructions or context not covered elsewhere.

Principais componentes das instruções do sistema

As seções a seguir descrevem os principais componentes das instruções do sistema e como usá-los para melhorar a qualidade das respostas do seu agente.

Definir a função e o perfil do agente com system_instruction

Defina a função e o perfil do agente usando a chave system_instruction. Essa instrução inicial define o tom e o estilo das respostas da API e ajuda o agente a entender o objetivo principal dele.

O bloco de código YAML a seguir mostra a estrutura básica da chave system_instrucction:

- system_instruction: str

Por exemplo, você pode definir um agente como analista de vendas de uma loja de e-commerce fictícia da seguinte maneira:

- system_instruction: >-
    You are an expert sales analyst for a fictitious ecommerce store. You will answer questions about sales, orders, and customer data. Your responses should be concise and data-driven.

Descrever seus dados com tables

A chave tables contém uma lista de descrições de tabelas para o agente e fornece detalhes sobre os dados específicos disponíveis para ele responder a perguntas. Cada objeto table nessa lista contém os metadados de uma tabela específica, incluindo nome, descrição, sinônimos, tags, campos, medidas, consultas e planos de ação de ouro.

O bloco de código YAML a seguir mostra a estrutura básica da chave tables:

- tables:
    - table:
      - name: str # The name of the table.
      - description: str # A description of the table.
      - synonyms: list[str] # Alternative terms for referring to the table.
      - tags: list[str] # Keywords or tags that are associated with the table.
      - fields: # A list of the fields in the table.
      - measures: # A list of the measures in the table.
      - golden_queries: # A list of golden queries for the table.
      - golden_action_plans: # A list of golden action plans for the table.

Por exemplo, o bloco de código YAML a seguir mostra a estrutura básica da chave tables para a tabela bigquery-public-data.thelook_ecommerce.orders:

- tables:
    - table:
        - name: bigquery-public-data.thelook_ecommerce.orders
        - description: Data for customer orders in The Look fictitious e-commerce store.
        - synonyms:
            - sales
            - orders_data
        - tags:
            - ecommerce
            - transaction

Descrever campos usados com frequência com fields

A chave fields, que está aninhada em um objeto table, usa uma lista de objetos de campo para descrever colunas individuais. Nem todos os campos precisam de contexto adicional, mas, para os usados com frequência, incluir mais detalhes pode ajudar a melhorar a performance do agente.

O bloco de código YAML a seguir mostra a estrutura básica da chave fields:

- fields: # Details about columns (fields) within the table.
    - field: # Details about a single column within the current table.
        - name: str # The name of the column.
        - description: str # A description of the column.
        - synonyms: list[str] # Alternative terms for referring to the column.
        - tags: list[str] # Keywords or tags that are associated with the column.
        - sample_values: list[str] # Sample values that are present within the column.
        - aggregations: list[str] # Commonly used or default aggregations for the column.

Por exemplo, o código YAML de amostra a seguir descreve campos principais, como order_id, status, created_at, num_of_items e earnings para a tabela orders:

- tables:
    - table:
        - name: bigquery-public-data.thelook_ecommerce.orders
        - fields:
            - field:
                - name: order_id
                - description: The unique identifier for each customer order.
            - field:
                - name: user_id
                - description: The unique identifier for each customer.
            - field:
                - name: status
                - description: The current status of the order.
                - sample_values:
                    - complete
                    - shipped
                    - returned
            - field:
                - name: created_at
                - description: The timestamp when the order was created.
            - field:
                - name: num_of_items
                - description: The total number of items in the order.
                - aggregations:
                    - sum
                    - avg
            - field:
                - name: earnings
                - description: The sales amount for the order.
                - aggregations:
                    - sum
                    - avg

Definir métricas de negócios com measures

A chave measures, que está aninhada em um objeto table, define métricas ou cálculos de negócios personalizados que não estão diretamente presentes como colunas nas suas tabelas. Fornecer contexto para as medidas ajuda o agente a responder perguntas sobre indicadores principais de desempenho (KPIs) ou outros valores calculados.

O bloco de código YAML a seguir mostra a estrutura básica da chave measures:

- measures: # A list of calculated metrics (measures) for the table.
    - measure: # Details about a single measure within the table.
        - name: str # The name of the measure.
        - description: str # A description of the measure.
        - exp: str # The expression that is used to construct the measure.
        - synonyms: list[str] # Alternative terms for referring to the measure.

Por exemplo, você pode definir uma métrica profit como um cálculo dos ganhos menos o custo da seguinte maneira:

- tables:
    - table:
        - name: bigquery-public-data.thelook_ecommerce.orders
        - measures:
            - measure:
                - name: profit
                - description: Raw profit (earnings minus cost).
                - exp: earnings - cost
                - synonyms:
                    - gains

Melhorar a acurácia com o golden_queries

A chave golden_queries, que está aninhada em um objeto table, usa uma lista de objetos golden_query. As consultas de ouro ajudam o agente a dar respostas mais precisas e relevantes a perguntas comuns ou importantes. Ao fornecer ao agente uma consulta em linguagem natural e a consulta SQL correspondente para cada consulta de ouro, você pode orientar o agente a fornecer resultados de maior qualidade e mais consistentes.

O bloco de código YAML a seguir mostra a estrutura básica da chave golden_queries:

- golden_queries: # A list of important or popular ("golden") queries for the table.
    - golden_query: # Details about a single golden query.
        - natural_language_query: str # The natural language query.
        - sql_query: str # The SQL query that corresponds to the natural language query.

Por exemplo, é possível definir consultas de ouro para análises comuns dos dados na tabela orders da seguinte maneira:

- tables:
    - table:
        - golden_queries:
            - golden_query:
                - natural_language_query: How many orders are there?
                - sql_query: SELECT COUNT(*) FROM sqlgen-testing.thelook_ecommerce.orders
            - golden_query:
                - natural_language_query: How many orders were shipped?
                - sql_query: >-
                    SELECT COUNT(*) FROM sqlgen-testing.thelook_ecommerce.orders
                    WHERE status = 'shipped'

Descrever tarefas de várias etapas com golden_action_plans

A chave golden_action_plans, que está aninhada em um objeto table, usa uma lista de objetos golden_action_plan. É possível usar planos de ação de ouro para dar ao agente exemplos de como lidar com solicitações de várias etapas, como buscar dados e criar uma visualização.

O bloco de código YAML a seguir mostra a estrutura básica da chave golden_action_plans:

- golden_action_plans: # A list of suggested multi-step plans for answering specific queries.
    - golden_action_plan: # Details about a single action plan.
        - natural_language_query: str # The natural language query.
        - action_plan: # A list of the steps for this action plan.
            - step: str # A single step within the action plan.

Por exemplo, é possível definir um plano de ação para mostrar detalhamentos de pedidos por idade e incluir detalhes sobre a consulta SQL e as etapas relacionadas à visualização:

- tables:
    - table:
        - golden_action_plans:
            - golden_action_plan:
                - natural_language_query: Show me the number of orders broken down by age group.
                - action_plan:
                    - step: >-
                        Run a SQL query that joins the table
                        sqlgen-testing.thelook_ecommerce.orders and
                        sqlgen-testing.thelook_ecommerce.users to get a
                        breakdown of order count by age group.
                    - step: >-
                        Create a vertical bar plot using the retrieved data,
                        with one bar per age group.

Definir junções de tabelas com relationships

A chave relationships contém uma lista de relações de junção entre tabelas. Ao definir relações de junção, você ajuda o agente a entender como combinar dados de várias tabelas ao responder a perguntas.

O bloco de código YAML a seguir mostra a estrutura básica da chave relationships:

- relationships: # A list of join relationships between tables.
    - relationship: # Details for a single join relationship.
        - name: str # A unique name for this join relationship.
        - description: str # A description of the relationship.
        - relationship_type: str # The join relationship type (e.g., "one-to-one", "one-to-many", "many-to-one", "many-to-many").
        - join_type: str # The join type (e.g., "inner", "outer", "left", "right", "full").
        - left_table: str # The name of the left table in the join.
        - right_table: str # The name of the right table in the join.
        - relationship_columns: # A list of columns that are used for the join.
            - left_column: str # The join column from the left table.
            - right_column: str # The join column from the right table.

Por exemplo, é possível definir uma relação orders_to_user entre as tabelas bigquery-public-data.thelook_ecommerce.orders e bigquery-public-data.thelook_ecommerce.users da seguinte maneira:

- relationships:
    - relationship:
        - name: orders_to_user
        - description: >-
            Connects customer order data to user information with the user_id and id fields to allow an aggregated view of sales by customer demographics.
        - relationship_type: many-to-one
        - join_type: left
        - left_table: bigquery-public-data.thelook_ecommerce.orders
        - right_table: bigquery-public-data.thelook_ecommerce.users
        - relationship_columns:
            - left_column: user_id
            - right_column: id

Explicar termos comerciais com o glossaries

A chave glossaries lista definições de termos comerciais, jargões e abreviações relevantes para seus dados e caso de uso. Ao fornecer definições de glossário, você ajuda o agente a interpretar e responder com precisão a perguntas que usam uma linguagem comercial específica.

O bloco de código YAML a seguir mostra a estrutura básica da chave glossaries:

- glossaries: # A list of definitions for glossary business terms, jargon, and abbreviations.
    - glossary: # The definition for a single glossary item.
        - term: str # The term, phrase, or abbreviation to define.
        - description: str # A description or definition of the term.
        - synonyms: list[str] # Alternative terms for the glossary entry.

Por exemplo, você pode definir termos como status comerciais comuns e "OMPF" de acordo com seu contexto comercial específico da seguinte forma:

- glossaries:
    - glossary:
        - term: complete
        - description: Represents an order status where the order has been completed.
        - synonyms: 'finish, done, fulfilled'
    - glossary:
        - term: shipped
        - description: Represents an order status where the order has been shipped to the customer.
    - glossary:
        - term: returned
        - description: Represents an order status where the customer has returned the order.
    - glossary:
        - term: OMPF
        - description: Order Management and Product Fulfillment

Incluir mais instruções com additional_descriptions

A chave additional_descriptions lista outras instruções gerais ou contextos não abordados em outras partes das instruções do sistema. Ao fornecer mais descrições, você ajuda o agente a entender melhor o contexto dos seus dados e caso de uso.

O bloco de código YAML a seguir mostra a estrutura básica da chave additional_descriptions:

- additional_descriptions: # A list of any other general instructions or content.
    - text: str # Any additional general instructions or context not covered elsewhere.

Por exemplo, é possível usar a chave additional_descriptions para fornecer informações sobre sua organização da seguinte forma:

- additional_descriptions:
    - text: All the sales data pertains to The Look, a fictitious ecommerce store.
    - text: 'Orders can be of three categories: food, clothes, and electronics.'

Exemplo: instruções do sistema

O exemplo a seguir mostra instruções de sistema de amostra para um agente analista de vendas fictício.

- system_instruction: >-
    You are an expert sales analyst for a fictitious ecommerce store. You will answer questions about sales, orders, and customer data. Your responses should be concise and data-driven.
- tables:
    - table:
        - name: bigquery-public-data.thelook_ecommerce.orders
        - description: Data for orders in The Look, a fictitious ecommerce store.
        - synonyms: sales
        - tags: 'sale, order, sales_order'
        - fields:
            - field:
                - name: order_id
                - description: The unique identifier for each customer order.
            - field:
                - name: user_id
                - description: The unique identifier for each customer.
            - field:
                - name: status
                - description: The current status of the order.
                - sample_values:
                    - complete
                    - shipped
                    - returned
            - field:
                - name: created_at
                - description: >-
                    The date and time at which the order was created in timestamp
                    format.
            - field:
                - name: returned_at
                - description: >-
                    The date and time at which the order was returned in timestamp
                    format.
            - field:
                - name: num_of_items
                - description: The total number of items in the order.
                - aggregations: 'sum, avg'
            - field:
                - name: earnings
                - description: The sales revenue for the order.
                - aggregations: 'sum, avg'
            - field:
                - name: cost
                - description: The cost for the items in the order.
                - aggregations: 'sum, avg'
        - measures:
            - measure:
                - name: profit
                - description: Raw profit (earnings minus cost).
                - exp: earnings - cost
                - synonyms: gains
        - golden_queries:
            - golden_query:
                - natural_language_query: How many orders are there?
                - sql_query: SELECT COUNT(*) FROM sqlgen-testing.thelook_ecommerce.orders
            - golden_query:
                - natural_language_query: How many orders were shipped?
                - sql_query: >-
                    SELECT COUNT(*) FROM sqlgen-testing.thelook_ecommerce.orders
                    WHERE status = 'shipped'
        - golden_action_plans:
            - golden_action_plan:
                - natural_language_query: Show me the number of orders broken down by age group.
                - action_plan:
                    - step: >-
                        Run a SQL query that joins the table
                        sqlgen-testing.thelook_ecommerce.orders and
                        sqlgen-testing.thelook_ecommerce.users to get a
                        breakdown of order count by age group.
                    - step: >-
                        Create a vertical bar plot using the retrieved data,
                        with one bar per age group.
    - table:
        - name: bigquery-public-data.thelook_ecommerce.users
        - description: Data for users in The Look, a fictitious ecommerce store.
        - synonyms: customers
        - tags: 'user, customer, buyer'
        - fields:
            - field:
                - name: id
                - description: The unique identifier for each user.
            - field:
                - name: first_name
                - description: The first name of the user.
                - tag: person
                - sample_values: 'alex, izumi, nur'
            - field:
                - name: last_name
                - description: The first name of the user.
                - tag: person
                - sample_values: 'warmer, stilles, smith'
            - field:
                - name: age_group
                - description: The age demographic group of the user.
                - sample_values:
                    - 18-24
                    - 25-34
                    - 35-49
                    - 50+
            - field:
                - name: email
                - description: The email address of the user.
                - tag: contact
                - sample_values: '222larabrown@gmail.com, cloudysanfrancisco@gmail.com'
        - golden_queries:
            - golden_query:
                - natural_language_query: How many unique customers are there?
                - sql_query: >-
                    SELECT COUNT(DISTINCT id) FROM
                    bigquery-public-data.thelook_ecommerce.users
            - golden_query:
                - natural_language_query: How many users in the 25-34 age group have a cymbalgroup email address?
                - sql_query: >-
                    SELECT COUNT(DISTINCT id) FROM
                    bigquery-public-data.thelook_ecommerce.users WHERE users.age_group =
                    '25-34' AND users.email LIKE '%@cymbalgroup.com';
    - relationships:
        - relationship:
            - name: orders_to_user
            - description: >-
                Connects customer order data to user information with the user_id and id fields to allow an aggregated view of sales by customer demographics.
            - relationship_type: many-to-one
            - join_type: left
            - left_table: bigquery-public-data.thelook_ecommerce.orders
            - right_table: bigquery-public-data.thelook_ecommerce.users
            - relationship_columns:
                - left_column: user_id
                - right_column: id
- glossaries:
    - glossary:
        - term: complete
        - description: Represents an order status where the order has been completed.
        - synonyms: 'finish, done, fulfilled'
    - glossary:
        - term: shipped
        - description: Represents an order status where the order has been shipped to the customer.
    - glossary:
        - term: returned
        - description: Represents an order status where the customer has returned the order.
    - glossary:
        - term: OMPF
        - description: Order Management and Product Fulfillment
- additional_descriptions:
    - text: All the sales data pertains to The Look, a fictitious ecommerce store.
    - text: 'Orders can be of three categories: food, clothes, and electronics.'