Overview

genai_get_content_by_role

You can use this function to extract messages by role, filter conversations by participant type, analyze specific role patterns, or process messages from particular conversation participants.

Usage#

Syntax#

genai_get_content_by_role(messages, role)

Parameters#

Name Type Required Description
messages dynamic Yes An array of message objects from a GenAI conversation. Each message typically contains role and content fields.
role string Yes The role to filter by. Common values include 'user', 'assistant', 'system', 'tool', or 'function'.

Returns#

Returns a string containing the content of the first message with the specified role, or an empty string if no matching message is found.

Example#

Extract the content of the system message from a GenAI conversation.

Query

['otel-demo-genai']
| extend system_content = genai_get_content_by_role(['attributes.gen_ai.input.messages'], 'system')
| where isnotempty(system_content)
| summarize conversation_count = count() by system_content
| top 3 by conversation_count

Run in Playground

Output

system_content conversation_count
You are a helpful shopping assistant. 1250
You are a technical support expert. 845

This query shows the distribution of system prompts being used, helping ensure configuration consistency.

  • genai_get_content_by_index: Gets content by position. Use this when you need a message at a specific index rather than by role.
  • genai_extract_user_prompt: Extracts the last user prompt. Use this shorthand when you specifically need the most recent user message.
  • genai_extract_assistant_response: Extracts the last assistant response. Use this shorthand when you specifically need the most recent AI response.
  • genai_extract_system_prompt: Extracts the system prompt. Use this shorthand when you specifically need the system message.
  • genai_message_roles: Lists all roles in the conversation. Use this to understand what roles are present before extracting by role.

Other query languages#

Splunk SPL users

In Splunk SPL, you would use mvfilter to filter by role and then extract the content.

Splunk example

| eval filtered_msgs=mvfilter(match(role, "system"))
| eval content=mvindex(filtered_msgs, 0)

APL equivalent

['ai-logs']
| extend content = genai_get_content_by_role(messages, 'system')
ANSI SQL users

In ANSI SQL, you would unnest the array, filter by role, and limit to the first result.

SQL example

SELECT
  conversation_id,
  content
FROM conversations
CROSS JOIN UNNEST(messages)
WHERE role = 'system'
LIMIT 1

APL equivalent

['ai-logs']
| extend content = genai_get_content_by_role(messages, 'system')

Updated

Was this page helpful?