ktx-ai-data-agents-context

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ktx AI Data Agents Context

ktx AI数据Agent上下文

Skill by ara.so — AI Agent Skills collection.
ktx is an executable context layer that teaches AI agents (Claude Code, Codex, Cursor, OpenCode) how to query your data warehouse accurately. It automatically builds and maintains a semantic layer from your warehouse metadata, dbt projects, LookML, Looker, Metabase, and wiki content - then serves it to agents through CLI and MCP tools with full-text and semantic search.
ara.so开发的Skill——AI Agent技能集合。
ktx是一个可执行的上下文层,用于指导AI Agent(Claude Code、Codex、Cursor、OpenCode)精准查询数据仓库。它会从仓库元数据、dbt项目、LookML、Looker、Metabase及知识库内容中自动构建并维护语义层,随后通过CLI和MCP工具为Agent提供支持,具备全文检索和语义搜索功能。

What ktx Does

ktx的功能

  • Learns from company knowledge: Ingests wiki content, dbt docs, Looker, Metabase - organizes it, removes duplicates, flags contradictions
  • Maps the data stack: Samples tables, detects joinable columns, annotates sources so agents write better queries
  • Builds a semantic layer: Combines raw tables and metrics through a join graph that resolves chasm and fan traps automatically
  • Serves agents at execution: Exposes CLI and MCP tools for Claude Code, Codex, Cursor, OpenCode to query context
  • 学习企业知识:导入知识库内容、dbt文档、Looker、Metabase数据,进行整理、去重并标记矛盾内容
  • 映射数据栈:采样数据表、检测可关联列、标注数据源,帮助Agent编写更优质的查询语句
  • 构建语义层:通过关联图整合原始表和指标,自动解决裂隙陷阱和扇形陷阱问题
  • 为Agent提供执行支持:通过CLI和MCP工具向Claude Code、Codex、Cursor、OpenCode暴露上下文查询能力

Installation

安装

Global Installation

全局安装

bash
npm install -g @kaelio/ktx
bash
npm install -g @kaelio/ktx

Project-Specific Installation

项目级安装

bash
npm install --save-dev @kaelio/ktx
Or with pnpm:
bash
pnpm add -D @kaelio/ktx
bash
npm install --save-dev @kaelio/ktx
或者使用pnpm:
bash
pnpm add -D @kaelio/ktx

Initial Setup

初始设置

Interactive Setup (Recommended)

交互式设置(推荐)

bash
ktx setup
This command:
  1. Creates or resumes a local ktx project
  2. Configures LLM and embedding providers
  3. Configures database connections
  4. Configures context sources (dbt, Looker, Metabase, Notion)
  5. Builds initial context
  6. Installs agent integration (MCP or Skills)
bash
ktx setup
该命令会:
  1. 创建或恢复本地ktx项目
  2. 配置LLM和嵌入模型提供商
  3. 配置数据库连接
  4. 配置上下文源(dbt、Looker、Metabase、Notion)
  5. 构建初始上下文
  6. 安装Agent集成(MCP或Skills)

Check Project Status

检查项目状态

bash
ktx status
Example output:
text
ktx project: /home/user/analytics
Project ready: yes
LLM ready: yes (claude-sonnet-4-6)
Embeddings ready: yes (text-embedding-3-small)
Databases configured: yes (warehouse)
Context sources configured: yes (dbt_main)
ktx context built: yes
Agent integration ready: yes (codex:project)
bash
ktx status
示例输出:
text
ktx project: /home/user/analytics
Project ready: yes
LLM ready: yes (claude-sonnet-4-6)
Embeddings ready: yes (text-embedding-3-small)
Databases configured: yes (warehouse)
Context sources configured: yes (dbt_main)
ktx context built: yes
Agent integration ready: yes (codex:project)

Configuration

配置

Project Structure

项目结构

