> ## Documentation Index
> Fetch the complete documentation index at: https://docs.genesiscomputing.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cortex Agents Tools

> Build AI-powered agents that query and analyze data using natural language through semantic models and Cortex Analyst integration.

## **Overview**

### **Tool Name**

```json theme={null}
_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

<Steps>
  <Step title="Natural Language Queries" icon="comment">
    Ask questions in plain English and get data-driven answers without writing SQL.
  </Step>

  <Step title="Auto-Generate Semantic Models" icon="wand-magic-sparkles">
    Automatically create semantic models from existing tables with relationships and metrics.
  </Step>

  <Step title="Ad-Hoc Analysis" icon="bolt">
    Run quick queries without creating persistent agents using run\_adhoc mode.
  </Step>

  <Step title="Reusable Agents" icon="robot">
    Create stored agents with specific capabilities for repeated use across teams.
  </Step>

  <Step title="Cortex Analyst Integration" icon="brain">
    Leverage Snowflake's AI-powered Cortex Analyst for intelligent query understanding.
  </Step>
</Steps>

## **Input Parameters for Each Function**

### **`_cortex_agent`**

**Parameters**

| **Name** | **Definition** | **Format** |
| - | - | :-: |
| **action** | Operation 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) |
| **name** | Name of semantic model or agent (for create/get/delete actions). | String |
| **tables** | List of table names to include in semantic model (for `generate_template`). | List of Strings |
| **query** | Natural language query to execute (for `run` and `run_adhoc` actions). | String |
| **agent\_config** | Configuration object defining agent tools and capabilities (for `create_agent` and `run_adhoc`). | Object |

<Tip>
  Use **run\_adhoc** for quick analysis without creating persistent agents. Only create stored agents when you need reusable, team-shared capabilities.
</Tip>

## **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.
   ```python theme={null}
   _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:
   ```python theme={null}
   _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:
   ```python theme={null}
   _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:
   ```python theme={null}
   _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.

<Warning>
  Cortex Agents execute queries on your Snowflake warehouse. Ensure semantic models have appropriate access controls and cost monitoring in place.
</Warning>

Successful Cortex Agent runs are recorded automatically as metered-service cost
facts and appear in Pulse Costs. See [Cost accounting](/docs/Setup/Advanced-Settings#cost-accounting).

Cortex Agent SQL API attribution: [Snowflake query tags](/docs/Integrations/Data%20Sources/Snowflake/Snowflake#identify-twin-scanner-queries).

## **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**

<CardGroup cols={2}>
  <Card title="Start with generate_template" icon="wand-magic-sparkles">
    Auto-generate semantic models first, then refine manually for better accuracy and business context.
  </Card>

  <Card title="Use run_adhoc for Exploration" icon="compass">
    Test queries with run\_adhoc before committing to stored agents for faster iteration.
  </Card>

  <Card title="Define Clear Relationships" icon="diagram-project">
    Ensure foreign keys and table relationships are well-defined in semantic models for accurate joins.
  </Card>

  <Card title="Validate Before Deploy" icon="check-circle">
    Always validate semantic models before using in production agents to catch errors early.
  </Card>
</CardGroup>

## **Example: Complete Sales Analysis Agent**

```python theme={null}
# 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"
)
```

## **Comparison: Cortex Agents vs. Cortex Search**

| **Feature** | **Cortex Agents** | **Cortex Search** |
| - | - | - |
| **Primary Use** | Analytical queries over structured data | Semantic search over text content |
| **Input Format** | Natural language questions | Search keywords/phrases |
| **Output Type** | Aggregated insights, metrics, tables | Ranked list of matching documents |
| **Data Type** | Structured tables (SQL databases) | Unstructured text (descriptions, docs) |
| **Query Complexity** | Complex analytics with joins, aggregations | Similarity matching with filters |
| **Best For** | "What/How/Why" business questions | "Find documents about X" searches |
| **Setup Requirement** | Semantic model definition | Index 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:

```yaml theme={null}
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
```
