Knowledge Bases
Store searchable context for your AI agents, and manage it with metadata schemas, automatic extraction, and query-time filtering.
Why Use a Knowledge Base
A knowledge base stores the context your AI agents pull from when answering questions, and is the same as the Knowledge Base ability in the Agent Studio. Adding context allows an agent to provide relevant answers on specific topics that may not be part of the underlying AI model.
The following are simple code examples, though the context you add can be much more complex. Some good examples of context include resources like code documentation, product manuals, business operations (e.g., store hours) and user-specific data. You can mix and match context types to create a robust knowledge base for your AI agent, ensuring that it can provide any information your users will need.
Creating a Knowledge Base
To add or update agent context, you must first create and connect a knowledge base.
First, create the new knowledge base with an embedding model that we provide out of the box:
await squid.ai().knowledgeBase('banking-knowledgebase').upsertKnowledgeBase({
description: 'This Knowledge Base contains information on card data',
embeddingModel: 'text-embedding-3-small',
chatModel: 'gpt-6.2-sol',
metadataFields: [],
});
Or, you can use an integration-based embedding model by passing an object with the connector ID, model name, and dimensions. See the OpenAI Compatible Embedding connector for setup instructions.
await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.upsertKnowledgeBase({
description: 'This Knowledge Base contains information on card data',
embeddingModel: {
integrationId: 'my-embeddings',
model: 'text-embedding-3-small',
dimensions: 1536,
},
chatModel: 'gpt-6.2-sol',
metadataFields: [],
});
A knowledge base stores its vectors in one of two backends: 'mongoAtlas', which supports native hybrid fusion, ranked keyword search (see Keyword search), and knowledge graph search, or 'postgres', which supports none of these. Omitting vectorDbType takes the server default, which depends on the deployment your application runs on. Pass it explicitly when your application depends on a specific backend. The backend cannot be changed after creation, and you can read it back with getKnowledgeBase():
await squid.ai().knowledgeBase('banking-knowledgebase-atlas').upsertKnowledgeBase({
description: 'This Knowledge Base contains information on card data',
embeddingModel: 'text-embedding-3-small',
chatModel: 'gpt-6.2-sol',
metadataFields: [],
vectorDbType: 'mongoAtlas',
});
const kb = await squid.ai().knowledgeBase('banking-knowledgebase-atlas').getKnowledgeBase();
console.log(kb?.vectorDbType); // 'mongoAtlas'
getKnowledgeBase() resolves to the stored knowledge base record (including vectorDbType), or to undefined when no knowledge base exists with that ID. Upserting a different vectorDbType onto an existing knowledge base throws an error rather than changing the backend.
Because the backend is fixed at creation, it also decides whether knowledge graph search can ever be enabled: a knowledge base created on 'postgres' cannot gain a graph. Pass vectorDbType: 'mongoAtlas' rather than relying on the server default if you may want one later.
Upserting Context
To add context to the knowledge base, use the upsertContext() method, passing the context and its type.
The upsertContext() method accepts a context ID. Providing a context ID allows you to more easily access context later for when you want to make changes.
const data = `Platinum Mastercard® Fair Credit, No annual fee. Flexible due dates...`;
await squid.ai().knowledgeBase('banking-knowledgebase').upsertContext({
type: 'text',
title: 'Credit Card Info',
text: data,
contextId: 'credit-cards',
});
Alternatively, use upsertContexts() to upsert an array of contexts.
const creditCard1 = `Platinum Mastercard® Fair Credit, No annual fee. Flexible due dates...`;
const creditCard2 = `Gold Mastercard®, $50 annual fee. Due dates once a month...`;
await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.upsertContexts([
{
type: 'text',
title: 'Credit Card 1 Info',
text: creditCard1,
contextId: 'credit-cards1',
},
{
type: 'text',
title: 'Credit Card 2 Info',
text: creditCard2,
contextId: 'credit-cards2',
},
]);
upsertContexts() resolves even when individual contexts are rejected, listing each rejection in
failures. A rejection carries an errorMessage, and an errorCode when a machine-readable class
applies. A failure that carries retryable: false fails the same way on the same bytes, so park the
document instead of re-submitting it; a failure without that flag may be transient:
errorCode | Meaning | What to do |
|---|---|---|
DUPLICATE_CONTENT | The request omitted a contextId and its content is byte-identical to a context the knowledge base already holds. | Not a failure. duplicateOf points at the existing context, so you can show the user where the original lives. |
EMBEDDING_FAILED | Extraction succeeded but embedding the context's chunks did not. Nothing was written, and an overwrite target keeps its previous content. | Retry the request as-is. It is safe to replay unchanged. |
CONTENT_IN_FLIGHT | The same content is already being ingested by another request. | Retry after the other request settles. |
EMBEDDED_CHILDREN_NOT_RECONCILED | The context's indexed attachments were not reconciled yet. | Retry. |
EXTRACTION_TIMED_OUT | Extraction missed its deadline, which can happen to a borderline document under load. | Retry. |
SOURCE_UNREACHABLE | The extraction provider could not fetch the source bytes. | Retry, with a fresh link if one is involved. |
PROVIDER_ACCESS_DENIED | The extraction provider refused the credential, or its quota is spent. | Fix the provider credential or quota, then retry. |
CONTENT_TOO_LARGE | The extracted text exceeds the 5 MB per-context ceiling. | Terminal. Split the document. |
ENCRYPTED_DOCUMENT | The file is password-protected. | Terminal. Remove the protection and re-upload. |
UNREADABLE_DOCUMENT | A PDF or Office file whose bytes cannot be opened as one. | Terminal. Re-export the file. |
UNREADABLE_WORKBOOK | A spreadsheet whose content the parser cannot read. | Terminal. Re-export the workbook. |
UNSUPPORTED_FILE_TYPE | The file type is not supported for extraction. | Terminal. Convert the file to a supported format. |
NO_EMBEDDABLE_CONTENT | Nothing extractable was found in the document. | Terminal. |
IMAGE_OVER_PROVIDER_LIMIT | The OCR provider refuses an image in the document as too large. | Terminal. Shrink or remove the image. |
SOURCE_OVER_PROVIDER_LIMIT | The file's bytes exceed what the extraction provider accepts. | Terminal. Split or shrink the file. |
A successful upsert can still report partial image trouble: when describing an embedded image fails,
the context is stored without that image's chunk and the response lists the failures in
imageFailures (capped) with the total in imageFailureCount.
Connecting to an Agent
A knowledge base only affects an agent's answers once it is connected to that agent. To connect a knowledge base and configure how the agent uses it, see Connect a Knowledge Base to an Agent.
Context Types
Two types of contexts are supported: text and file.
Text context is created with a string that contains the context:
const data = `Platinum Mastercard® Fair Credit, No annual fee. Flexible due dates...`;
await squid.ai().knowledgeBase('banking-knowledgebase').upsertContext({
type: 'text',
title: 'Credit Card Info',
text: data,
contextId: 'credit-cards',
});
File context is created by providing a File object as a second parameter to the upsertContext() method. The file is then uploaded to Squid and the context is created from the file contents. File contexts also accept a preferredExtractionMethod field on the context object (the first upsertContext() argument) that selects how the document is extracted, such as legacy_with_llm (shown as Basic + page understanding in the Console), which adds an AI description of each page alongside its text; see Extraction methods.
const file = new File([contextBlob], 'CreditCardList.pdf', { type: 'application/pdf' });
await squid.ai().knowledgeBase('banking-knowledgebase').upsertContext(
{
type: 'file',
contextId: 'credit-cards',
preferredExtractionMethod: 'legacy_with_llm',
},
file
);
Your context can be as long as you like; however since there are character limits to LLM prompts, only a portion of your context may actually be included alongside the user's inquiry. When constructing a prompt, Squid decides which portions of the supplied context are most relevant to the user's question.
OneNote sections and attachments
OneNote section files (.one) are a supported file context type, with a larger size allowance (1.5 GB per section file, where other files are capped at 500 MB). Attachments embedded in .one sections and in .msg and .eml email files are indexed as their own hidden child contexts, up to 1,000 per container. A child context carries parentContextId pointing at its container, is managed together with it (deleting the container deletes the children), and is left out of listContexts() results.
Spreadsheet Files
Spreadsheet files (.csv, .tsv, .xlsx, .xlsm, .xls, and .xlsb) uploaded as file context are handled by a dedicated ingestion pipeline. Instead of chunking raw cell text, Squid extracts the workbook's structure (sheet names and sizes, header rows, hidden sheets, and, where the file format provides them, charts and pivot tables) and embeds a generated summary of the whole workbook. Search results for spreadsheet contexts therefore describe what a workbook contains rather than returning fragments of cell data.
Summaries are previews, so agents do not rely on them for exact numbers. When a connected knowledge base contains spreadsheet contexts, the agent automatically gets a querySpreadsheetsWithAi tool that answers questions against the actual uploaded files by running Python in a sandbox:
- Exact values: counts, sums, averages, lookups of specific rows or cells, filtering, and sorting.
- Questions spanning several workbooks, such as joining or comparing data across files, in a single call.
- Structure and provenance questions: what a sheet actually contains, which sheets feed live calculations, and which cells are formulas versus hardcoded inputs. Formula and dependency inspection is fullest for
.xlsx/.xlsm, partial for.xls, and unavailable for.xlsb(cell values only) and CSV/TSV (no formula metadata).
No configuration is required, but the dedicated pipeline and the agent tool depend on the retained original file. When a context is uploaded with discardOriginalFile: true (an upsertContext() file option, false by default, that tells Squid to drop the stored original after text extraction instead of keeping it for reprocessing and download), the spreadsheet is ingested as plain extracted text and querySpreadsheetsWithAi is not offered for it.
Getting Context
To get a list of all contexts, use the listContexts() method. This method returns an array of agent context objects, which includes the contextId:
await squid.ai().knowledgeBase('banking-knowledgebase').listContexts();
To get a specific context item, use the getContext() method, passing the context ID:
await squid.ai().knowledgeBase('banking-knowledgebase').getContext('credit-cards');
Listing a page of context
listContexts() returns every context in the knowledge base, which becomes unwieldy once a knowledge
base holds thousands of entries. Use listContextsPage() to page through them instead, and to search
by ID or title:
- TypeScript
- Python
const page = await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.listContextsPage({
offset: 0,
limit: 50,
// Truncates each entry's text so a listing stays small.
truncateTextAfter: 500,
// Case-insensitive substring match on context ID and title only, not on the text.
search: 'credit',
});
page = await squid.ai().knowledge_base('banking-knowledgebase').list_contexts_page(
offset=0,
limit=50,
search='credit',
truncate_text_after=500,
)
Every option is optional. The response carries the requested contexts plus a totalCount that
ignores offset and limit, so you can render a page count without a second call.
search matches the context ID and title only, so use
searching to find entries by their content. In Python,
truncate_text_after is also accepted by get_context() and list_contexts().
Deleting Context
To delete a context entry, use the deleteContext() method:
await squid.ai().knowledgeBase('banking-knowledgebase').deleteContext('credit-cards');
This method results in an error if an entry has not yet been created for the context ID provided.
Context Metadata
When adding or updating the context of an AI knowledge base, you can optionally provide context metadata. Metadata is an object where keys can have a type of string, number, or boolean. Adding metadata provides additional information about the context that can then be used when interacting with your agent. The following example shows adding a PDF as context and providing two key/value pairs as metadata:
const file = new File([contextBlob], 'CreditCardList.pdf', { type: 'application/pdf' });
await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.upsertContext(
{
contextId: 'credit-cards',
type: 'file',
metadata: { company: 'Bank of America', year: 2023 },
},
file
);
You can then use metadata when chatting with your AI agent, as shown in the filtering context with metadata section.
Defining a metadata schema
Declaring a metadata schema on the knowledge base makes metadata structured and self-maintaining. Pass field definitions in metadataFields when upserting the knowledge base:
- TypeScript
- Python
await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.upsertKnowledgeBase({
description: 'This Knowledge Base contains information on card data',
embeddingModel: 'text-embedding-3-small',
chatModel: 'gpt-6.2-sol',
metadataFields: [
{ name: 'author', dataType: 'string', required: true, description: 'The full name of the person who wrote the document.' },
{ name: 'publishedAt', dataType: 'date', required: false, description: 'The date the document was published.' },
{ name: 'category', dataType: 'string', required: false, description: 'The document category, for example report, memo, or guide.' },
],
});
await squid.ai().knowledge_base('banking-knowledgebase').upsert(
description='This Knowledge Base contains information on card data',
embedding_model='text-embedding-3-small',
chat_model='gpt-6.2-sol',
metadata_fields=[
{'name': 'author', 'dataType': 'string', 'required': True, 'description': 'The full name of the person who wrote the document.'},
{'name': 'publishedAt', 'dataType': 'date', 'required': False, 'description': 'The date the document was published.'},
{'name': 'category', 'dataType': 'string', 'required': False, 'description': 'The document category, for example report, memo, or guide.'},
],
)
Each field definition has:
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Letters, numbers, and underscores only. Reserved names such as text and contextId are rejected. |
dataType | 'string' | 'number' | 'boolean' | 'date' | Yes | Used for validation and filtering. date values are normalized to epoch milliseconds so range filters work. |
required | boolean | Yes | A hint surfaced to the agent alongside the field; it does not affect extraction or ingestion; a context still ingests even when a required value cannot be found. |
description | string | No | Used to extract the value from documents and to guide agents when they construct metadata filters. |
The TypeScript type also declares an 'array' data type; it is not yet supported and is rejected when the knowledge base schema is saved.
Declaring a schema enables three things: validation of supplied metadata (a value with the wrong type rejects only that context), automatic extraction of missing values, and agent-driven filtering.
Automatic metadata extraction
When a context is upserted without values for declared fields, Squid fills them in automatically, whether or not the fields are marked required. For file uploads, document properties are used first: fields named after well-known properties (title/docTitle, author/docAuthor, createdAt/docCreatedAt, modifiedAt/docModifiedAt, and docType) are filled from PDF and Office document properties, markdown front matter, and HTML metadata. An LLM pass over the document text handles all remaining fields, guided by each field's description. Values you supply always win and are never overwritten, with one exception: an empty string counts as no value and stays eligible for extraction. The names of extracted fields are recorded on the stored context in autoExtractedMetadataFields, and extraction is best-effort: a value that cannot be found stays absent without failing the upload.
To have Squid write field descriptions for you based on the values already stored in the knowledge base, call generateMetadataFieldDescriptions(). It returns the generated descriptions without saving them; review and save them onto the knowledge base with upsertKnowledgeBase():
const { fields } = await squid.ai().knowledgeBase('banking-knowledgebase').generateMetadataFieldDescriptions({ overwriteExisting: false });
Built-in metadata keys
Two metadata keys are maintained for you, without declaring them in the schema:
lastModifiedholds when the document last changed, stored as epoch milliseconds. You can supply it on upsert; when absent, Squid derives it from the document's own properties (PDF and Office files), and the SharePoint, OneDrive, Outlook, and Google Drive connectors stamp it from the source (Outlook uses the received time). It supports range filters such as{ lastModified: { $gt: Date.parse('2026-01-01') } }, and agents see it as a date.filenameis stamped by the SharePoint, OneDrive, and Google Drive connectors with the document's file name, so filters can target specific files.
Filtering Knowledge Base Context with Metadata
When you have added metadata to your context, you can use the contextMetadataFilterForKnowledgeBase chat option to instruct the AI agent to only consult specific contexts. Only contexts that meet the filter requirement will be used to respond to the client prompt.
The following example filters contexts to only include those with a metadata value of "company" that is equal to "Bank of America":
await squid
.ai()
.agent('banking-copilot')
.ask('Which Bank of America credit card is best for students?', {
contextMetadataFilterForKnowledgeBase: {
['banking-knowledgebase']: { company: { $eq: 'Bank of America' } },
},
});
The following metadata filters are supported:
| Filter | Description | Supported types |
|---|---|---|
| $eq | Matches vectors with metadata values that are equal to a specified value | number, string, boolean |
| $ne | Matches vectors with metadata values that are not equal to a specified value | number, string, boolean |
| $gt | Matches vectors with metadata values that are greater than a specified value | number |
| $gte | Matches vectors with metadata values that are greater than or equal to a specified value | number |
| $lt | Matches vectors with metadata values that are less than a specified value | number |
| $lte | Matches vectors with metadata values that are less than or equal to a specified value | number |
| $in | Matches vectors with metadata values that are in a specified array | string, number |
| $nin | Matches vectors with metadata values that are not in a specified array | string, number |
| $exists | Matches vectors with the specified metadata field | boolean |
Scoping to a folder with $underPath
$underPath matches a hierarchical string field, such as a document's folderPath, against a
subtree. It matches when the value is exactly the operand, or begins with the operand followed by a
/:
await squid
.ai()
.agent('banking-copilot')
.ask('What changed in the 2023 reports?', {
contextMetadataFilterForKnowledgeBase: {
['banking-knowledgebase']: { folderPath: { $underPath: 'reports/2023' } },
},
});
That filter admits reports/2023 and reports/2023/q1/deck, but never the sibling
reports/2023 drafts. The / separator supplies the segment boundary, which a raw prefix match
would not, so subtree scoping cannot leak into a folder that merely shares a prefix.
Details worth knowing:
- Leading and trailing slashes in the operand are ignored, so
reports/2023/andreports/2023address the same subtree. - An empty operand matches every context that has the field at all.
- Matching is case-sensitive, so
Reportsandreportsare distinct folders. folderPathis an ordinary metadata key rather than a reserved one. Write it with POSIX/separators and no leading or trailing slash, and use the empty string (not an absent value) for a file at the upload root.$underPathapplies to knowledge bases only. It is not accepted by metrics tag filters or matchmaking, which reject unknown operators.
A bare scalar value is shorthand for $eq, so { company: 'Bank of America' } and { company: { $eq: 'Bank of America' } } are equivalent. Filters can also be combined with $and and $or:
- TypeScript
- Python
await squid
.ai()
.agent('banking-copilot')
.ask('Summarize recent card reports', {
contextMetadataFilterForKnowledgeBase: {
['banking-knowledgebase']: {
$and: [{ category: 'report' }, { publishedAt: { $gt: Date.parse('2026-01-01') } }],
},
},
});
await squid.ai().agent('banking-copilot').ask(
'Summarize recent card reports',
options={
'contextMetadataFilterForKnowledgeBase': {
'banking-knowledgebase': {
# 1767225600000 is 2026-01-01 as epoch milliseconds
'$and': [{'category': 'report'}, {'publishedAt': {'$gt': 1767225600000}}],
},
},
},
)
Fields declared with dataType: 'date' are stored as epoch milliseconds, so pass numeric values (for example Date.parse('2026-01-01')) in range filters.
Agent-driven metadata filtering
When a knowledge base declares a metadata schema, connected agents can construct metadata filters on their own. The knowledge base search tool gains a filter parameter, and the model fills it in based on the user's question, guided by each field's description and a small set of sample values shown in the tool description.
Filters you set with contextMetadataFilterForKnowledgeBase always apply and are combined with the agent's filter using AND. The agent can narrow the allowed scope but can never widen it, so the app-level filter remains a security boundary.
Setting enableMetadataInspection: true on the connected knowledge base additionally gives the agent an inspection tool that enumerates and searches a field's stored values on demand, which helps it construct accurate filters. Values are sampled from the most recently updated documents, so the absence of a value in the sample does not prove it never occurs.
Respecting Source Permissions
Content indexed from a connector usually carries its own access rules. A SharePoint document, a Confluence page, or a Slack conversation is visible to some people in your organization and not to others. A knowledge base can honor those rules, so an agent grounds its answers only in the content the person chatting with it is allowed to see.
Two people who ask the same agent the same question receive answers drawn only from the documents each of them can open in the source system. Content a user cannot access is never retrieved, never reaches the model, and never appears in citations.
This is separate from metadata filtering, which narrows results by topic or attribute rather than by who is asking. The two combine, and permissions always apply.
Your application remains responsible for authenticating users. Squid applies the permissions of the authenticated user identity your application establishes. See Authentication to set this up.
Access Control for Your Own Content
For content your application ingests itself, turn on access control to restrict what each caller can retrieve. Every chunk then carries the access scopes of its context, each caller is resolved to the scopes they hold, and a search returns only chunks whose scopes intersect the caller's:
await this.squid
.ai()
.knowledgeBase('hr-handbook')
.upsertKnowledgeBase({
description: 'HR documents, visible per department',
embeddingModel: 'text-embedding-3-small',
metadataFields: [],
accessControl: {
mode: 'enforced',
// The backend function that resolves a caller's scopes, as 'ServiceName:functionName'.
scopeResolver: 'ExampleService:resolveHrScopes',
},
});
The scope resolver is an ordinary backend function. It runs once per search, receives the knowledge base ID and the caller's auth, and returns the scopes the caller holds:
import { ResolveKbScopesContext, SquidService } from '@squidcloud/backend';
export class ExampleService extends SquidService {
resolveHrScopes(context: ResolveKbScopesContext): Array<string> {
// `auth` is undefined for unauthenticated callers and API-key callers;
// returning [] limits them to content stamped as public.
if (!context.auth) return [];
const departments = context.auth.attributes['departments'];
return Array.isArray(departments) ? departments : [];
}
}
Attach scopes when ingesting, with scopes on each context, and update them later without re-ingesting:
await this.squid
.ai()
.knowledgeBase('hr-handbook')
.upsertContext({
type: 'text',
title: 'Engineering on-call guide',
text: onCallGuide,
contextId: 'eng-on-call',
scopes: ['engineering'], // only callers resolved to 'engineering' retrieve this
});
// Permissions changed at the source without the document changing:
await this.squid.ai().knowledgeBase('hr-handbook').setContextScopes('eng-on-call', ['engineering', 'security']);
Rules of the scope system:
- A context ingested with an empty
scopesarray is stamped public and visible to every caller. A context ingested with no scope information at all, including everything ingested before access control was enabled, is visible to no one until re-ingested or updated withsetContextScopes(). - Scope names starting with
__are reserved; a resolver may not return them and a caller may not store them. - A missing or undeployed resolver fails every search rather than falling back to an unfiltered one.
- Retrieval channels that cannot apply the scope filter are refused on an enforced knowledge base:
grep()and knowledge graph search. - Access control is how a knowledge base allows direct searches without the app API key, and it enables the audit log.
Connector-backed document security (SharePoint, Azure AI Search native ACLs) builds on the same machinery; see Connector access modes for the token-based variant.
Searching a Knowledge Base
Use the search() method to query a knowledge base directly and get back the matching chunks. A direct search requires the app API key, so call it from backend code; the exception is a knowledge base with enforced access control, which any caller may search because every result is scope-filtered to them:
- TypeScript
- Python
const chunks = await this.squid.ai().knowledgeBase('banking-knowledgebase').search({
prompt: 'Which credit cards have no annual fee?',
});
chunks = await squid.ai().knowledge_base('banking-knowledgebase').search(
'Which credit cards have no annual fee?',
)
A caller without the API key on a knowledge base that does not enforce access control gets UNAUTHORIZED. The same rule applies to downloadContext(contextId), which returns a download of a context's stored original file.
Two search options tune reranking: rerankProvider picks whose reranker orders the candidates ('cohere' or 'voyage', defaulting to the deployment's default), and rerankScoreThreshold (default 0.2) drops low-relevance chunks once at least 10 are kept.
Keyword search
Semantic (vector) search is weakest exactly where precision matters most: exact tokens such as identifiers, error codes, SKUs, and file names. The optional searchMode option selects how matches are found. How each mode behaves depends on the knowledge base's search backend: the vectorDbType ('mongoAtlas' or 'postgres') fixed when the knowledge base is created and readable via getKnowledgeBase().
| Mode | Description |
|---|---|
'hybrid' | The default on a knowledge base without a graph. On 'mongoAtlas', natively fuses semantic and keyword candidates; on 'postgres', falls back to semantic search. |
'vector' | Semantic similarity only. |
'keyword' | Embedding-free lexical search. On 'mongoAtlas', ranked full-text (BM25) matching, where a partial match still returns the best results. On 'postgres', an unranked filter: every whitespace-separated term must appear in a chunk as a literal, case-insensitive substring. |
'graph' | Multi-hop retrieval over an entity graph, fused with a hybrid search. Available only on 'mongoAtlas' knowledge bases with the graph enabled, where it is also the default. See Knowledge Graph Search. |
- TypeScript
- Python
const chunks = await squid.ai().knowledgeBase('banking-knowledgebase').search({
prompt: 'ERR_0000_4F2A',
searchMode: 'keyword',
});
chunks = await squid.ai().knowledge_base('banking-knowledgebase').search(
'ERR_0000_4F2A',
options={'searchMode': 'keyword'},
)
Connected agents choose a search mode on their own: the knowledge base search tool offers the modes the backend supports, and the agent switches to keyword search when a question targets exact tokens. Knowledge bases with a knowledge graph additionally offer a 'graph' mode, which is their default when searchMode is omitted.
Literal scan with grep
Every search mode above works on chunks, which are produced after ingestion has split and processed
the text. grep() scans the raw extracted text instead, before chunking, and returns each matching
line with the file it came from. Reach for it when you need characters rather than meaning, and when
the surrounding line matters, such as finding a specific SKU in a price list or a value in a
spreadsheet row.
const result = await squid
.ai()
.knowledgeBase('banking-knowledgebase')
.grep('ERR_0000_4F2A', {
// Scopes the scan to matching contexts before any text is read.
metadataFilter: { category: 'runbooks' },
maxMatches: 100,
});
for (const match of result.matches) {
// e.g. "CreditCardList.pdf, page 4, line 12: ..."
console.log(`${match.fileName}, ${match.part}, line ${match.lineNumber}: ${match.line}`);
}
Both options are optional:
| Option | Type | Description |
|---|---|---|
metadataFilter | object | Scopes the scan to the contexts whose metadata matches, using the same grammar as metadata filtering, including $and, $or, and $underPath. Applied before any text is matched. |
maxMatches | number | The maximum number of matches to return. Defaults to 50 and is capped at 200. |
Each match carries the contextId and fileName it came from, the part (a sheet or section title
when the extractor supplies one, otherwise page N), the 1-based lineNumber, the matching line,
and context, which is the matching line plus a small window of surrounding lines.
Two behaviors to keep in mind:
- The pattern is always literal. Regular expression metacharacters are escaped, so punctuation and symbols match themselves. The pattern may span lines.
- Matching is case-insensitive for ASCII letters only.
acmefindsACME, butcafédoes not findCAFÉ. Search the exact casing when the text is not ASCII.
An empty matches array proves the string is absent only when the response carries no limitation.
A scan that fell short of the requested scope sets limitation to one of the following, so check it
before concluding anything from an empty result:
| Limitation | Meaning |
|---|---|
timedOut | The scan hit its server-side deadline. Routine on large knowledge bases, and says nothing about whether the pattern occurs. |
noIndexedText | Nothing in scope has stored text. Contexts ingested before literal search existed stay here until re-ingested. |
filterMatchedNoContexts | metadataFilter admitted no contexts, so nothing was read. |
scopeTruncated | metadataFilter admitted more contexts than one scan can cover, so only some were searched. Narrow the filter. |
partsCapReached | The scan filled its per-call budget of matching pages or sheets, so more matching places exist. |
partialCoverage | Some contexts in scope have no stored text. unscannedContextCount reports how many. |
patternTooBroad | The pattern may occur in too many places to check them all within the time limit. Use a longer, more specific pattern. |
truncatedContent | Some in-scope text was cut at ingest and was never searchable. truncatedContentFileNames samples the affected files. |
coverageUnknown | The scan succeeded, but how much of the scope holds stored text could not be determined. |
The separate truncated flag means only that the returned list stopped at maxMatches and that more
matches exist.
Agents connected to a knowledge base get this scan as a grepKnowledgeBase tool, and they broadcast
status updates as they run it: grepKnowledgeBase
reports the title Searching Knowledge Base Text, distinct from the Accessing Knowledge Base title
of ranked retrieval.
grep() is available in the TypeScript client. There is no Python or REST equivalent.
Bulk Ingestion
upsertContexts() ingests inline and resolves once the contexts are searchable, which suits tens of
documents. For thousands, use bulk ingestion: a durable, asynchronous lane that runs contexts through
the AI provider's batch APIs.
The difference that matters is the return contract. bulkUpsertContexts() resolves as soon as the
request is staged, never when ingestion finishes, so you track the returned job separately.
Ingesting a directory with the CLI
The quickest path is the CLI, which walks a directory, batches the files, uploads them, and polls each job to completion:
squid kb-upload --dir ./docs --knowledgeBase banking-knowledgebase
| Option | Description |
|---|---|
--dir | Required. The local directory to walk recursively. |
--knowledgeBase | Required. The knowledge base to ingest into. |
--extensions | Comma-separated allow-list. Defaults to pdf, docx, txt, md, html, csv, xlsx, xls, xlsm, xlsb, pptx. |
--batchSize | Files staged per job. Defaults to 200, maximum 1000. |
--dryRun | Lists the files that would be uploaded and exits without contacting the server. |
--timeoutMinutes | How long to wait for each job before reporting it as still running server-side and moving on. Defaults to 120. |
--appId, --apiKey, --region, and --environmentId fall back to SQUID_APP_ID, SQUID_API_KEY,
SQUID_REGION, and SQUID_ENVIRONMENT_ID. Pressing Ctrl-C cancels the job that is in flight.
Staging contexts from code
Bulk ingestion requires an API key, so run it from backend code:
const { jobId, contextIds, duplicates } = await this.squid
.ai()
.knowledgeBase('banking-knowledgebase')
.bulkUpsertContexts(contexts, files, {
// How quickly the job must finish. 'economy' rides provider batches (cheapest,
// tails up to 24 hours), 'fast' runs inline within minutes at full price, and
// 'auto' (the default) decides from the job's size.
speed: 'auto',
});
Each staged context accepts the same per-context tuning as the synchronous path: options (the ragType and chunkOverlap it is chunked with; the overlap must stay below the 4,000-character chunk size), imageMinSizePixels, discardOriginalFile, metadata, scopes, and preferredExtractionMethod. One difference: imageExtractionModel is not accepted, because a job bills one fixed vision model for every image it describes. A context's extracted text is capped at 5 MB; larger documents fail with CONTENT_TOO_LARGE.
Some deployments have no bulk-ingestion models configured, and staging there fails with BULK_INGESTION_DISABLED. Call getBulkIngestionAvailability() first when you want to fall back to upsertContexts() without uploading files only to have them rejected.
contextIds is index-aligned with the contexts you passed. A context rejected as a content duplicate
still occupies its slot, so cross-reference duplicates by context ID to see what was actually
staged. A duplicate is content the knowledge base already holds, or content an earlier context in the
same call introduced.
duplicates covers text contexts and files whose bytes you passed to the call, since those are in
hand at staging time. A file staged by stagedObjectKey is the exception: its bytes are first read
by the deferred extraction pass, so its duplicate surfaces later in the job's per-file statuses as a
failed file carrying errorCode: 'DUPLICATE_CONTENT'. Treat that code as a skip rather than a
failure, because the knowledge base already holds the content.
Tracking a job
const kb = squid.ai().knowledgeBase('banking-knowledgebase');
// Poll for the job's current state.
const status = await kb.getBulkIngestionJob(jobId);
console.log(status.state, status.counts);
// Or subscribe to server-side updates.
kb.observeBulkIngestionJob(jobId).subscribe((update) => {
console.log(update.state, update.counts);
});
// Already-finalized contexts are kept when a job is cancelled.
await kb.cancelBulkIngestionJob(jobId);
observeBulkIngestionJob() completes when the job reaches completed, failed, or cancelled. A
terminal failed or cancelled state arrives as a normal emitted value rather than an error, so
handle it in your next callback. The observable only errors on a transport failure.
Beyond state and counts, the status reports what the job is doing right now: phase is
'extracting', 'awaiting-provider-batch', or 'indexing' while the job runs, transport says
whether the job rides provider batches ('batch', cheaper but with tails up to 24 hours) or runs
inline ('sync'), and providerBatches details each provider batch, so a long wait on a submitted
batch reads differently from a stall. The squid kb-upload progress line and the Console upload rows
surface the same phase.
The per-file statuses in files say which file finished and why a file failed. A failed file carries
an errorMessage, usually an errorCode, and retryable: false when the same bytes fail the same
way again. Most codes are shared with upsertContexts() (the sync-only codes
CONTENT_IN_FLIGHT, EMBEDDED_CHILDREN_NOT_RECONCILED, and EMBEDDING_FAILED do not appear here),
and two are bulk-specific; DUPLICATE_CONTENT appears on both paths:
errorCode | Meaning |
|---|---|
JOB_FULL | The job's request ceiling had no room left for this file, before any paid stage ran. Re-submit the file in a fresh job. |
EXTRACTION_ABANDONED | Every worker that took the file up died before finishing it. Terminal. |
DUPLICATE_CONTENT | A file staged by stagedObjectKey whose bytes the knowledge base already holds. A skip, not a failure. |
Two details to plan for:
- The observable is cold, so each subscription registers its own server-side subscription. Share it
(for example with RxJS
share()) when several consumers watch one job. - If the application or knowledge base is deleted while a job is in flight, the job record is purged
without a final update and the observable never completes. Bound it with RxJS
timeout()when that is possible. - A finished job stays readable for about 7 days, then its record is deleted and
getBulkIngestionJob()andobserveBulkIngestionJob()fail withBULK_INGESTION_JOB_NOT_FOUND. The per-file ledger outlives the job.
Uploading large file sets
Passing files directly to bulkUpsertContexts() sends them through Squid, which buffers the request
in memory and therefore caps a single call at 50 files and 256 MB in total. Beyond that, mint
presigned URLs and upload straight to storage, which is subject to neither cap:
const kb = this.squid.ai().knowledgeBase('banking-knowledgebase');
// At most 500 file names per call.
const { uploads } = await kb.createBulkUploadUrls(['statement-2026-01.pdf', 'statement-2026-02.pdf']);
for (const upload of uploads) {
await fetch(upload.uploadUrl, {
method: 'PUT',
body: fileBytesFor(upload.fileName),
// Required headers are empty on S3, but Azure Blob rejects the PUT without them.
headers: upload.requiredHeaders,
});
}
// Reference the staged objects instead of sending bytes through Squid.
const staged = uploads.map(upload => ({
type: 'file' as const,
contextId: upload.fileName,
stagedObjectKey: upload.stagedObjectKey,
}));
await kb.bulkUpsertContexts(staged);
Presigned URLs expire shortly after they are minted, so upload each wave promptly rather than minting all of them up front.
Checking a File's Ingestion Status
Every file and text context has a durable ingestion status, tracked by path independently of any one job, so it survives the 7-day job purge and covers synchronous upserts too:
const kb = this.squid.ai().knowledgeBase('banking-knowledgebase');
// One file, by `folderPath/filename` (or just the filename at the upload root).
const file = await kb.getFileStatus('statements/2026/january.pdf');
console.log(file.status); // 'completed', 'in_progress', 'failed', or 'no_record'
if (file.status === 'failed') console.log(file.errorCode, file.errorMessage);
// A folder subtree, a bare filename, or an exact path; failures are listed first.
const folder = await kb.getFolderStatus('statements/2026', 100);
console.log(folder.counts, folder.files.length);
'no_record' means the knowledge base has never seen that path. getFolderStatus() matches its
argument three ways and unions the results: as a folder subtree (segment-safe, like
$underPath), as a bare filename anywhere in the knowledge base, and, when it
contains a /, as an exact path. fileLimit defaults to 50. The Console offers the same lookup as a
status-search dialog on the knowledge base page.
Python: get_file_status(path) and get_folder_status(folder_path), with an optional file_limit that is keyword-only, so passing it positionally raises a TypeError.
Audit Logs
A knowledge base with enforced access control records every search: who searched, what for, and with which scopes. Reading the log requires the app API key:
const { entries, nextCursor } = await this.squid
.ai()
.knowledgeBase('hr-handbook')
.auditLogs({ limit: 100 }); // newest first; defaults to 100, up to 1000
for (const entry of entries) {
console.log(entry);
}
// Page with the cursor until it comes back undefined.
A knowledge base without enforced access control records no searches. For agent conversations, use the agent's own audit log instead.
Synthetic Documents for Development
In a dev environment, Squid can write fictional documents into a knowledge base, styled to continue
what it already holds, so you can develop retrieval features against realistic content:
const kb = this.squid.ai().knowledgeBase('banking-knowledgebase');
const jobId = await kb.startSyntheticDataGeneration({
prompt: 'Credit card policy documents for a retail bank',
size: 'M', // S, M, L or XL: 10, 25, 100 or 500 documents
});
const run = await kb.getSyntheticDataGeneration();
console.log(run?.status, run?.phase);
Outside a dev environment the call fails with a 403. cancelSyntheticDataGeneration() stops the
run and keeps the documents written so far. The Console offers the same under Generate Synthetic
Data on the knowledge base page.
Choosing an Embedding Model
listEmbeddingModels() returns the embedding models the application can create knowledge bases with,
including models served by embedding connectors:
const models = await squid.ai().listEmbeddingModels();
for (const model of models) {
// e.g. 'voyage-4-large', its display name, dimensions, and the connector serving it (if any)
console.log(model.modelId, model.displayName, model.dimensions, model.integrationId);
}
Pass { includeDeprecated: true } to also list retired models, each carrying replacedBy. Creating
a knowledge base with a retired model name creates it on the replacement instead. Python:
list_embedding_models(include_deprecated=False).
Best Practices
- Split large documents into focused knowledge bases by topic. This gives the agent better signal for choosing the right context.
- Add metadata to your contexts to enable filtering at query time, reducing noise in responses.