text
my-project/
├── ktx.yaml                         # Project configuration
├── semantic-layer/<connection-id>/  # YAML semantic sources
├── wiki/global/                     # Shared business context
├── wiki/user/<user-id>/             # User-scoped notes
├── raw-sources/<connection-id>/     # Ingest artifacts and reports
└── .ktx/                            # Local state and secrets (git-ignored)
text
my-project/
├── ktx.yaml                         # 项目配置文件
├── semantic-layer/<connection-id>/  # YAML语义源
├── wiki/global/                     # 共享业务上下文
├── wiki/user/<user-id>/             # 用户专属笔记
├── raw-sources/<connection-id>/     # 导入的工件和报告
└── .ktx/                            # 本地状态和密钥(已加入git忽略)

ktx.yaml Example

ktx.yaml示例

yaml
version: 1
project_id: analytics-warehouse
llm:
  provider: anthropic
  model: claude-sonnet-4-6
embeddings:
  provider: openai
  model: text-embedding-3-small

databases:
  warehouse:
    type: postgres
    host: localhost
    port: 5432
    database: analytics
    user: readonly_user
    # Password stored in .ktx/secrets.yaml or env var

context_sources:
  dbt_main:
    type: dbt
    project_dir: ./dbt
    profiles_dir: ~/.dbt
  
  notion_docs:
    type: notion
    # Token stored in .ktx/secrets.yaml or env var NOTION_TOKEN
yaml
version: 1
project_id: analytics-warehouse
llm:
  provider: anthropic
  model: claude-sonnet-4-6
embeddings:
  provider: openai
  model: text-embedding-3-small

databases:
  warehouse:
    type: postgres
    host: localhost
    port: 5432
    database: analytics
    user: readonly_user
    # 密码存储在.ktx/secrets.yaml或环境变量中

context_sources:
  dbt_main:
    type: dbt
    project_dir: ./dbt
    profiles_dir: ~/.dbt
  
  notion_docs:
    type: notion
    # Token存储在.ktx/secrets.yaml或环境变量NOTION_TOKEN中

Environment Variables

环境变量

ktx respects these environment variables:
bash
undefined
ktx支持以下环境变量:
bash
undefined

LLM configuration

LLM配置

export ANTHROPIC_API_KEY=your_key_here export OPENAI_API_KEY=your_key_here
export ANTHROPIC_API_KEY=your_key_here export OPENAI_API_KEY=your_key_here

Database credentials

数据库凭证

export DB_PASSWORD=your_db_password
export DB_PASSWORD=your_db_password

Context sources

上下文源

export NOTION_TOKEN=your_notion_token export DBT_PROFILES_DIR=~/.dbt
export NOTION_TOKEN=your_notion_token export DBT_PROFILES_DIR=~/.dbt

Project resolution

项目路径

export KTX_PROJECT_DIR=/path/to/project
undefined
export KTX_PROJECT_DIR=/path/to/project
undefined

Key Commands

核心命令

Building Context

构建上下文

bash
undefined
bash
undefined

Build context from all configured sources

从所有已配置的源构建上下文

ktx ingest
ktx ingest

Build from specific connection

从指定连接构建上下文

ktx ingest --connection warehouse
ktx ingest --connection warehouse

Rebuild everything from scratch

从头重建所有内容

ktx ingest --rebuild
undefined
ktx ingest --rebuild
undefined

Searching Context

搜索上下文

bash
undefined
bash
undefined

Search semantic layer (metrics, dimensions, sources)

搜索语义层(指标、维度、数据源)

ktx sl "revenue" ktx sl "customer lifetime value"
ktx sl "revenue" ktx sl "customer lifetime value"

Search wiki content

搜索知识库内容

ktx wiki "refund policy" ktx wiki "revenue recognition rules"
ktx wiki "refund policy" ktx wiki "revenue recognition rules"

Combined search

组合搜索

ktx search "monthly recurring revenue"
undefined
ktx search "monthly recurring revenue"
undefined

MCP Server (for AI Agents)

MCP服务器(用于AI Agent)

bash
undefined
bash
undefined

Start MCP server for agent integration

启动MCP服务器以实现Agent集成

ktx mcp start
ktx mcp start

Start with custom project directory

使用自定义项目目录启动

ktx mcp start --project-dir /path/to/project
ktx mcp start --project-dir /path/to/project

List available MCP tools

列出可用的MCP工具

ktx mcp tools
undefined
ktx mcp tools
undefined

