Esta página descreve a estrutura recomendada para escrever comandos eficazes para os agentes de dados da API Conversational Analytics. Estes comandos são contexto criado que define como strings através do parâmetro system_instruction
. As instruções do sistema bem estruturadas podem melhorar a precisão e a relevância das respostas fornecidas pela API.
Para ver exemplos de contexto criado em diferentes ambientes, consulte as seguintes páginas de documentação:
- Oriente o comportamento do agente com contexto criado para origens de dados do BigQuery
- Oriente o comportamento do agente com contexto criado para origens de dados do Looker
O que são instruções do sistema?
As instruções do sistema são orientações definidas pelo utilizador que os programadores 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. Este contexto também inclui origens de dados associadas (tabelas do BigQuery, explorações do Looker, origens de dados do Looker Studio) e o histórico de conversas (para conversas com várias interações).
Ao fornecer orientações claras e estruturadas através de instruções do sistema, pode melhorar a capacidade do agente de interpretar as perguntas dos utilizadores e gerar respostas úteis e precisas. As instruções do sistema bem definidas são especialmente úteis se estiver a estabelecer ligação a dados, como tabelas do BigQuery, onde pode não existir uma camada semântica predefinida, como acontece com uma análise detalhada do Looker.
Por exemplo, pode usar instruções do sistema para fornecer os seguintes tipos de orientações a um agente:
- Lógica específica da empresa: defina um cliente "fiel" como um cliente que fez mais de cinco compras num determinado período.
- Formatação de respostas: resuma todas as respostas do seu agente de dados em 20 palavras ou menos para poupar tempo aos utilizadores.
- Apresentação de dados: formate todos os números de acordo com o guia de estilo da empresa.
Forneça instruções do sistema
Pode fornecer instruções do sistema à API Conversational Analytics como uma string formatada em YAML através do parâmetro system_instruction
. Embora o parâmetro system_instruction
seja opcional, é recomendável fornecer instruções do sistema bem estruturadas para receber respostas precisas e relevantes.
Pode definir a string formatada em YAML no seu código durante a configuração inicial, conforme mostrado em Configure as definições iniciais e a autenticação (HTTP) ou Especifique o projeto de faturação e as instruções do sistema (SDK Python). Em seguida, pode incluir o parâmetro system_instruction
nas seguintes chamadas da API:
- Criar um agente de dados persistente: inclua a string
system_instruction
no objetopublished_context
no corpo do pedido para configurar o comportamento do agente que persiste em várias conversas. Para mais informações, consulte os artigos Crie um agente de dados (HTTP) ou Configure o contexto para um chat com ou sem estado (SDK Python). - Enviar um pedido sem estado: forneça a string
system_instruction
no objetoinline_context
no pedido de chat para definir o comportamento e o contexto do agente durante essa chamada API específica. Para mais informações, consulte os artigos Crie uma conversa sem estado com várias interações (HTTP) ou Envie um pedido de chat sem estado com contexto inline (SDK Python).
Modelo YAML para instruções do sistema
O modelo seguinte mostra a estrutura YAML recomendada para a string que fornece ao parâmetro system_instruction
, incluindo as chaves disponíveis e os tipos de dados esperados.
Pode usar o seguinte modelo YAML para fornecer as 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.
Componentes principais das instruções do sistema
As secções seguintes descrevem os principais componentes das instruções do sistema e como usá-los para melhorar a qualidade das respostas do seu agente. Estas chaves incluem o seguinte:
system_instruction
tables
fields
measures
golden_queries
golden_action_plans
relationships
glossaries
additional_descriptions
Defina a função e o perfil do agente com system_instruction
Defina a função e a personalidade do agente através da tecla system_instruction
. Esta instrução inicial define o tom e o estilo das respostas da API e ajuda o agente a compreender o seu objetivo principal.
O seguinte bloco de código YAML mostra a estrutura básica da chave system_instruction
:
- system_instruction: str
Por exemplo, pode definir um agente como analista de vendas de uma loja de comércio eletrónico fictícia da seguinte forma:
- 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.
Descreva os seus dados com o tables
A chave tables
contém uma lista de descrições de tabelas para o agente e fornece detalhes sobre os dados específicos que estão disponíveis para o agente responder a perguntas. Cada objeto table
nesta lista contém os metadados de uma tabela específica, incluindo o nome, a descrição, os sinónimos, as etiquetas, os campos, as medidas, as consultas de referência e os planos de ação de referência dessa tabela.
O seguinte bloco de código YAML 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.
Descreva os campos usados frequentemente com fields
A chave fields
, que está aninhada num objeto table
, recebe uma lista de objetos de campo para descrever colunas individuais. Nem todos os campos precisam de contexto adicional. No entanto, incluir detalhes adicionais nos campos usados com frequência pode ajudar a melhorar o desempenho do agente.
O seguinte bloco de código YAML 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.
Defina métricas empresariais com o measures
A chave measures
, que está aninhada num objeto table
, define métricas ou cálculos empresariais personalizados que não estão diretamente presentes como colunas nas suas tabelas. Fornecer contexto para as medidas ajuda o agente a responder a perguntas sobre indicadores essenciais de desempenho (IEDs) ou outros valores calculados.
O seguinte bloco de código YAML 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.
Melhore a precisão com o golden_queries
A chave golden_queries
, que está aninhada num objeto table
, recebe uma lista de objetos golden_query
. As consultas de ouro ajudam o agente a fornecer 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, pode orientar o agente para fornecer resultados de maior qualidade e mais consistentes.
O seguinte bloco de código YAML 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.
Descreva tarefas com vários passos com golden_action_plans
A chave golden_action_plans
, que está aninhada num objeto table
, recebe uma lista de objetos golden_action_plan
. Pode usar planos de ação ideais para fornecer ao agente exemplos de como processar pedidos com vários passos, como obter dados e, em seguida, criar uma visualização.
O seguinte bloco de código YAML 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.
Defina 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, pode ajudar o agente a compreender como juntar dados de várias tabelas quando responde a perguntas.
O seguinte bloco de código YAML 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.
Explicar termos empresariais com o glossaries
A glossaries
lista as definições de termos empresariais, jargão e abreviaturas relevantes para os seus dados e exemplo de utilização. Ao fornecer definições de glossário, pode ajudar o agente a interpretar e responder com precisão a perguntas que usam linguagem empresarial específica.
O seguinte bloco de código YAML 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.
Inclua mais instruções com additional_descriptions
A chave additional_descriptions
lista quaisquer instruções gerais ou contexto adicionais que não sejam abordados noutras partes das instruções do sistema. Ao fornecer descrições adicionais, pode ajudar o agente a compreender melhor o contexto dos seus dados e exemplo de utilização.
O seguinte bloco de código YAML 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.