grepai-search-advanced

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GrepAI Advanced Search Options

GrepAI 高级搜索选项

This skill covers advanced search options including JSON output, compact mode, and integration with AI agents.
本技能涵盖了包括JSON输出、紧凑模式以及与AI Agent集成在内的高级搜索选项。

When to Use This Skill

何时使用本技能

  • Integrating GrepAI with scripts or tools
  • Using GrepAI with AI agents (Claude, GPT)
  • Processing search results programmatically
  • Reducing token usage in AI contexts
  • 将GrepAI与脚本或工具集成
  • 与AI Agent(Claude、GPT)搭配使用GrepAI
  • 以编程方式处理搜索结果
  • 在AI场景中减少令牌使用

Command-Line Options

命令行选项

OptionDescription
--limit N
Number of results (default: 10)
--json
/
-j
JSON output format
--toon
/
-t
TOON output format (~50% fewer tokens than JSON)
--compact
/
-c
Compact output (no content, works with --json or --toon)
Note:
--json
and
--toon
are mutually exclusive.
选项描述
--limit N
结果数量(默认值:10)
--json
/
-j
JSON输出格式
--toon
/
-t
TOON输出格式(令牌用量比JSON少约50%)
--compact
/
-c
紧凑输出(无内容,需配合--json或--toon使用)
注意:
--json
--toon
不能同时使用。

JSON Output

JSON输出

Standard JSON

标准JSON

bash
grepai search "authentication" --json
Output:
json
{
  "query": "authentication",
  "results": [
    {
      "score": 0.89,
      "file": "src/auth/middleware.go",
      "start_line": 15,
      "end_line": 45,
      "content": "func AuthMiddleware() gin.HandlerFunc {\n    return func(c *gin.Context) {\n        token := c.GetHeader(\"Authorization\")\n        if token == \"\" {\n            c.AbortWithStatus(401)\n            return\n        }\n        claims, err := ValidateToken(token)\n        ...\n    }\n}"
    },
    {
      "score": 0.82,
      "file": "src/auth/jwt.go",
      "start_line": 23,
      "end_line": 55,
      "content": "func ValidateToken(tokenString string) (*Claims, error) {\n    ..."
    }
  ],
  "total": 2
}
bash
grepai search "authentication" --json
输出:
json
{
  "query": "authentication",
  "results": [
    {
      "score": 0.89,
      "file": "src/auth/middleware.go",
      "start_line": 15,
      "end_line": 45,
      "content": "func AuthMiddleware() gin.HandlerFunc {\n    return func(c *gin.Context) {\n        token := c.GetHeader(\"Authorization\")\n        if token == \"\" {\n            c.AbortWithStatus(401)\n            return\n        }\n        claims, err := ValidateToken(token)\n        ...\n    }\n}"
    },
    {
      "score": 0.82,
      "file": "src/auth/jwt.go",
      "start_line": 23,
      "end_line": 55,
      "content": "func ValidateToken(tokenString string) (*Claims, error) {\n    ..."
    }
  ],
  "total": 2
}

Compact JSON (AI Optimized)

紧凑JSON(AI优化版)

bash
grepai search "authentication" --json --compact
Output:
json
{
  "q": "authentication",
  "r": [
    {
      "s": 0.89,
      "f": "src/auth/middleware.go",
      "l": "15-45"
    },
    {
      "s": 0.82,
      "f": "src/auth/jwt.go",
      "l": "23-55"
    }
  ],
  "t": 2
}
Key differences:
  • Abbreviated keys (
    s
    vs
    score
    ,
    f
    vs
    file
    )
  • No content (just file locations)
  • ~80% fewer tokens for AI agents
