Trieve TypeScript SDK
The `trieve-ts-sdk` is a TypeScript SDK designed to interact with the Trieve API, providing a comprehensive and type-safe interface for integrating Trieve's search, RAG (Retrieval Augmented Generation), and analytics capabilities into applications. As of version 0.0.124, it offers functionalities like semantic and hybrid search, support for MMR (Maximum Marginal Relevance) and recency bias, dataset management, and advanced analytics tracking. The SDK facilitates common operations such as creating chunks, performing queries, and managing topics. It also ships with React components for search and RAG, enabling quicker integration into front-end projects. The Trieve ecosystem, which this SDK interfaces with, has a frequent release cadence, with major updates often introducing new API features like improved analytics, scraping support, and refined API key scoping. Its key differentiators include its focus on search relevance, rich API feature set for RAG, and first-class TypeScript support, making it an ideal choice for developers building AI-powered search experiences.
Common errors
-
TrieveAPIError: Missing or invalid API key
cause The `apiKey` provided to the `TrieveSDK` constructor is invalid, expired, or missing, or lacks the necessary permissions for the requested operation.fixEnsure `process.env.TRIEVE_API_KEY` (or direct `apiKey` value) is correctly set with a valid, active API key obtained from your Trieve dashboard. Verify the API key has the required permissions for your dataset and organization. -
TrieveAPIError: Dataset with ID '<dataset-id>' not found
cause The `datasetId` provided to the `TrieveSDK` constructor does not correspond to an existing dataset in your Trieve account, or the provided API key does not have access to it.fixDouble-check the `process.env.TRIEVE_DATASET_ID` (or direct `datasetId` value) for typos. Confirm the dataset exists in your Trieve account and that the associated API key has the necessary read/write permissions for that dataset. -
TypeError: TrieveSDK is not a constructor
cause This error typically occurs when attempting to use a CommonJS `require` syntax (`const { TrieveSDK } = require(...)`) in an environment expecting ESM `import`s, or if `TrieveSDK` is not properly imported from the package.fixEnsure you are using `import { TrieveSDK } from 'trieve-ts-sdk';` at the top of your file. If in a Node.js CommonJS environment, configure your project for ESM or consider an older SDK version/wrapper if available for CJS compatibility (though this SDK is primarily ESM-first). -
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
cause This is a common TypeScript error indicating that a variable could be `undefined` (or `null`) but the function or property expects a definite `string` (or other non-nullable type). This often happens when reading environment variables.fixImplement nullish coalescing (`?? ''`), optional chaining (`?.`), or explicit type guards (`if (variable) { ... }`) to ensure the value is of the expected type before passing it to SDK methods. For example, `apiKey: process.env.TRIEVE_API_KEY ?? ''`.
Warnings
- breaking The underlying Trieve API, which this SDK communicates with, underwent a significant change in v0.13.0 where API keys were refactored to be scoped to organizations. This may require reconfiguring how API keys are generated and used within your Trieve account and subsequently with the SDK.
- breaking The `trieve-ts-sdk` itself was newly introduced around Trieve project version v0.11.8. Projects previously integrating with the Trieve API via direct REST calls will need to refactor their codebase to utilize the SDK's typed client and methods for improved maintainability and type safety.
- gotcha The `trieve-ts-sdk` package versioning (e.g., `0.0.124`) might not directly align with the main `trieve` project's API versioning (e.g., `v0.13.0`). Users should consult both the SDK's changelog and the main Trieve project's release notes for a complete understanding of breaking changes or new features that might affect the SDK's behavior or available API surface.
- gotcha When performing batch chunk creation or other operations that might be resource-intensive, be aware that the underlying Trieve API might have limits configurable via environment flags (e.g., `BATCH_CHUNK_LIMIT` as of Trieve v0.13.0). Exceeding these limits without proper handling can lead to API errors.
Install
-
npm install trieve-ts-sdk -
yarn add trieve-ts-sdk -
pnpm add trieve-ts-sdk
Imports
- TrieveSDK
const TrieveSDK = require('trieve-ts-sdk').TrieveSDK;import { TrieveSDK } from 'trieve-ts-sdk'; - SearchPayload
import SearchPayload from 'trieve-ts-sdk/dist/types/SearchPayload';
import type { SearchPayload } from 'trieve-ts-sdk'; - SuggestedQueriesResponse
import { SuggestedQueriesResponse } from 'trieve-ts-sdk/functions/chunks';import type { SuggestedQueriesResponse } from 'trieve-ts-sdk'; - getChunksByTrackingIds
import { getChunksByTrackingIds } from 'trieve-ts-sdk/functions/chunks/index';import { getChunksByTrackingIds } from 'trieve-ts-sdk';
Quickstart
import { TrieveSDK } from "trieve-ts-sdk";
import type { SearchPayload } from "trieve-ts-sdk"; // Explicitly import a type for clarity
// Initialize the Trieve SDK client with your API key and dataset ID.
// It's recommended to load these from environment variables for production applications.
const trieve = new TrieveSDK({
apiKey: process.env.TRIEVE_API_KEY ?? "", // Replace with your actual Trieve API Key
datasetId: process.env.TRIEVE_DATASET_ID ?? "", // Replace with your actual Trieve Dataset ID
});
async function performSearch(queryText: string) {
if (!process.env.TRIEVE_API_KEY || !process.env.TRIEVE_DATASET_ID) {
console.error("Missing TRIEVE_API_KEY or TRIEVE_DATASET_ID environment variables. Please set them.");
return;
}
const searchPayload: SearchPayload = {
query: queryText,
search_type: "hybrid", // You can also use "semantic" or "fulltext"
filters: {}, // Optional: Add filters to narrow down search results
page: 1,
page_size: 10,
highlight_results: true,
};
try {
console.log(`Searching for: "${queryText}" in dataset "${trieve.datasetId}"...`);
const data = await trieve.search(searchPayload);
console.log("Search Results:", JSON.stringify(data, null, 2));
if (data.hits && data.hits.length > 0) {
console.log(`Found ${data.hits.length} relevant results.`);
data.hits.forEach((hit, index) => {
console.log(`Result ${index + 1}: ${hit.chunk_html ?? hit.link ?? 'No content preview'}`);
});
} else {
console.log("No results found for your query.");
}
} catch (error) {
console.error("Error during Trieve search:", error);
}
}
// Example usage:
performSearch("What are the key features of the Trieve API and how do I use them?");