Managing Semantic Layer

管理语义层

bash
undefined
bash
undefined

Validate semantic layer YAML

验证语义层YAML文件

ktx sl validate
ktx sl validate

List all semantic sources

列出所有语义源

ktx sl list
ktx sl list

Show specific metric details

查看指定指标的详细信息

ktx sl show monthly_revenue
undefined
ktx sl show monthly_revenue
undefined

Database Connection Examples

数据库连接示例

PostgreSQL

PostgreSQL

yaml
databases:
  warehouse:
    type: postgres
    host: localhost
    port: 5432
    database: analytics
    user: readonly_user
    ssl: true
yaml
databases:
  warehouse:
    type: postgres
    host: localhost
    port: 5432
    database: analytics
    user: readonly_user
    ssl: true

Snowflake

Snowflake

yaml
databases:
  snowflake_prod:
    type: snowflake
    account: xy12345.us-east-1
    warehouse: COMPUTE_WH
    database: ANALYTICS
    schema: PUBLIC
    user: readonly_user
    role: ANALYST
yaml
databases:
  snowflake_prod:
    type: snowflake
    account: xy12345.us-east-1
    warehouse: COMPUTE_WH
    database: ANALYTICS
    schema: PUBLIC
    user: readonly_user
    role: ANALYST

BigQuery

BigQuery

yaml
databases:
  bigquery_prod:
    type: bigquery
    project_id: my-gcp-project
    dataset: analytics
    credentials_file: /path/to/service-account.json
yaml
databases:
  bigquery_prod:
    type: bigquery
    project_id: my-gcp-project
    dataset: analytics
    credentials_file: /path/to/service-account.json

ClickHouse

ClickHouse

yaml
databases:
  clickhouse:
    type: clickhouse
    host: localhost
    port: 9000
    database: analytics
    user: readonly
yaml
databases:
  clickhouse:
    type: clickhouse
    host: localhost
    port: 9000
    database: analytics
    user: readonly

Context Source Examples

上下文源示例

dbt

dbt

yaml
context_sources:
  dbt_main:
    type: dbt
    project_dir: ./dbt
    profiles_dir: ~/.dbt
    target: prod
yaml
context_sources:
  dbt_main:
    type: dbt
    project_dir: ./dbt
    profiles_dir: ~/.dbt
    target: prod

LookML

LookML

yaml
context_sources:
  looker:
    type: lookml
    project_dir: ./looker-project
    models:
      - sales
      - marketing
yaml
context_sources:
  looker:
    type: lookml
    project_dir: ./looker-project
    models:
      - sales
      - marketing

Metabase

Metabase

yaml
context_sources:
  metabase:
    type: metabase
    url: https://metabase.company.com
    # Token in .ktx/secrets.yaml or METABASE_TOKEN env var
    collections:
      - Sales Dashboards
      - Marketing Analytics
yaml
context_sources:
  metabase:
    type: metabase
    url: https://metabase.company.com
    # Token存储在.ktx/secrets.yaml或环境变量METABASE_TOKEN中
    collections:
      - Sales Dashboards
      - Marketing Analytics

Notion

Notion

yaml
context_sources:
  notion_wiki:
    type: notion
    # Token in .ktx/secrets.yaml or NOTION_TOKEN env var
    page_ids:
      - abc123def456
      - ghi789jkl012
yaml
context_sources:
  notion_wiki:
    type: notion
    # Token存储在.ktx/secrets.yaml或环境变量NOTION_TOKEN中
    page_ids:
      - abc123def456
      - ghi789jkl012

Semantic Layer YAML

语义层YAML

Defining a Metric

定义指标

yaml
undefined
yaml
undefined

semantic-layer/warehouse/metrics/revenue.yaml

semantic-layer/warehouse/metrics/revenue.yaml

type: metric name: monthly_revenue description: Total revenue aggregated by month sql: | SELECT DATE_TRUNC('month', order_date) as month, SUM(amount) as revenue FROM orders WHERE status = 'completed' GROUP BY 1 dimensions:
  • month measures:
  • revenue tags:
  • finance
  • reporting
