Skip to main content

Overview

Tool Name

_cortex_agent

Purpose

The _cortex_agent tool enables you to create intelligent AI agents that understand and query your data using natural language. By building semantic models from your tables, these agents can answer business questions without requiring SQL expertise. Perfect for self-service analytics, automated reporting, and conversational data exploration.

Functions Available

  1. _cortex_agent: Manages semantic models and Cortex Agents for AI-powered data analysis, natural language querying, and automated insights generation. Controlled by the action parameter.

Key Features

Natural Language Queries

Ask questions in plain English and get data-driven answers without writing SQL.

Auto-Generate Semantic Models

Automatically create semantic models from existing tables with relationships and metrics.

Ad-Hoc Analysis

Run quick queries without creating persistent agents using run_adhoc mode.

Reusable Agents

Create stored agents with specific capabilities for repeated use across teams.

Cortex Analyst Integration

Leverage Snowflake’s AI-powered Cortex Analyst for intelligent query understanding.

Input Parameters for Each Function

_cortex_agent

Parameters
NameDefinitionFormat
actionOperation to perform. Values: generate_template, create_agent, run, run_adhoc, list_agents, describe_agent, delete_agent, create_semantic_model, list_semantic_models, get_semantic_model, validate_semantic_model, delete_semantic_model, feedback, create_thread, list_threads.String (required)
nameName of semantic model or agent (for create/get/delete actions).String
tablesList of table names to include in semantic model (for generate_template).List of Strings
queryNatural language query to execute (for run and run_adhoc actions).String
agent_configConfiguration object defining agent tools and capabilities (for create_agent and run_adhoc).Object
Use run_adhoc for quick analysis without creating persistent agents. Only create stored agents when you need reusable, team-shared capabilities.

Use Cases

  1. Self-Service Analytics Enable business users to query data without SQL: “What were our top 5 products by revenue last quarter?”
  2. Executive Dashboards Create agents that answer executive questions: “How does Q4 performance compare to last year?”
  3. Automated Reporting Build agents that generate regular reports: “Summarize weekly sales trends by region.”
  4. Data Exploration Help analysts discover insights: “Show me customer segments with declining engagement.”
  5. Conversational BI Enable Slack/Teams bots to answer data questions: “What’s our current inventory level for product X?”

Workflow/How It Works

  1. Step 1: Generate Semantic Model from Tables Start by creating a semantic model that defines your data structure, relationships, and business metrics.
    _cortex_agent(
        action="generate_template",
        tables=["sales", "customers", "products"],
        name="sales_model"
    )
    
  2. Step 2: Query with Ad-Hoc Agent (Recommended) For quick analysis, use run_adhoc without creating a persistent agent:
    _cortex_agent(
        action="run_adhoc",
        query="What were total sales last quarter?",
        agent_config={
            "tools": [{
                "type": "cortex_analyst",
                "semantic_model": "@my_stage/semantic_models/sales_model.yaml"
            }]
        }
    )
    
  3. Step 3: Create Stored Agent (Optional) For reusable agents shared across teams:
    _cortex_agent(
        action="create_agent",
        name="sales_analyst",
        agent_config={
            "tools": [{
                "type": "cortex_analyst",
                "semantic_model": "@my_stage/semantic_models/sales_model.yaml"
            }]
        }
    )
    
  4. Step 4: Query Using Stored Agent Execute queries against the created agent:
    _cortex_agent(
        action="run",
        name="sales_analyst",
        query="Show me top customers by revenue this year"
    )
    
  5. Step 5: Validate and Maintain Use validate_semantic_model to check model correctness and list_agents to manage your agent inventory.

Integration Relevance

  • data_connector_tools for identifying tables and understanding schema before model generation.
  • _query_database to verify semantic model accuracy against actual data.
  • project_manager_tools to track agent creation and semantic model development tasks.
  • slack_tools to deploy agents as Slack bots for team-wide access.
  • scheduler_tools to automate regular queries and reports using stored agents.

Configuration Details

  • Semantic Model Location: Store models in Snowflake stages (e.g., @my_stage/semantic_models/).
  • Agent Config Structure: Define tools array with type: "cortex_analyst" and semantic model path.
  • Table Selection: Include related tables with foreign key relationships for best results.
  • Query Complexity: Supports aggregations, filters, time-based analysis, and multi-table joins.
  • Model Validation: Always validate semantic models before deploying to production agents.
Cortex Agents execute queries on your Snowflake warehouse. Ensure semantic models have appropriate access controls and cost monitoring in place.

Limitations or Notes

  1. Snowflake Cortex Required: Requires Snowflake account with Cortex features enabled and licensed.
  2. Semantic Model Quality: Agent accuracy depends on well-defined semantic models with clear relationships.
  3. Query Ambiguity: Complex or ambiguous questions may require refinement for accurate results.
  4. Table Access: Agent can only query tables included in its semantic model definition.
  5. No Real-Time Training: Semantic models must be updated manually when schema changes occur.
  6. Language Support: Optimized for English; other languages may have reduced accuracy.
  7. Compute Costs: Each query executes SQL on your warehouse; monitor usage for cost control.

