trieve
Expert guidance for Trieve, the all-in-one search infrastructure that combines full-text, semantic, and hybrid search with built-in RAG capabilities. Helps developers implement production search with chunking, re-ranking, recommendations, and analytics without managing vector databases or embedding models.
What this skill does
# Trieve — AI Search Infrastructure
## Overview
Trieve, the all-in-one search infrastructure that combines full-text, semantic, and hybrid search with built-in RAG capabilities. Helps developers implement production search with chunking, re-ranking, recommendations, and analytics without managing vector databases or embedding models.
## Instructions
### Dataset and Chunk Management
Create a dataset and ingest content as chunks:
```typescript
// src/search/ingest.ts — Ingest documents into Trieve
const TRIEVE_API_URL = "https://api.trieve.ai";
const TRIEVE_API_KEY = process.env.TRIEVE_API_KEY!;
const DATASET_ID = process.env.TRIEVE_DATASET_ID!;
async function trieveFetch(path: string, options?: RequestInit) {
const res = await fetch(`${TRIEVE_API_URL}${path}`, {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${TRIEVE_API_KEY}`,
"TR-Dataset": DATASET_ID,
...options?.headers,
},
});
if (!res.ok) throw new Error(`Trieve error: ${await res.text()}`);
return res.json();
}
// Create a chunk (the fundamental unit of searchable content)
async function ingestChunk(params: {
content: string;
link?: string;
tag_set?: string[];
metadata?: Record<string, any>;
group_tracking_id?: string; // Group related chunks (e.g., same document)
}) {
return trieveFetch("/api/chunk", {
method: "POST",
body: JSON.stringify({
chunk_html: params.content, // HTML or plain text content
link: params.link, // Source URL
tag_set: params.tag_set, // Tags for filtering
metadata: params.metadata,
group_tracking_ids: params.group_tracking_id
? [params.group_tracking_id]
: undefined,
upsert_by_tracking_id: true, // Update if exists, insert if not
}),
});
}
// Bulk ingest for large datasets
async function bulkIngest(documents: any[]) {
const chunks = documents.flatMap((doc) => {
// Split long documents into smaller chunks
const paragraphs = doc.content.split("\n\n").filter(Boolean);
return paragraphs.map((paragraph: string, index: number) => ({
chunk_html: paragraph,
tracking_id: `${doc.id}-chunk-${index}`,
link: doc.url,
tag_set: doc.tags,
metadata: {
title: doc.title,
author: doc.author,
section_index: index,
},
group_tracking_ids: [doc.id], // All chunks from same doc in one group
}));
});
// Send in batches of 120 (API limit)
for (let i = 0; i < chunks.length; i += 120) {
const batch = chunks.slice(i, i + 120);
await trieveFetch("/api/chunks", {
method: "POST",
body: JSON.stringify(batch),
});
console.log(`Ingested ${Math.min(i + 120, chunks.length)}/${chunks.length} chunks`);
}
}
```
### Search
Perform full-text, semantic, or hybrid search:
```typescript
// src/search/query.ts — Search with different strategies
// Hybrid search — combines keyword matching with semantic similarity
async function hybridSearch(query: string, options?: {
filters?: Record<string, any>;
page?: number;
pageSize?: number;
scoreThreshold?: number;
}) {
return trieveFetch("/api/chunk/search", {
method: "POST",
body: JSON.stringify({
query,
search_type: "hybrid", // "fulltext" | "semantic" | "hybrid"
page: options?.page ?? 1,
page_size: options?.pageSize ?? 10,
score_threshold: options?.scoreThreshold ?? 0.3,
get_total_pages: true,
highlight_results: true, // Return highlighted snippets
highlight_max_length: 200,
highlight_max_num: 3,
use_weights: true, // Balance keyword vs semantic scores
filters: options?.filters ? {
must: Object.entries(options.filters).map(([field, value]) => ({
field: `metadata.${field}`,
match_any: Array.isArray(value) ? value : [value],
})),
} : undefined,
}),
});
}
// Autocomplete / typeahead search
async function autocomplete(query: string) {
return trieveFetch("/api/chunk/autocomplete", {
method: "POST",
body: JSON.stringify({
query,
search_type: "fulltext", // Keyword-based for speed
page_size: 5,
highlight_results: true,
highlight_max_length: 100,
}),
});
}
// Group search — return results grouped by document
async function groupSearch(query: string) {
return trieveFetch("/api/chunk_group/group_oriented_search", {
method: "POST",
body: JSON.stringify({
query,
search_type: "hybrid",
page: 1,
page_size: 10,
group_size: 3, // Show top 3 chunks per group
}),
});
}
```
### RAG (Retrieval-Augmented Generation)
Use Trieve's built-in RAG to generate answers from your data:
```typescript
// src/search/rag.ts — Generate answers using retrieved context
async function ragQuery(question: string) {
const response = await trieveFetch("/api/chunk/generate", {
method: "POST",
body: JSON.stringify({
prev_messages: [
{ role: "user", content: question },
],
// Search configuration for retrieval step
chunk_filter: null,
search_type: "hybrid",
page_size: 5, // Retrieve top 5 chunks as context
// LLM configuration for generation step
llm_options: {
completion_first: false, // Search first, then generate
system_prompt: "Answer the user's question based on the provided context. If the context doesn't contain the answer, say so. Cite sources.",
temperature: 0.3, // Low temperature for factual answers
max_tokens: 500,
},
highlight_results: true,
}),
});
// Response includes both the generated answer and the source chunks
return {
answer: response.message,
sources: response.chunks.map((c: any) => ({
content: c.chunk.chunk_html,
link: c.chunk.link,
score: c.score,
})),
};
}
// Streaming RAG for real-time response display
async function streamRagQuery(question: string, onChunk: (text: string) => void) {
const response = await fetch(`${TRIEVE_API_URL}/api/chunk/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${TRIEVE_API_KEY}`,
"TR-Dataset": DATASET_ID,
},
body: JSON.stringify({
prev_messages: [{ role: "user", content: question }],
search_type: "hybrid",
page_size: 5,
stream_response: true,
}),
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value);
onChunk(text);
}
}
```
### Recommendations
Get content recommendations based on chunk similarity:
```typescript
// src/search/recommend.ts — Content recommendations
async function getRecommendations(chunkId: string, limit = 5) {
return trieveFetch("/api/chunk/recommend", {
method: "POST",
body: JSON.stringify({
positive_chunk_ids: [chunkId], // "More like this"
negative_chunk_ids: [], // "Less like this"
limit,
strategy: "average_vector", // Average vectors of positive examples
}),
});
}
// Recommend based on user reading history
async function personalizedRecommendations(readChunkIds: string[], limit = 10) {
return trieveFetch("/api/chunk/recommend", {
method: "POST",
body: JSON.stringify({
positive_chunk_ids: readChunkIds.slice(-5), // Last 5 read articles
negative_chunk_ids: [],
limit,
strategy: "average_vector",
filters: {
must_not: readChunkIds.map((id) => ({ // Exclude already-read content
field: "id",
match_any: [id],
})),
},
}),
});
}
```
### Analytics
Track search performance and usRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.