undefined
type: metric name: monthly_revenue description: Total revenue aggregated by month sql: | SELECT DATE_TRUNC('month', order_date) as month, SUM(amount) as revenue FROM orders WHERE status = 'completed' GROUP BY 1 dimensions:
  • month measures:
  • revenue tags:
  • finance
  • reporting
undefined

Defining a Dimension

定义维度

yaml
undefined
yaml
undefined

semantic-layer/warehouse/dimensions/customer_segment.yaml

semantic-layer/warehouse/dimensions/customer_segment.yaml

type: dimension name: customer_segment description: Customer segmentation based on lifetime value sql: | CASE WHEN lifetime_value >= 10000 THEN 'Enterprise' WHEN lifetime_value >= 1000 THEN 'Mid-Market' ELSE 'SMB' END source_table: customers
undefined
type: dimension name: customer_segment description: Customer segmentation based on lifetime value sql: | CASE WHEN lifetime_value >= 10000 THEN 'Enterprise' WHEN lifetime_value >= 1000 THEN 'Mid-Market' ELSE 'SMB' END source_table: customers
undefined

Defining a Joinable Source

定义可关联数据源

yaml
undefined
yaml
undefined

semantic-layer/warehouse/sources/orders.yaml

semantic-layer/warehouse/sources/orders.yaml

type: source name: orders description: All customer orders table: public.orders primary_key: order_id joins:
  • to: customers type: many_to_one on: orders.customer_id = customers.customer_id columns:
  • name: order_id type: integer description: Unique order identifier
  • name: customer_id type: integer description: Foreign key to customers
  • name: amount type: decimal description: Order total in USD
  • name: order_date type: timestamp description: When order was placed
undefined
type: source name: orders description: All customer orders table: public.orders primary_key: order_id joins:
  • to: customers type: many_to_one on: orders.customer_id = customers.customer_id columns:
  • name: order_id type: integer description: Unique order identifier
  • name: customer_id type: integer description: Foreign key to customers
  • name: amount type: decimal description: Order total in USD
  • name: order_date type: timestamp description: When order was placed
undefined

Agent Integration

Agent集成

Using with Claude Code

与Claude Code配合使用

After running
ktx setup
, ktx installs MCP integration automatically. The MCP server provides these tools:
  • ktx_search_semantic_layer
    : Search metrics, dimensions, sources
  • ktx_search_wiki
    : Search wiki content
  • ktx_get_metric
    : Get full metric definition
  • ktx_query_preview
    : Preview SQL for a semantic query
In Claude Code:
text
Use ktx to find our revenue metrics
What wiki pages discuss refund policies?
Show me the SQL for monthly_recurring_revenue metric
运行
ktx setup
后,ktx会自动安装MCP集成。MCP服务器提供以下工具:
  • ktx_search_semantic_layer
    : 搜索指标、维度、数据源
  • ktx_search_wiki
    : 搜索知识库内容
  • ktx_get_metric
    : 获取完整指标定义
  • ktx_query_preview
    : 预览语义查询的SQL语句
在Claude Code中使用:
text
Use ktx to find our revenue metrics
What wiki pages discuss refund policies?
Show me the SQL for monthly_recurring_revenue metric

Using with Codex

与Codex配合使用

bash
undefined
bash
undefined

Install ktx skill

安装ktx skill

npx skills add Kaelio/ktx --skill ktx
npx skills add Kaelio/ktx --skill ktx

Then in your project

然后在你的项目中运行

ktx setup

Codex can now use ktx tools:
```text
Query our warehouse for Q1 2024 revenue by customer segment
Find documentation about our churn calculation
ktx setup

Codex现在可以使用ktx工具:
```text
Query our warehouse for Q1 2024 revenue by customer segment
Find documentation about our churn calculation

Using with Cursor or OpenCode

与Cursor或OpenCode配合使用

Start the MCP server manually:
bash
ktx mcp start
Then configure your agent's MCP settings to connect to the ktx server.
手动启动MCP服务器:
bash
ktx mcp start
然后配置Agent的MCP设置,连接到ktx服务器。

Common Workflows

常见工作流

Setting Up a New Analytics Project

搭建新的分析项目