Supported Actions

generate_template - Auto-create semantic model from tables
create_agent - Define new AI agent with capabilities
run_adhoc - Query without creating stored agent (recommended for quick analysis)
run - Execute query using stored agent
list_agents - Show all created agents
describe_agent - Get agent configuration details
delete_agent - Remove an agent
create_semantic_model - Manually create semantic model
list_semantic_models - View available models
get_semantic_model - Retrieve model definition
validate_semantic_model - Check model correctness
delete_semantic_model - Remove a semantic model
create_thread - Start conversation context
list_threads - View conversation threads
feedback - Provide feedback on query results

Not Supported

❌ Real-time semantic model updates (requires manual refresh)
❌ Cross-database queries (semantic model scoped to single database)
❌ Custom SQL injection or direct query modification
❌ Unstructured data queries (designed for structured tables)
❌ Multi-tenant data isolation within single agent
❌ Agent-to-agent communication or chaining
❌ Visual chart generation (returns data only)

Output

  • generate_template: Confirmation with semantic model name, included tables, and file location.
  • create_agent: Agent creation status with name, configuration summary, and unique ID.
  • run_adhoc: Query results as structured data (JSON/table format) with SQL execution details.
  • run: Query results from stored agent with response time and confidence score.
  • list_agents: Table of all agents with names, creation dates, and associated semantic models.
  • describe_agent: Detailed agent configuration including tools, semantic models, and permissions.
  • list_semantic_models: List of available models with table counts and validation status.
  • validate_semantic_model: Validation report with errors, warnings, and recommendations.
  • Errors: Structured error messages with hints for query refinement or model corrections.

Best Practices

Start with generate_template

Auto-generate semantic models first, then refine manually for better accuracy and business context.

Use run_adhoc for Exploration

Test queries with run_adhoc before committing to stored agents for faster iteration.

Define Clear Relationships

Ensure foreign keys and table relationships are well-defined in semantic models for accurate joins.

Validate Before Deploy

Always validate semantic models before using in production agents to catch errors early.

Example: Complete Sales Analysis Agent

# 1. Generate semantic model from sales tables
_cortex_agent(
    action="generate_template",
    tables=["SALES.ORDERS", "SALES.CUSTOMERS", "SALES.PRODUCTS"],
    name="sales_analytics_model"
)

# 2. Validate the generated model
_cortex_agent(
    action="validate_semantic_model",
    name="sales_analytics_model"
)

# 3. Quick ad-hoc query (no agent creation needed)
results = _cortex_agent(
    action="run_adhoc",
    query="What were our top 10 products by revenue in Q4 2024?",
    agent_config={
        "tools": [{
            "type": "cortex_analyst",
            "semantic_model": "@my_stage/semantic_models/sales_analytics_model.yaml"
        }]
    }
)

# 4. Create stored agent for team use (optional)
_cortex_agent(
    action="create_agent",
    name="sales_analyst_bot",
    agent_config={
        "tools": [{
            "type": "cortex_analyst",
            "semantic_model": "@my_stage/semantic_models/sales_analytics_model.yaml"
        }]
    }
)

# 5. Query using stored agent
_cortex_agent(
    action="run",
    name="sales_analyst_bot",
    query="Show me customer retention rate by segment over the past 6 months"
)

# 6. List all available agents
_cortex_agent(
    action="list_agents"
)
FeatureCortex AgentsCortex Search
Primary UseAnalytical queries over structured dataSemantic search over text content
Input FormatNatural language questionsSearch keywords/phrases
Output TypeAggregated insights, metrics, tablesRanked list of matching documents
Data TypeStructured tables (SQL databases)Unstructured text (descriptions, docs)
Query ComplexityComplex analytics with joins, aggregationsSimilarity matching with filters
Best For”What/How/Why” business questions”Find documents about X” searches
Setup RequirementSemantic model definitionIndex creation on text columns

Advanced: Semantic Model Structure

A semantic model YAML defines:
  • Tables: Data sources with column definitions
  • Relationships: Foreign key connections between tables
  • Measures: Pre-defined calculations (SUM, AVG, COUNT)
  • Dimensions: Categorical fields for grouping
  • Time Intelligence: Date/time hierarchies for temporal analysis
Example semantic model excerpt:
tables:
  - name: sales
    columns:
      - name: order_id
        type: number
      - name: revenue
        type: number
      - name: order_date
        type: date
    measures:
      - name: total_revenue
        expr: SUM(revenue)
relationships:
  - from: sales.customer_id
    to: customers.id
    type: many_to_one

Ready to enable natural language analytics? Start by generating a semantic model from your key business tables and unlock conversational insights! 🚀
I