# Chapter 14: Building AI Agents ## The Problem You've been using Claude Code to build segments, journeys, and workflows. But what about your team members who aren't using Claude Code? What about the sales rep who needs quick answers about customer data? The support team that needs to look up product information? You need AI assistants tailored to specific roles—assistants that know your data, follow your guidelines, and can be used by anyone through a simple chat interface. ## The Key Idea Core concept Custom AI agents are chat assistants you design for specific purposes. They connect to your Treasure Data tables, follow your rules, and can be shared with your team through Slack, webhooks, or the TD Console. ## What is AI Agent Foundry? [AI Agent Foundry](https://docs.treasuredata.com/products/customer-data-platform/ai-agent-foundry) is Treasure Data's platform for building and deploying AI agents. Each project contains: - **Agents** — Chat assistants with specific tasks and instructions - **Knowledge Bases** — Connections to your TD tables via SQL queries - **Integrations** — How users access the agent (Slack, webhooks, TD Console) ```mermaid flowchart LR U[Users] --> I[Integration] I --> A[Agent] A --> K[Knowledge Base] K --> T[TD Tables] I --> |Slack, Webhook,
TD Console| A ``` ## What You Can Build | Agent Type | Purpose | Example Questions | | --- | --- | --- | | Customer Insights | Answer questions about customer behavior | "How many high-value customers do we have?" | | Campaign Helper | Suggest targeting rules | "Who should I target for a win-back campaign?" | | Product Expert | Answer product questions | "What's our best-selling product in Q4?" | | Report Generator | Create ad-hoc reports | "Show me revenue by region this month" | ## The Agent Workflow Building an agent with `tdx` follows the familiar pattern: ```mermaid flowchart LR A[Pull] --> B[Edit] B --> C[Push] C --> D[Share] ``` ```bash # 1. Pull project to local files tdx agent pull "Marketing Agents" # 2. Edit agent files locally (with AI help) # 3. Preview and push changes tdx agent push --dry-run tdx agent push # 4. Share the chat URL with your team ``` ## Creating Your First Agent Tell AI what you need: ``` > "Create a customer insights agent that can answer questions about our customer data" ``` AI creates the folder structure: ``` agents/marketing-agents/ ├── tdx.json # Project config ├── customer-insights/ │ ├── agent.yml # Agent configuration │ └── prompt.md # System prompt └── knowledge_bases/ └── customer-data.yml # TD table connection ``` ### Project Config (tdx.json) ```json { "llm_project": "Marketing Agents" } ``` ### Agent Configuration (agent.yml) Before we look at the configuration, let's understand the three settings that shape your agent's personality: #### Mental Model: Hiring an Employee Think of creating an agent like hiring a new team member: | Setting | Hiring Analogy | What It Controls | | --- | --- | --- | | **Model** | Experience level | Capability and cost. `claude-4.5-sonnet` is your senior analyst; `claude-4.5-haiku` is a quick assistant for simple tasks | | **Temperature** | Work style | How creative vs. by-the-book. Low (0.3) = consistent, factual answers. High (0.9) = creative, varied responses | | **Prompt** | Job description | What the agent knows, how it should behave, what it should never do | **Temperature in practice:** - `0.0-0.3` — "Give me the same answer every time" (data lookups, customer counts) - `0.7` — "Be helpful but consistent" (general questions, default) - `0.9-1.0` — "Surprise me with ideas" (brainstorming, creative copy) The default temperature is `0.7`—a balanced middle ground. For a data-focused agent, we'll use `0.3` to get consistent, factual answers: Reasoning Mode If you enable reasoning mode (`reasoning_effort`), temperature must be set to `1` or omitted entirely. ```yaml name: Customer Insights description: Answers questions about customer behavior and segments model: claude-4.5-sonnet temperature: 0.3 # Low for consistent, factual answers max_tool_iterations: 5 starter_message: | Hi! I can help you understand our customer data. Try asking: - "How many high-value customers do we have?" - "What's the average order value this month?" - "Which segment grew the most last quarter?" tools: - type: knowledge_base target: '@ref(type: "knowledge_base", name: "customer-data")' target_function: SEARCH function_name: search_customers function_description: Search customer data and metrics ``` ### System Prompt (prompt.md) ```markdown You are a Customer Insights assistant for our marketing team. ## Your Role Help team members understand customer data without writing SQL. Answer questions about: - Customer counts and segments - Purchase behavior and trends - Campaign performance ## Guidelines - Always cite the data source when providing numbers - If you're unsure, say so rather than guessing - Keep responses concise and actionable ## Data Access You have access to customer-data which includes: - Customer profiles and attributes - Purchase history - Segment membership ``` ### Knowledge Base (knowledge_bases/customer-data.yml) A knowledge base gives your agent access to information. There are two types: - **TD tables** (`.yml` files) — Query your customer data - **Text content** (`.md` files) — Static information like FAQs, policies, product details Here's a table-based knowledge base that connects to your TD data: ```yaml name: customer-data database: marketing_db tables: - name: customer_metrics td_query: | SELECT customer_id, lifetime_value, total_orders, last_purchase_date, segment_name FROM customer_360 enable_data: true enable_data_index: true ``` The agent can now search this data when users ask questions. ## Pushing and Testing Preview your changes: ```bash tdx agent push --dry-run ``` ``` Push summary for 'Marketing Agents': + 1 new agent + 1 new knowledge base Changes: + customer-insights/agent.yml + customer-insights/prompt.md + knowledge_bases/customer-data.yml ``` Push to make it live: ```bash tdx agent push ``` ``` ✔ Pushed 2 resources to 'Marketing Agents' Agent: Customer Insights Chat: https://console.treasuredata.com/app/af/.../ag/.../tc ``` Test in the TD Console, then share the URL or set up integrations. ## Adding More Capabilities ### Multiple Knowledge Bases Connect different data sources: ```yaml tools: - type: knowledge_base target: '@ref(type: "knowledge_base", name: "customer-data")' target_function: SEARCH function_name: search_customers function_description: Search customer profiles and metrics - type: knowledge_base target: '@ref(type: "knowledge_base", name: "product-catalog")' target_function: SEARCH function_name: search_products function_description: Search product information ``` ### Web Search Add real-time information: ```yaml tools: - type: web_search target: '@ref(type: "web_search_tool", name: "web-search")' target_function: SEARCH function_name: search_web function_description: Search the web for current trends ``` ### Agent-to-Agent Create specialized agents that work together: ```yaml # In campaign-helper/agent.yml tools: - type: agent target: '@ref(type: "agent", name: "Customer Insights")' target_function: CHAT function_name: ask_customer_insights function_description: Get customer data insights ``` Now Campaign Helper can ask Customer Insights for data. ### Parent Segment Data Give your agent direct access to CDP segment and audience data: ```yaml tools: - type: parent_segment_kb target_function: LIST_SEGMENT_FOLDERS function_name: list_segment_folders function_description: List all segment folders in the project - type: parent_segment_kb target_function: GET_SEGMENT function_name: get_segment_details function_description: Get details about a specific segment ``` Unlike other tools, `parent_segment_kb` is a singleton — your project has one parent segment knowledge base, so no `target` reference is needed. Available functions: `LIST_SEGMENT_FOLDERS`, `LIST_BY_FOLDER`, `LIST_ATTRIBUTES`, `LIST_BEHAVIORS`, `GET_SEGMENT`, `GET_JOURNEY`, `GET_AUDIENCE`, `GET_QUERY`, `QUERY_DATA_DIRECT`, `QUERY_SEGMENT_ANALYTICS`. ## Text-Based Knowledge Bases For static content like FAQs or guidelines, use markdown files: **knowledge_bases/targeting-guidelines.md:** ```markdown --- name: Targeting Guidelines --- # Segment Targeting Guidelines ## High-Value Customers - Definition: LTV > $1000 - Typical size: 5-10% of customer base - Best for: Premium offers, early access ## At-Risk Customers - Definition: No purchase in 90+ days - Typical size: 15-20% of customer base - Best for: Win-back campaigns ``` Reference it like any knowledge base: ```yaml tools: - type: knowledge_base target: '@ref(type: "knowledge_base", name: "Targeting Guidelines")' target_function: READ_TEXT function_name: read_guidelines function_description: Read targeting best practices ``` ## Sharing with Your Team AI Agent Foundry supports multiple integration types: | Integration | Access | Use Case | | --- | --- | --- | | TD Console | Browser chat | Internal testing, power users | | Slack | Slack workspace | Team-wide access | | Webhook | API calls | Custom apps, Google Sheets | Set up integrations in the TD Console after pushing your agent. ## Managing Agents ```bash # List agents in current project tdx agents # Pull latest from server tdx agent pull "Marketing Agents" # Clone to staging/production tdx agent clone "Marketing Agents" \ --name "Marketing Agents (Prod)" \ --profile production ``` ## Mental Model: Specialized Team Members Think of each agent as a team member with a specific job: | Role | Agent | | --- | --- | | Data analyst answering questions | Customer Insights | | Campaign strategist suggesting targets | Campaign Helper | | Product specialist | Product Expert | They're available 24/7, know your data, and serve your entire team. ## Pitfalls **"The agent doesn't know about recent data."** Knowledge bases query your TD tables via SQL. Ensure the underlying tables are fresh. **"The agent gives inconsistent answers."** Lower the temperature for more deterministic responses: ```yaml temperature: 0.2 ``` **"The agent makes up numbers."** Strengthen your system prompt: ```markdown ## Important Rules - Only cite data from the knowledge base - If you can't find data, say "I don't have that information" - Never make up numbers ``` ## What You've Learned - AI agents are chat assistants tailored to specific roles - Knowledge bases can be TD tables (queryable data) or markdown files (text content) - Agents connect to TD tables through knowledge bases - The workflow is pull → edit → push - Agents can chain together for complex tasks - Share agents via Slack, webhooks, or TD Console ## Next Step You've built AI agents for your team. [Chapter 15](/treasure-code/book/15-review-deploy) covers the final piece—how to validate, test, and safely deploy all your marketing configurations. ## Resources - [AI Agent Foundry Documentation](https://docs.treasuredata.com/products/customer-data-platform/ai-agent-foundry) — Official TD documentation - [Agent Commands Reference](/treasure-code/commands/agent) — Full tdx command documentation - [tdx-skills/agent](https://github.com/treasure-data/td-skills/tree/main/tdx-skills/agent) — AI assistance for building agents *You can build AI assistants for your team. Next, you'll learn to ship with confidence.*