bash
grepai search "authentication" --json --compact
输出:
json
{
  "q": "authentication",
  "r": [
    {
      "s": 0.89,
      "f": "src/auth/middleware.go",
      "l": "15-45"
    },
    {
      "s": 0.82,
      "f": "src/auth/jwt.go",
      "l": "23-55"
    }
  ],
  "t": 2
}
核心差异:
  • 缩写键名(
    s
    对应
    score
    f
    对应
    file
  • 无内容字段(仅包含文件位置)
  • 对AI Agent而言令牌用量减少约80%

TOON Output (v0.26.0+)

TOON输出(v0.26.0+)

TOON (Token-Oriented Object Notation) is an even more compact format, optimized for AI agents.
TOON(面向令牌的对象表示法)是一种更紧凑的格式,专为AI Agent优化。

Standard TOON

标准TOON

bash
grepai search "authentication" --toon
Output:
[2]{content,end_line,file_path,score,start_line}:
  "func AuthMiddleware()...",45,src/auth/middleware.go,0.89,15
  "func ValidateToken()...",55,src/auth/jwt.go,0.82,23
bash
grepai search "authentication" --toon
输出:
[2]{content,end_line,file_path,score,start_line}:
  "func AuthMiddleware()...",45,src/auth/middleware.go,0.89,15
  "func ValidateToken()...",55,src/auth/jwt.go,0.82,23

Compact TOON (Best for AI)

紧凑TOON(AI场景最佳选择)

bash
grepai search "authentication" --toon --compact
Output:
[2]{end_line,file_path,score,start_line}:
  45,src/auth/middleware.go,0.89,15
  55,src/auth/jwt.go,0.82,23
bash
grepai search "authentication" --toon --compact
输出:
[2]{end_line,file_path,score,start_line}:
  45,src/auth/middleware.go,0.89,15
  55,src/auth/jwt.go,0.82,23

TOON vs JSON Comparison

TOON与JSON对比

FormatTokens (5 results)Best For
JSON~1,500Scripts, parsing
JSON compact~300AI agents
TOON~250AI agents
TOON compact~150Token-constrained AI
格式令牌用量(5条结果)适用场景
JSON~1,500脚本、解析处理
JSON紧凑版~300AI Agent
TOON~250AI Agent
TOON紧凑版~150令牌受限的AI场景

When to Use TOON

何时使用TOON

  • Use TOON when integrating with AI agents that support it
  • Use TOON compact for maximum token efficiency (~50% smaller than JSON compact)
  • Stick with JSON for traditional scripting (jq, programming languages)
  • 使用TOON:与支持该格式的AI Agent集成时
  • 使用TOON紧凑版:追求最高令牌效率(比JSON紧凑版小约50%)
  • 坚持使用JSON:传统脚本场景(jq、编程语言)

Compact Format Reference

紧凑格式参考

Full KeyCompact KeyDescription
query
q
Search query
results
r
Results array
score
s
Similarity score
file
f
File path
start_line
/
end_line
l
Line range ("15-45")
total
t
Total results
完整键名紧凑键名描述
query
q
搜索查询词
results
r
结果数组
score
s
相似度评分
file
f
文件路径
start_line
/
end_line
l
行范围("15-45")
total
t
总结果数

Combining Options

选项组合使用

bash
undefined
bash
undefined

5 results in compact JSON

5条结果的紧凑JSON格式

grepai search "error handling" --limit 5 --json --compact
grepai search "error handling" --limit 5 --json --compact

20 results in full JSON

20条结果的完整JSON格式

grepai search "database" --limit 20 --json
undefined
grepai search "database" --limit 20 --json
undefined

AI Agent Integration

AI Agent集成

For Claude/GPT Prompts

用于Claude/GPT提示词

Use compact mode to minimize tokens:
bash
undefined
使用紧凑模式最小化令牌用量:
bash
undefined

Agent asks for context

Agent请求上下文

grepai search "payment processing" --json --compact --limit 5

Then provide results to the AI with file read tool for details.
grepai search "payment processing" --json --compact --limit 5

随后将结果提供给AI,并配合文件读取工具获取详细内容。

Workflow Example

工作流示例

  1. Search for relevant code:
bash
grepai search "authentication middleware" --json --compact --limit 3
  1. Get response:
json
{
  "q": "authentication middleware",
  "r": [
    {"s": 0.92, "f": "src/auth/middleware.go", "l": "15-45"},
    {"s": 0.85, "f": "src/auth/jwt.go", "l": "23-55"},
    {"s": 0.78, "f": "src/handlers/auth.go", "l": "10-40"}
  ],
  "t": 3
}
  1. Read specific files: AI reads
    src/auth/middleware.go:15-45
    for full context.
  1. 搜索相关代码:
bash
grepai search "authentication middleware" --json --compact --limit 3
  1. 获取响应:
json
{
  "q": "authentication middleware",
  "r": [
    {"s": 0.92, "f": "src/auth/middleware.go", "l": "15-45"},
    {"s": 0.85, "f": "src/auth/jwt.go", "l": "23-55"},
    {"s": 0.78, "f": "src/handlers/auth.go", "l": "10-40"}
  ],
  "t": 3
}
  1. 读取特定文件: AI读取
    src/auth/middleware.go:15-45
    以获取完整上下文。

Scripting with JSON

结合JSON的脚本开发

Bash + jq

Bash + jq

bash
undefined
bash
undefined

Get just file paths

仅获取文件路径

grepai search "config" --json | jq -r '.results[].file'
grepai search "config" --json | jq -r '.results[].file'

Filter by score

按评分过滤

grepai search "config" --json | jq '.results[] | select(.score > 0.8)'
grepai search "config" --json | jq '.results[] | select(.score > 0.8)'

Count results

统计结果数量

grepai search "config" --json | jq '.total'
undefined
grepai search "config" --json | jq '.total'
undefined

Python

Python

python
import subprocess
import json

result = subprocess.run(
    ['grepai', 'search', 'authentication', '--json'],
    capture_output=True,
    text=True
)

data = json.loads(result.stdout)
for r in data['results']:
    print(f"{r['score']:.2f} | {r['file']}:{r['start_line']}")
python
import subprocess
import json

result = subprocess.run(
    ['grepai', 'search', 'authentication', '--json'],
    capture_output=True,
    text=True
)

data = json.loads(result.stdout)
for r in data['results']:
    print(f"{r['score']:.2f} | {r['file']}:{r['start_line']}")

Node.js

Node.js

javascript
const { execSync } = require('child_process');

const output = execSync('grepai search "authentication" --json');
const data = JSON.parse(output);

data.results.forEach(r => {
    console.log(`${r.score.toFixed(2)} | ${r.file}:${r.start_line}`);
});
javascript
const { execSync } = require('child_process');

const output = execSync('grepai search "authentication" --json');
const data = JSON.parse(output);

data.results.forEach(r => {
    console.log(`${r.score.toFixed(2)} | ${r.file}:${r.start_line}`);
});

MCP Integration

MCP集成

GrepAI provides MCP tools with format selection (v0.26.0+):
bash
undefined
GrepAI提供支持格式选择的MCP工具(v0.26.0+):
bash
undefined

Start MCP server

启动MCP服务器

grepai mcp-serve

MCP tools support JSON (default) or TOON format:

| MCP Tool | Parameters |
|----------|------------|
| `grepai_search` | `query`, `limit`, `compact`, `format` |
| `grepai_trace_callers` | `symbol`, `compact`, `format` |
| `grepai_trace_callees` | `symbol`, `compact`, `format` |
| `grepai_trace_graph` | `symbol`, `depth`, `format` |
| `grepai_index_status` | `format` |
grepai mcp-serve

MCP工具支持JSON(默认)或TOON格式:

| MCP工具 | 参数 |
|----------|------------|
| `grepai_search` | `query`, `limit`, `compact`, `format` |
| `grepai_trace_callers` | `symbol`, `compact`, `format` |
| `grepai_trace_callees` | `symbol`, `compact`, `format` |
| `grepai_trace_graph` | `symbol`, `depth`, `format` |
| `grepai_index_status` | `format` |

Format Parameter

Format参数

json
{
  "name": "grepai_search",
  "arguments": {
    "query": "authentication",
    "format": "toon",
    "compact": true
  }
}
Valid values:
"json"
(default) or
"toon"
json
{
  "name": "grepai_search",
  "arguments": {
    "query": "authentication",
    "format": "toon",
    "compact": true
  }
}
有效值:
"json"
(默认)或
"toon"

Token Optimization

令牌优化

Token Comparison

令牌用量对比

For a typical search with 5 results:
FormatApproximate Tokens
Human-readable~2,000
JSON full~1,500
JSON compact~300
对于包含5条结果的典型搜索:
格式近似令牌数
人类可读格式~2,000
完整JSON~1,500
紧凑JSON~300

When to Use Each Format

各格式适用场景

FormatUse Case
Human-readableManual inspection
JSON fullScripts needing content
JSON compactAI agents, token-limited contexts
格式适用场景
人类可读格式人工检查
完整JSON需要内容的脚本
紧凑JSONAI Agent、令牌受限场景

Piping Results

结果管道传输

To File

输出到文件

bash
grepai search "authentication" --json > results.json
bash
grepai search "authentication" --json > results.json

To Another Tool

传输至其他工具

bash
undefined
bash
undefined

Open results in VS Code

在VS Code中打开结果

grepai search "config" --json | jq -r '.results[0].file' | xargs code
grepai search "config" --json | jq -r '.results[0].file' | xargs code

Copy first result path to clipboard (macOS)

将首个结果路径复制到剪贴板(macOS)

grepai search "config" --json | jq -r '.results[0].file' | pbcopy
undefined
grepai search "config" --json | jq -r '.results[0].file' | pbcopy
undefined

Batch Searches

批量搜索

Run multiple searches:
bash
#!/bin/bash
queries=("authentication" "database" "logging" "error handling")

for q in "${queries[@]}"; do
    echo "=== $q ==="
    grepai search "$q" --json --compact --limit 3
    echo
done
运行多个搜索:
bash
#!/bin/bash
queries=("authentication" "database" "logging" "error handling")

for q in "${queries[@]}"; do
    echo "=== $q ==="
    grepai search "$q" --json --compact --limit 3
    echo
done

Error Handling

错误处理

JSON Error Response

JSON错误响应

When search fails:
json
{
  "error": "Index not found. Run 'grepai watch' first.",
  "code": "INDEX_NOT_FOUND"
}
搜索失败时:
json
{
  "error": "Index not found. Run 'grepai watch' first.",
  "code": "INDEX_NOT_FOUND"
}

Checking for Errors in Scripts

脚本中的错误检查

bash
result=$(grepai search "query" --json)
if echo "$result" | jq -e '.error' > /dev/null 2>&1; then
    echo "Error: $(echo "$result" | jq -r '.error')"
    exit 1
fi
bash
result=$(grepai search "query" --json)
if echo "$result" | jq -e '.error' > /dev/null 2>&1; then
    echo "Error: $(echo "$result" | jq -r '.error')"
    exit 1
fi

Best Practices

最佳实践

  1. Use compact for AI agents: 80% token savings
  2. Use full JSON for scripts: When you need content
  3. Use human-readable for debugging: Easier to read
  4. Limit results appropriately: Don't fetch more than needed
  5. Check for errors: Parse JSON response properly
  1. AI Agent使用紧凑格式: 节省80%令牌用量
  2. 脚本使用完整JSON: 需要内容时
  3. 调试使用人类可读格式: 更易阅读
  4. 合理限制结果数量: 不要获取超出需求的结果
  5. 检查错误: 正确解析JSON响应

Output Format

输出格式示例

Advanced search output (JSON compact):
json
{
  "q": "authentication middleware",
  "r": [
    {"s": 0.92, "f": "src/auth/middleware.go", "l": "15-45"},
    {"s": 0.85, "f": "src/auth/jwt.go", "l": "23-55"},
    {"s": 0.78, "f": "src/handlers/auth.go", "l": "10-40"}
  ],
  "t": 3
}
Token estimate: ~80 tokens (vs ~800 for full content)
高级搜索输出(紧凑JSON):
json
{
  "q": "authentication middleware",
  "r": [
    {"s": 0.92, "f": "src/auth/middleware.go", "l": "15-45"},
    {"s": 0.85, "f": "src/auth/jwt.go", "l": "23-55"},
    {"s": 0.78, "f": "src/handlers/auth.go", "l": "10-40"}
  ],
  "t": 3
}
令牌估算: 80个令牌(对比完整内容的800个)