bash
undefined
bash
undefined

1. Install ktx

1. 安装ktx

npm install -g @kaelio/ktx
npm install -g @kaelio/ktx

2. Navigate to your project

2. 进入项目目录

cd /path/to/analytics-project
cd /path/to/analytics-project

3. Run interactive setup

3. 运行交互式设置

ktx setup
ktx setup

4. Verify configuration

4. 验证配置

ktx status
ktx status

5. Build initial context

5. 构建初始上下文

ktx ingest
ktx ingest

6. Test search

6. 测试搜索功能

ktx sl "revenue" ktx wiki "metric definitions"
undefined
ktx sl "revenue" ktx wiki "metric definitions"
undefined

Updating Context After Schema Changes

架构变更后更新上下文

bash
undefined
bash
undefined

Rebuild context for specific connection

为指定连接重建上下文

ktx ingest --connection warehouse --rebuild
ktx ingest --connection warehouse --rebuild

Or rebuild everything

或者重建所有内容

ktx ingest --rebuild
undefined
ktx ingest --rebuild
undefined

Adding a New Metric

添加新指标

bash
undefined
bash
undefined

1. Create metric YAML file

1. 创建指标YAML文件

cat > semantic-layer/warehouse/metrics/arr.yaml <<EOF type: metric name: annual_recurring_revenue description: ARR calculated from active subscriptions sql: | SELECT DATE_TRUNC('year', subscription_start) as year, SUM(monthly_amount * 12) as arr FROM subscriptions WHERE status = 'active' GROUP BY 1 dimensions:
  • year measures:
  • arr tags:
  • finance
  • saas EOF
cat > semantic-layer/warehouse/metrics/arr.yaml <<EOF type: metric name: annual_recurring_revenue description: ARR calculated from active subscriptions sql: | SELECT DATE_TRUNC('year', subscription_start) as year, SUM(monthly_amount * 12) as arr FROM subscriptions WHERE status = 'active' GROUP BY 1 dimensions:
  • year measures:
  • arr tags:
  • finance
  • saas EOF

2. Validate

2. 验证文件

ktx sl validate
ktx sl validate

3. Rebuild context

3. 重建上下文

ktx ingest --connection warehouse
ktx ingest --connection warehouse

4. Test search

4. 测试搜索

ktx sl "annual recurring revenue"
undefined
ktx sl "annual recurring revenue"
undefined

Writing Wiki Documentation

编写知识库文档

bash
undefined
bash
undefined

Create a wiki page

创建知识库页面

mkdir -p wiki/global/metrics cat > wiki/global/metrics/revenue-recognition.md <<EOF
mkdir -p wiki/global/metrics cat > wiki/global/metrics/revenue-recognition.md <<EOF

Revenue Recognition

Revenue Recognition

Overview

Overview

Our revenue recognition follows ASC 606 guidelines.
Our revenue recognition follows ASC 606 guidelines.

Key Rules

Key Rules

  1. Revenue is recognized when service is delivered
  2. Refunds are deducted in the month issued
  3. Deferred revenue is amortized monthly
  1. Revenue is recognized when service is delivered
  2. Refunds are deducted in the month issued
  3. Deferred revenue is amortized monthly

Related Metrics

Related Metrics

  • monthly_revenue
  • deferred_revenue
  • recognized_revenue EOF
  • monthly_revenue
  • deferred_revenue
  • recognized_revenue EOF

Rebuild wiki index

重建知识库索引

ktx ingest
ktx ingest

Search it

搜索知识库

ktx wiki "revenue recognition"
undefined
ktx wiki "revenue recognition"
undefined

Troubleshooting

故障排查

ktx status shows "LLM ready: no"

ktx status显示"LLM ready: no"

Configure LLM provider:
bash
ktx setup
配置LLM提供商:
bash
ktx setup

Follow prompts to configure Anthropic, OpenAI, or Vertex AI

按照提示配置Anthropic、OpenAI或Vertex AI


Or set environment variable:
```bash
export ANTHROPIC_API_KEY=your_key_here
ktx status

或者设置环境变量:
```bash
export ANTHROPIC_API_KEY=your_key_here
ktx status

