Escrever instruções do sistema eficazes pode fornecer aos agentes de dados da API Conversational Analytics contexto útil para responder a perguntas sobre as suas origens de dados. As instruções do sistema são um tipo de contexto criado que os proprietários de agentes de dados podem fornecer para moldar o comportamento de um agente de dados e refinar as respostas da API.
Esta página descreve a estrutura recomendada para escrever comandos eficazes para os agentes de dados da API Conversational Analytics que se ligam aos dados do BigQuery. Estes comandos são contexto criado que define como strings através do parâmetro system_instruction.
Esta página descreve como escrever instruções do sistema para origens de dados do BigQuery, que se baseiam em bases de dados do BigQuery.
Definir contexto nas instruções do sistema
As instruções do sistema consistem numa série de componentes e objetos essenciais que fornecem ao agente de dados detalhes sobre a origem de dados e orientações sobre a função do agente ao responder a perguntas. Pode fornecer instruções do sistema ao agente de dados no parâmetro system_instruction como uma string formatada em YAML.
O modelo seguinte mostra uma estrutura YAML sugerida para a string que fornece ao parâmetro system_instruction, incluindo as chaves disponíveis e os tipos de dados esperados.
O seguinte modelo YAML mostra um exemplo de como pode estruturar as instruções do sistema para uma origem de dados do BigQuery.
- 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.
Exemplos de componentes principais de instruções do sistema que usam origens de dados do BigQuery
As secções seguintes contêm exemplos de componentes essenciais das instruções do sistema no BigQuery. Estas chaves incluem o seguinte:
system_instructiontablesfieldsmeasuresgolden_queriesgolden_action_plansrelationshipsglossariesadditional_descriptions
system_instruction
Use a chave system_instruction para definir a função e a personalidade do agente. Esta instrução inicial define o tom e o estilo das respostas da API e ajuda o agente a compreender o seu objetivo principal.
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.
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 ouro e os planos de ação de ouro dessa tabela. O seguinte bloco de código YAML 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
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 código YAML de exemplo descreve os 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
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.
Por exemplo, pode definir uma medida profit como um cálculo dos ganhos menos o custo da seguinte forma:
- tables:
- table:
- name: bigquery-public-data.thelook_ecommerce.orders
- measures:
- measure:
- name: profit
- description: Raw profit (earnings minus cost).
- exp: earnings - cost
- synonyms: gains
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 que pode definir.
Por exemplo, pode definir consultas de ouro para análises comuns dos dados na tabela orders da seguinte forma:
- 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'
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.
Por exemplo, pode definir um plano de ação para mostrar discriminações de encomendas por grupo etário e incluir detalhes sobre a consulta SQL e os passos relacionados com a 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.
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.
Por exemplo, pode definir uma relação orders_to_user entre a tabela bigquery-public-data.thelook_ecommerce.orders e a tabela bigquery-public-data.thelook_ecommerce.users da seguinte forma:
- 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
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.
Por exemplo, pode definir termos como estados comuns da empresa e "OMPF" de acordo com o contexto específico da sua empresa 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
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.
Por exemplo, pode usar a tecla additional_descriptions para fornecer informações sobre a 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 no BigQuery
O exemplo seguinte mostra instruções do sistema de exemplo 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.'