ktx-ai-data-agents-context
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesektx 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/ktxbash
npm install -g @kaelio/ktxProject-Specific Installation
项目级安装
bash
npm install --save-dev @kaelio/ktxOr with pnpm:
bash
pnpm add -D @kaelio/ktxbash
npm install --save-dev @kaelio/ktx或者使用pnpm:
bash
pnpm add -D @kaelio/ktxInitial Setup
初始设置
Interactive Setup (Recommended)
交互式设置(推荐)
bash
ktx setupThis command:
- Creates or resumes a local ktx project
- Configures LLM and embedding providers
- Configures database connections
- Configures context sources (dbt, Looker, Metabase, Notion)
- Builds initial context
- Installs agent integration (MCP or Skills)
bash
ktx setup该命令会:
- 创建或恢复本地ktx项目
- 配置LLM和嵌入模型提供商
- 配置数据库连接
- 配置上下文源(dbt、Looker、Metabase、Notion)
- 构建初始上下文
- 安装Agent集成(MCP或Skills)
Check Project Status
检查项目状态
bash
ktx statusExample 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_TOKENyaml
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
undefinedktx支持以下环境变量:
bash
undefinedLLM 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
undefinedexport KTX_PROJECT_DIR=/path/to/project
undefinedKey Commands
核心命令
Building Context
构建上下文
bash
undefinedbash
undefinedBuild 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
undefinedktx ingest --rebuild
undefinedSearching Context
搜索上下文
bash
undefinedbash
undefinedSearch 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"
undefinedktx search "monthly recurring revenue"
undefinedMCP Server (for AI Agents)
MCP服务器(用于AI Agent)
bash
undefinedbash
undefinedStart 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
undefinedktx mcp tools
undefinedManaging Semantic Layer
管理语义层
bash
undefinedbash
undefinedValidate 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
undefinedktx sl show monthly_revenue
undefinedDatabase Connection Examples
数据库连接示例
PostgreSQL
PostgreSQL
yaml
databases:
warehouse:
type: postgres
host: localhost
port: 5432
database: analytics
user: readonly_user
ssl: trueyaml
databases:
warehouse:
type: postgres
host: localhost
port: 5432
database: analytics
user: readonly_user
ssl: trueSnowflake
Snowflake
yaml
databases:
snowflake_prod:
type: snowflake
account: xy12345.us-east-1
warehouse: COMPUTE_WH
database: ANALYTICS
schema: PUBLIC
user: readonly_user
role: ANALYSTyaml
databases:
snowflake_prod:
type: snowflake
account: xy12345.us-east-1
warehouse: COMPUTE_WH
database: ANALYTICS
schema: PUBLIC
user: readonly_user
role: ANALYSTBigQuery
BigQuery
yaml
databases:
bigquery_prod:
type: bigquery
project_id: my-gcp-project
dataset: analytics
credentials_file: /path/to/service-account.jsonyaml
databases:
bigquery_prod:
type: bigquery
project_id: my-gcp-project
dataset: analytics
credentials_file: /path/to/service-account.jsonClickHouse
ClickHouse
yaml
databases:
clickhouse:
type: clickhouse
host: localhost
port: 9000
database: analytics
user: readonlyyaml
databases:
clickhouse:
type: clickhouse
host: localhost
port: 9000
database: analytics
user: readonlyContext Source Examples
上下文源示例
dbt
dbt
yaml
context_sources:
dbt_main:
type: dbt
project_dir: ./dbt
profiles_dir: ~/.dbt
target: prodyaml
context_sources:
dbt_main:
type: dbt
project_dir: ./dbt
profiles_dir: ~/.dbt
target: prodLookML
LookML
yaml
context_sources:
looker:
type: lookml
project_dir: ./looker-project
models:
- sales
- marketingyaml
context_sources:
looker:
type: lookml
project_dir: ./looker-project
models:
- sales
- marketingMetabase
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 Analyticsyaml
context_sources:
metabase:
type: metabase
url: https://metabase.company.com
# Token存储在.ktx/secrets.yaml或环境变量METABASE_TOKEN中
collections:
- Sales Dashboards
- Marketing AnalyticsNotion
Notion
yaml
context_sources:
notion_wiki:
type: notion
# Token in .ktx/secrets.yaml or NOTION_TOKEN env var
page_ids:
- abc123def456
- ghi789jkl012yaml
context_sources:
notion_wiki:
type: notion
# Token存储在.ktx/secrets.yaml或环境变量NOTION_TOKEN中
page_ids:
- abc123def456
- ghi789jkl012Semantic Layer YAML
语义层YAML
Defining a Metric
定义指标
yaml
undefinedyaml
undefinedsemantic-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
undefinedtype: 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
undefinedDefining a Dimension
定义维度
yaml
undefinedyaml
undefinedsemantic-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
undefinedtype: 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
undefinedDefining a Joinable Source
定义可关联数据源
yaml
undefinedyaml
undefinedsemantic-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
undefinedtype: 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
undefinedAgent Integration
Agent集成
Using with Claude Code
与Claude Code配合使用
After running , ktx installs MCP integration automatically. The MCP server provides these tools:
ktx setup- : Search metrics, dimensions, sources
ktx_search_semantic_layer - : Search wiki content
ktx_search_wiki - : Get full metric definition
ktx_get_metric - : Preview SQL for a semantic query
ktx_query_preview
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会自动安装MCP集成。MCP服务器提供以下工具:
ktx setup- : 搜索指标、维度、数据源
ktx_search_semantic_layer - : 搜索知识库内容
ktx_search_wiki - : 获取完整指标定义
ktx_get_metric - : 预览语义查询的SQL语句
ktx_query_preview
在Claude Code中使用:
text
Use ktx to find our revenue metrics
What wiki pages discuss refund policies?
Show me the SQL for monthly_recurring_revenue metricUsing with Codex
与Codex配合使用
bash
undefinedbash
undefinedInstall 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 calculationktx setup
Codex现在可以使用ktx工具:
```text
Query our warehouse for Q1 2024 revenue by customer segment
Find documentation about our churn calculationUsing with Cursor or OpenCode
与Cursor或OpenCode配合使用
Start the MCP server manually:
bash
ktx mcp startThen 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
undefinedbash
undefined1. 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"
undefinedktx sl "revenue"
ktx wiki "metric definitions"
undefinedUpdating Context After Schema Changes
架构变更后更新上下文
bash
undefinedbash
undefinedRebuild context for specific connection
为指定连接重建上下文
ktx ingest --connection warehouse --rebuild
ktx ingest --connection warehouse --rebuild
Or rebuild everything
或者重建所有内容
ktx ingest --rebuild
undefinedktx ingest --rebuild
undefinedAdding a New Metric
添加新指标
bash
undefinedbash
undefined1. 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"
undefinedktx sl "annual recurring revenue"
undefinedWriting Wiki Documentation
编写知识库文档
bash
undefinedbash
undefinedCreate 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
- Revenue is recognized when service is delivered
- Refunds are deducted in the month issued
- Deferred revenue is amortized monthly
- Revenue is recognized when service is delivered
- Refunds are deducted in the month issued
- 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"
undefinedktx wiki "revenue recognition"
undefinedTroubleshooting
故障排查
ktx status shows "LLM ready: no"
ktx status显示"LLM ready: no"
Configure LLM provider:
bash
ktx setup配置LLM提供商:
bash
ktx setupFollow 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 statusDatabase connection fails
数据库连接失败
Test connection:
bash
undefined测试连接:
bash
undefinedCheck 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 runningktx ingest --connection warehouse --verbose
常见修复方案:
- 验证用户对所有表拥有SELECT权限
- 检查防火墙/网络是否允许访问数据库主机
- 确保SSL设置与数据库要求匹配
- 对于Snowflake:验证仓库正在运行Semantic layer validation errors
语义层验证报错
bash
undefinedbash
undefinedValidate 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
- 关联定义无效
undefinedundefinedMCP server won't start
MCP服务器无法启动
bash
undefinedbash
undefinedCheck 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
undefinedktx mcp start --port 3001
undefinedSearch returns no results
搜索无结果返回
bash
undefinedbash
undefinedRebuild 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/
undefinedls -la wiki/global/
undefinedAgent can't access ktx tools
Agent无法访问ktx工具
- Verify MCP server is running:
ktx status - Check agent's MCP configuration points to correct ktx server
- Restart agent after starting MCP server
- Check MCP server logs:
ktx mcp start --verbose
- 验证MCP服务器是否运行:
ktx status - 检查Agent的MCP配置是否指向正确的ktx服务器
- 启动MCP服务器后重启Agent
- 查看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.yamltext
semantic-layer/
warehouse/
metrics/
finance/
revenue.yaml
arr.yaml
product/
dau.yaml
retention.yaml
dimensions/
time.yaml
geography.yaml
sources/
orders.yaml
customers.yaml2. Document Metric Business Logic in Wiki
2. 在知识库中记录指标业务逻辑
Link semantic layer metrics to wiki documentation:
yaml
undefined将语义层指标与知识库文档关联:
yaml
undefinedsemantic-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
... 其余定义内容
undefinedundefined3. Use Tags for Discovery
3. 使用标签提升可发现性
yaml
type: metric
name: customer_churn_rate
tags:
- saas
- retention
- executive-dashboard
- monthly-reportingyaml
type: metric
name: customer_churn_rate
tags:
- saas
- retention
- executive-dashboard
- monthly-reporting4. Version Control Everything
4. 版本控制所有内容
bash
undefinedbash
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/bashdaily-context-update.sh
daily-context-update.sh
cd /path/to/project
ktx ingest --connection warehouse
ktx sl validate
undefinedcd /path/to/project
ktx ingest --connection warehouse
ktx sl validate
undefinedAdvanced 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: 4096yaml
llm:
provider: vertex
model: claude-3-5-sonnet-v2@20250219
project_id: my-gcp-project
region: us-central1
temperature: 0.1
max_tokens: 4096Multiple 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: applicationyaml
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: applicationProgrammatic 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
资源
- Documentation: https://docs.kaelio.com/ktx
- GitHub: https://github.com/Kaelio/ktx
- Slack Community: https://join.slack.com/t/ktxcommunity/shared_invite/zt-3y9b44m1x-LVyNNJD5nwaZHq4XS29LMQ
- CLI Reference: https://docs.kaelio.com/ktx/docs/cli-reference/ktx
- Agent Setup Guide: https://docs.kaelio.com/ktx/docs/ai-resources/agent-quickstart
- 官方文档: https://docs.kaelio.com/ktx
- GitHub: https://github.com/Kaelio/ktx
- Slack社区: https://join.slack.com/t/ktxcommunity/shared_invite/zt-3y9b44m1x-LVyNNJD5nwaZHq4XS29LMQ
- CLI参考: https://docs.kaelio.com/ktx/docs/cli-reference/ktx
- Agent快速入门: https://docs.kaelio.com/ktx/docs/ai-resources/agent-quickstart