Database connection fails

数据库连接失败

Test connection:
bash
undefined
测试连接:
bash
undefined

Check credentials in ktx.yaml or .ktx/secrets.yaml

检查ktx.yaml或.ktx/secrets.yaml中的凭证

ktx ingest --connection warehouse --verbose

Common fixes:
- Verify user has SELECT permissions on all tables
- Check firewall/network access to database host
- Ensure SSL settings match your database requirements
- For Snowflake: verify warehouse is running
ktx ingest --connection warehouse --verbose

常见修复方案:
- 验证用户对所有表拥有SELECT权限
- 检查防火墙/网络是否允许访问数据库主机
- 确保SSL设置与数据库要求匹配
- 对于Snowflake:验证仓库正在运行

Semantic layer validation errors

语义层验证报错

bash
undefined
bash
undefined

Validate specific file

验证指定文件

ktx sl validate semantic-layer/warehouse/metrics/revenue.yaml
ktx sl validate semantic-layer/warehouse/metrics/revenue.yaml

Common issues:

常见问题:

- Invalid YAML syntax

- YAML语法无效

- Missing required fields (name, type, sql)

- 缺少必填字段(name、type、sql)

- Referenced tables don't exist

引用的表不存在

- Invalid join definitions

- 关联定义无效

undefined
undefined

MCP server won't start

MCP服务器无法启动

bash
undefined
bash
undefined

Check if project is properly initialized

检查项目是否已正确初始化

ktx status
ktx status

Ensure context is built

确保上下文已构建

ktx ingest
ktx ingest

Start with verbose logging

启用详细日志启动

ktx mcp start --verbose
ktx mcp start --verbose

Check for port conflicts (default: 3000)

检查端口冲突(默认端口:3000)

ktx mcp start --port 3001
undefined
ktx mcp start --port 3001
undefined

Search returns no results

搜索无结果返回

bash
undefined
bash
undefined

Rebuild search indexes

重建搜索索引

ktx ingest --rebuild
ktx ingest --rebuild

Check if context sources are configured

检查上下文源是否已配置

cat ktx.yaml
cat ktx.yaml

Verify semantic layer files exist

验证语义层文件是否存在

ls -la semantic-layer/
ls -la semantic-layer/

Verify wiki files exist

验证知识库文件是否存在

ls -la wiki/global/
undefined
ls -la wiki/global/
undefined

Agent can't access ktx tools

Agent无法访问ktx工具

  1. Verify MCP server is running:
    ktx status
  2. Check agent's MCP configuration points to correct ktx server
  3. Restart agent after starting MCP server
  4. Check MCP server logs:
    ktx mcp start --verbose
  1. 验证MCP服务器是否运行:
    ktx status
  2. 检查Agent的MCP配置是否指向正确的ktx服务器
  3. 启动MCP服务器后重启Agent
  4. 查看MCP服务器日志:
    ktx mcp start --verbose

Best Practices

最佳实践

1. Organize Semantic Layer by Domain

1. 按领域组织语义层

text
semantic-layer/
  warehouse/
    metrics/
      finance/
        revenue.yaml
        arr.yaml
      product/
        dau.yaml
        retention.yaml
    dimensions/
      time.yaml
      geography.yaml
    sources/
      orders.yaml
      customers.yaml
text
semantic-layer/
  warehouse/
    metrics/
      finance/
        revenue.yaml
        arr.yaml
      product/
        dau.yaml
        retention.yaml
    dimensions/
      time.yaml
      geography.yaml
    sources/
      orders.yaml
      customers.yaml

2. Document Metric Business Logic in Wiki

2. 在知识库中记录指标业务逻辑

Link semantic layer metrics to wiki documentation:
yaml
undefined
将语义层指标与知识库文档关联:
yaml
undefined

semantic-layer/warehouse/metrics/revenue.yaml

semantic-layer/warehouse/metrics/revenue.yaml

type: metric name: monthly_revenue description: See wiki/global/metrics/revenue-recognition.md for full details
type: metric name: monthly_revenue description: See wiki/global/metrics/revenue-recognition.md for full details

... rest of definition

