grepai-search-advanced
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGrepAI 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
命令行选项
| Option | Description |
|---|---|
| Number of results (default: 10) |
| JSON output format |
| TOON output format (~50% fewer tokens than JSON) |
| Compact output (no content, works with --json or --toon) |
Note:and--jsonare mutually exclusive.--toon
| 选项 | 描述 |
|---|---|
| 结果数量(默认值:10) |
| JSON输出格式 |
| TOON输出格式(令牌用量比JSON少约50%) |
| 紧凑输出(无内容,需配合--json或--toon使用) |
注意:和--json不能同时使用。--toon
JSON Output
JSON输出
Standard JSON
标准JSON
bash
grepai search "authentication" --jsonOutput:
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 --compactOutput:
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 (vs
s,scorevsf)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" --toonOutput:
[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,23bash
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,23Compact TOON (Best for AI)
紧凑TOON(AI场景最佳选择)
bash
grepai search "authentication" --toon --compactOutput:
[2]{end_line,file_path,score,start_line}:
45,src/auth/middleware.go,0.89,15
55,src/auth/jwt.go,0.82,23bash
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,23TOON vs JSON Comparison
TOON与JSON对比
| Format | Tokens (5 results) | Best For |
|---|---|---|
| JSON | ~1,500 | Scripts, parsing |
| JSON compact | ~300 | AI agents |
| TOON | ~250 | AI agents |
| TOON compact | ~150 | Token-constrained AI |
| 格式 | 令牌用量(5条结果) | 适用场景 |
|---|---|---|
| JSON | ~1,500 | 脚本、解析处理 |
| JSON紧凑版 | ~300 | AI Agent |
| TOON | ~250 | AI 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 Key | Compact Key | Description |
|---|---|---|
| | Search query |
| | Results array |
| | Similarity score |
| | File path |
| | Line range ("15-45") |
| | Total results |
| 完整键名 | 紧凑键名 | 描述 |
|---|---|---|
| | 搜索查询词 |
| | 结果数组 |
| | 相似度评分 |
| | 文件路径 |
| | 行范围("15-45") |
| | 总结果数 |
Combining Options
选项组合使用
bash
undefinedbash
undefined5 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
undefinedgrepai search "database" --limit 20 --json
undefinedAI Agent Integration
AI Agent集成
For Claude/GPT Prompts
用于Claude/GPT提示词
Use compact mode to minimize tokens:
bash
undefined使用紧凑模式最小化令牌用量:
bash
undefinedAgent 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
工作流示例
- Search for relevant code:
bash
grepai search "authentication middleware" --json --compact --limit 3- 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
}- Read specific files:
AI reads for full context.
src/auth/middleware.go:15-45
- 搜索相关代码:
bash
grepai search "authentication middleware" --json --compact --limit 3- 获取响应:
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
}- 读取特定文件:
AI读取以获取完整上下文。
src/auth/middleware.go:15-45
Scripting with JSON
结合JSON的脚本开发
Bash + jq
Bash + jq
bash
undefinedbash
undefinedGet 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'
undefinedgrepai search "config" --json | jq '.total'
undefinedPython
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
undefinedGrepAI提供支持格式选择的MCP工具(v0.26.0+):
bash
undefinedStart 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: (default) or
"json""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:
| Format | Approximate 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
各格式适用场景
| Format | Use Case |
|---|---|
| Human-readable | Manual inspection |
| JSON full | Scripts needing content |
| JSON compact | AI agents, token-limited contexts |
| 格式 | 适用场景 |
|---|---|
| 人类可读格式 | 人工检查 |
| 完整JSON | 需要内容的脚本 |
| 紧凑JSON | AI Agent、令牌受限场景 |
Piping Results
结果管道传输
To File
输出到文件
bash
grepai search "authentication" --json > results.jsonbash
grepai search "authentication" --json > results.jsonTo Another Tool
传输至其他工具
bash
undefinedbash
undefinedOpen 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
undefinedgrepai search "config" --json | jq -r '.results[0].file' | pbcopy
undefinedBatch 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
doneError 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
fibash
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
fiBest Practices
最佳实践
- Use compact for AI agents: 80% token savings
- Use full JSON for scripts: When you need content
- Use human-readable for debugging: Easier to read
- Limit results appropriately: Don't fetch more than needed
- Check for errors: Parse JSON response properly
- AI Agent使用紧凑格式: 节省80%令牌用量
- 脚本使用完整JSON: 需要内容时
- 调试使用人类可读格式: 更易阅读
- 合理限制结果数量: 不要获取超出需求的结果
- 检查错误: 正确解析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个)