... 其余定义内容

undefined
undefined

3. Use Tags for Discovery

3. 使用标签提升可发现性

yaml
type: metric
name: customer_churn_rate
tags:
  - saas
  - retention
  - executive-dashboard
  - monthly-reporting
yaml
type: metric
name: customer_churn_rate
tags:
  - saas
  - retention
  - executive-dashboard
  - monthly-reporting

4. Version Control Everything

4. 版本控制所有内容

bash
undefined
bash
undefined

.gitignore

.gitignore

.ktx/secrets.yaml .ktx/cache/ .ktx/*.db

Commit:
- `ktx.yaml`
- `semantic-layer/`
- `wiki/global/`
.ktx/secrets.yaml .ktx/cache/ .ktx/*.db

提交以下内容到版本控制:
- `ktx.yaml`
- `semantic-layer/`
- `wiki/global/`

5. Set Up Read-Only Database Users

5. 使用只读数据库用户

ktx never writes to your database, but use dedicated read-only credentials:
sql
-- PostgreSQL example
CREATE USER ktx_readonly WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE analytics TO ktx_readonly;
GRANT USAGE ON SCHEMA public TO ktx_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ktx_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public 
  GRANT SELECT ON TABLES TO ktx_readonly;
ktx不会向数据库写入数据,但建议使用专用的只读凭证:
sql
-- PostgreSQL示例
CREATE USER ktx_readonly WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE analytics TO ktx_readonly;
GRANT USAGE ON SCHEMA public TO ktx_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ktx_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public 
  GRANT SELECT ON TABLES TO ktx_readonly;

6. Regular Context Updates

6. 定期更新上下文

Set up a cron job or CI workflow:
bash
#!/bin/bash
设置定时任务或CI工作流:
bash
#!/bin/bash

daily-context-update.sh

daily-context-update.sh

cd /path/to/project ktx ingest --connection warehouse ktx sl validate
undefined
cd /path/to/project ktx ingest --connection warehouse ktx sl validate
undefined

Advanced Usage

高级用法

Custom LLM Configuration

自定义LLM配置

yaml
llm:
  provider: vertex
  model: claude-3-5-sonnet-v2@20250219
  project_id: my-gcp-project
  region: us-central1
  temperature: 0.1
  max_tokens: 4096
yaml
llm:
  provider: vertex
  model: claude-3-5-sonnet-v2@20250219
  project_id: my-gcp-project
  region: us-central1
  temperature: 0.1
  max_tokens: 4096

Multiple Database Connections

多数据库连接

yaml
databases:
  prod_warehouse:
    type: snowflake
    account: prod.us-east-1
    database: ANALYTICS_PROD
  
  staging_warehouse:
    type: snowflake
    account: staging.us-east-1
    database: ANALYTICS_STAGING
  
  postgres_app:
    type: postgres
    host: app-db.internal
    database: application
yaml
databases:
  prod_warehouse:
    type: snowflake
    account: prod.us-east-1
    database: ANALYTICS_PROD
  
  staging_warehouse:
    type: snowflake
    account: staging.us-east-1
    database: ANALYTICS_STAGING
  
  postgres_app:
    type: postgres
    host: app-db.internal
    database: application

Programmatic Usage (TypeScript)

程序化使用(TypeScript)

typescript
import { KtxContext } from '@kaelio/ktx';

const ctx = await KtxContext.load('/path/to/project');

// Search semantic layer
const results = await ctx.searchSemanticLayer('revenue');
console.log(results);

// Get metric definition
const metric = await ctx.getMetric('monthly_revenue');
console.log(metric.sql);

// Search wiki
const wikiResults = await ctx.searchWiki('refund policy');
console.log(wikiResults);
typescript
import { KtxContext } from '@kaelio/ktx';

const ctx = await KtxContext.load('/path/to/project');

// 搜索语义层
const results = await ctx.searchSemanticLayer('revenue');
console.log(results);

// 获取指标定义
const metric = await ctx.getMetric('monthly_revenue');
console.log(metric.sql);

// 搜索知识库
const wikiResults = await ctx.searchWiki('refund policy');
console.log(wikiResults);

Resources

资源