How to Build an AI agent
Build custom AI agents with persistent instructions, knowledge bases, connected tools, and multi-agent workflows using Squid's client SDK.
Why Build an AI Agent with Squid
Adding AI capabilities to your app typically means stitching together an LLM API, a vector database for context retrieval, tool-calling logic, conversation memory, and security rules. Each piece requires its own integration work.
Squid handles all of this in a unified platform. You define an agent with instructions and abilities, connect it to your data sources and tools, and interact with it through a single SDK. Squid manages prompt construction, context retrieval, memory, and orchestration so you can focus on the experience you want to create.
How it Works
Under the hood, agents use a Large Language Model (LLM) to generate answers to users' questions. When a user asks a question, the persistent instructions and most relevant context are passed to the LLM as part of the prompt, providing the user with a contextualized answer.
Squid lets you choose the LLM for your AI agent, allowing you to find the best fit for your use case. The following LLM providers are available out of the box:
You can also connect to additional providers by adding an AI connector. This allows you to use self-hosted models (e.g., Ollama, vLLM), AWS Bedrock models, or any other OpenAI-compatible endpoint.
Building an Agent
An agent represents a distinct personality or setup for your AI workflow. Each agent is like a different persona or use case, distinguished by its own set of instructions and abilities. This design enables customized responses from the AI according to the specific agent.
The following examples show how to create an agent using Squid's SDKs. If you are unfamiliar with developing using the Squid platform and SDKs, please read our documentation on fullstack development.
Upserting an Agent
To create or update an AI agent programmatically, use the upsert() method, specifying which agent ID should be created or updated:
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-6.2-sol',
},
isPublic: true,
});
When inserting an agent, pass an options object with a model field indicating the model the agent will use.
The isPublic parameter determines whether the chat functionality of the given agent can be accessed without setting up security rules.
Deleting an Agent
To delete an existing agent, use the delete() method:
await squid.ai().agent('banking-copilot').delete();
This function results in an error if no agent exists for the provided agent ID.
Updating the Model
To change the LLM model an agent uses, call updateModel():
await squid.ai().agent('banking-copilot').updateModel('claude-sonnet-5-5');
The model can be a vendor model name (e.g. 'gpt-5.6-sol', 'claude-sonnet-5-5', 'gemini-3.8-flash') or an integration-based model for additional providers like Ollama, AWS Bedrock, or any OpenAI-compatible endpoint:
await squid.ai().agent('banking-copilot').updateModel({
integrationId: 'my-ollama',
model: 'llama3',
});
You can also select a CLI agent model such as 'claude-code' or 'codex' to run long-running, tool-driven agentic asks.
You can also override the model per-request when calling ask() or chat() using the model option. See Ask Options for details.
Falling Back to a Backup Model
When a model provider is unavailable, the request fails. Set backupModel to have Squid retry that request on a second model instead:
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-5.6-sol',
backupModel: 'claude-sonnet-5-5',
},
});
backupModel accepts the same values as model, and can also be set per-request through Ask Options. Leave it unset to keep a provider outage surfacing as an error.
When the backup is used
The backup covers provider-side unavailability, such as a rate limit or a capacity outage, and one content case: a turn the primary model's safety classifier declines with no text at all falls back to the backup instead of failing with AI_RESPONSE_FILTERED. Squid does not fall back when:
- The request failed on its own merits, such as an invalid prompt, a rejected response format, or an exhausted Squid quota.
- The request is not the conversation's first one.
- The request already produced output or ran a tool.
Fallback also applies only to models Squid calls through its own provider SDKs: the vendor models and the openai_compatible, Bedrock, and Vertex connectors. A model you serve yourself from backend code reports failures as plain errors carrying no provider status, so a failure on one is never diagnosed as an outage. The backup is skipped silently when its API key cannot be resolved, when it resolves to the same model as the primary, or when either model is a CLI agent model.
A conversation that falls back stays on the backup
Once a conversation falls back, it is pinned to the backup model for the rest of its life, so an outage costs the primary's retry budget once rather than once per turn and the model does not change mid-dialogue. The pin outlives the option that created it: changing or removing backupModel, changing the agent's model, and the primary recovering all leave a pinned conversation where it is. If a pinned model later stops resolving, the request fails rather than moving the conversation.
Pinning needs somewhere to be recorded, so it requires Squid-managed memory. Without memory, every request is a first request and each one falls back independently.
When a provider throttles and the retry budget runs out with no backup to serve the request, the caller receives HTTP 429 with a Retry-After header rather than a generic failure, so clients can wait and retry.
Routing Between Models
Instead of one model, model can name a ladder of models and let a small routing model pick which one answers each request, so simple questions run on a cheap model and demanding ones on a capable one:
const result = await squid.ai().agent('banking-copilot').askWithResult('What are your hours?', {
model: {
// The ladder, cheapest first: two or three steps, each a model name
// or a model with its own reasoning effort.
models: ['gemini-3.8-flash', { model: 'gpt-6.2-sol', reasoningEffort: 'high' }],
// The model that rates how demanding the question is.
routingModel: 'gemini-3.8-flash',
},
});
console.log(result.responseString);
// Which model answered, the rating (simple/moderate/complex), and the routing call's cost.
console.log(result.routing?.model, result.routing?.level, result.routing?.costUsd);
How routing behaves:
- Omitting
modelsuses the platform's fast, medium, and capable chat models as the ladder, at low, default, and high effort. An explicit ladder takes two or three distinct steps. instructions(up to 2,000 characters) replaces the default rating rule with your own, in plain language.- The response's
routingfield reports the chosenmodel, itsreasoningEffort, theleveland one-linereason, and the routing call's token counts and best-effortcostUsd. On a streamedchat(), pass ajobIdand read the same field from the job's result. - Routing is a per-request option only: storing a routing
modelon the agent withupsert()is rejected (MODEL_ROUTING_NOT_STORABLE). It works withask(),askAsync(),askWithResult(), andchat()in TypeScript, and withask()andask_with_annotations()in Python. Voice asks and transcription reject a routingmodel. - Requests that use routing must run without conversation memory and without
fileUrlsorfileIds, and when the ask uses AI functions, every ladder model must support them. - If the routing call fails, the request fails; there is no silent fallback.
backupModeland a request-levelreasoningEffortapply to the chosen ladder model.
Consulting an Advisor Model
advisor gives the answering model a consultAdvisor tool that asks a stronger model for help mid-turn, while the turn itself stays on the cheaper model:
await squid
.ai()
.agent('banking-copilot')
.ask('Reconcile these two statements', {
advisor: {
model: 'claude-opus-5-5', // the model that gives the advice
maxConsultations: 3, // per turn, 1 to 10; defaults to 3
instructions: 'Double-check arithmetic and flag unsupported assumptions.',
},
});
The advisor sees only what the answering model passes it, unless shareFunctions: true also lets it call the turn's functions (including ones with side effects, at its own cost). Models rarely consult an advisor unprompted, so tell the agent when to use it in its instructions. Consultations surface as Consulting Advisor and Advisor Result status updates, and the Console exposes the same settings in the agent's Settings tab.
Validating Answers
validation has an independent judge model check each answer before it is returned, and lets the agent retry when the judge rejects it:
const result = await squid.ai().agent('banking-copilot').askWithResult('Summarize the Q3 dispute volume', {
validation: {
model: 'gpt-6.2-sol', // the judge; defaults to the model that produced the answer
instructions: 'Reject answers that cite no specific numbers.',
maxAttempts: 2, // attempts including the first answer; 1 to 5
},
});
if (result.validation && !result.validation.passed) {
console.log(result.validation.summary, result.validation.issues);
}
An empty object (validation: {}) uses the defaults. Validation works with non-CLI models only. Conversation memory keeps an answer only when it passes, so a rejected answer does not poison later turns. The returned validation verdict carries passed, a summary, and the issues found; passed: false also covers validation that could not complete. The Console exposes the same as an Answer validation toggle with a judge-model picker in the agent's settings.
askWithResult() is the ask variant that returns the full result object (responseString, annotations, routing, validation) instead of the answer string alone.
A first request does not fall back when doing so would lose its fileIds, because answering from a model that never saw the attachments is worse than reporting the outage. Where neither model reads file ids, the ids are inert and the fallback proceeds. A conversation that is already pinned keeps running on its model either way.
Giving the backup its own settings
Pass a BackupModelOptions object instead of a bare model name when the backup needs sampling settings of its own:
await squid.ai().agent('banking-copilot').upsert({
options: {
model: 'gpt-5.6-sol',
temperature: 0.2,
backupModel: {
model: 'claude-sonnet-5-5',
temperature: 0.4,
maxOutputTokens: 4096,
},
},
});
The object accepts model, temperature, reasoningEffort, maxTokens, maxOutputTokens, and verbosity.
On a turn the backup serves, those sampling settings are read from backupModel and nowhere else. A value left unset there takes the backup model's own default even when the agent's configuration or the request itself sets one, and this holds for every turn of a pinned conversation rather than only the turn that fell back. Everything else, including instructions, functions, knowledge bases, connected agents, response format, and memory, always comes from the primary configuration.
Listing Agents and Resources
The squid.ai() client exposes discovery methods for everything defined in your app:
| TypeScript | Python | Returns |
|---|---|---|
listAgents() | list_agents() | All agents with their configuration |
listKnowledgeBases() | list_knowledge_bases() | All knowledge bases |
listChatModels() | list_chat_models() | Available chat models. Pass includeDeprecated: true to include deprecated vendor models. |
listFunctions() | list_functions() | Registered AI functions |
- TypeScript
- Python
const agents = await squid.ai().listAgents();
const models = await squid.ai().listChatModels({ includeDeprecated: false });
agents = await squid.ai().list_agents()
models = await squid.ai().list_chat_models(include_deprecated=False)
Each method returns an array of records with the following contents:
- Agents (
AiAgent):id,createdAt,updatedAt,description,isPublic,auditLog, andoptions(the agent's full configuration, including its model and connected knowledge bases, integrations, and functions). - Knowledge bases (
AiKnowledgeBase):id,name,description,embeddingModel,chatModel,metadataFields,createdAt, andupdatedAt. Knowledge bases created by connector syncs may carry additional sync bookkeeping fields. - Chat models (
ModelIdSpec):modelId(the string to pass as a model selection),displayName,description, andsource('vendor','connector', or'custom'). Integration-based models includeintegrationId, and deprecated models includereplacedBynaming the active model that calls are routed to. - AI functions (
AiFunctionMetadata):serviceFunction(ServiceName:functionName),description, andparams(each withname,type,description, andrequired). Connector-provided functions carryattributes.integrationType, and entries flaggedinternalare not meant for direct use.
Setting the Agent Description
To set or update a human-readable description for the agent, use the setAgentDescription() method. This updates only the description without affecting other agent configuration:
await squid
.ai()
.agent('banking-copilot')
.setAgentDescription('Assists customer support staff with banking and finance questions');
Alternatively, you can use upsert() to set the description along with all other agent values in a single call. Note that upsert() replaces the entire agent configuration, so any fields not included will be cleared.
Instructions
Instructions set the rules for how the agent responds to prompts and answers questions. They should be direct and simple, and explain the purpose of the agent. Instructions are supplied as a block of text.
Adding Instructions
To add or edit instructions for an AI agent, use the updateInstructions() method, passing the instruction data as a string.
const instruction = 'You are a helpful copilot that assists customer support staff by providing answers to their questions about banking and finance products.';
await squid.ai().agent('banking-copilot').updateInstructions(instruction);
Connected Knowledge Bases
Knowledge bases store the searchable context an agent draws on when answering questions. To create a knowledge base and manage its context and metadata, see the Knowledge Bases documentation.
Connect a Knowledge Base to an Agent
Use setAgentOptionInPath() to give an agent access to one or more knowledge bases without affecting other agent configuration. The description tells the agent when to consult each knowledge base:
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
},
]);
To disconnect all knowledge bases, pass an empty array:
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', []);
You can also use upsert() to set connected knowledge bases along with all other agent values in a single call. Note that upsert() replaces the entire agent configuration, so any fields not included will be cleared.
Each connected knowledge base entry supports the following fields:
| Field | Type | Required | Description |
|---|---|---|---|
knowledgeBaseId | string | Yes | The knowledge base to connect |
description | string | Yes | Tells the agent when to consult this knowledge base |
includeMetadata | boolean | No | Include document metadata with search results provided to the agent. When omitted, falls back to the deprecated ask-level includeMetadata option, which defaults to true; set to false to exclude metadata. |
enableMetadataInspection | boolean | No | Give the agent a tool to enumerate and search this knowledge base's metadata field values. Defaults to false. See agent-driven metadata filtering. |
access | AiIntegrationAccess | No | For a knowledge base whose external source trims documents by the caller's token: whose token searches run with. See Connector access modes. |
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
includeMetadata: true,
enableMetadataInspection: true,
},
]);
The ask-level includeMetadata option still works but is deprecated in favor of the per-knowledge-base flag.
Search Modes and Spreadsheets
The knowledge base search tool lets the agent pick a retrieval mode per query, choosing 'vector' (semantic), 'keyword' (best for exact tokens such as IDs and error codes), or 'hybrid', depending on what the knowledge base's backend supports. See Keyword search.
When a connected knowledge base contains spreadsheet files, the agent also gets a querySpreadsheetsWithAi tool that computes exact answers (counts, sums, lookups, comparisons across files) by running Python against the uploaded files instead of relying on retrieved summaries. See Spreadsheet Files.
Interacting with your Agent
Once an agent has been created, you're ready to start asking questions or giving prompts.
Getting a Full Response with ask()
Use the ask() method to send a prompt and receive the complete response as a string:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?');
Getting Responses with Annotations
Use askWithAnnotations() to receive the response along with any file annotations (e.g., generated images or documents):
const { responseString, annotations } = await squid
.ai()
.agent('banking-copilot')
.askWithAnnotations('Generate a comparison chart of our credit cards');
Streaming Responses with chat()
Use the chat() method to stream responses token by token. This returns an RxJS Observable<string> that emits the accumulated response as each token arrives, which is ideal for displaying real-time responses in a UI:
import { Subscription } from 'rxjs';
const stream = squid
.ai()
.agent('banking-copilot')
.chat('Which credit card is best for students?');
const subscription: Subscription = stream.subscribe({
next: (accumulatedResponse) => {
// Each emission contains the full response so far
console.log(accumulatedResponse);
},
complete: () => {
console.log('Response complete');
},
error: (err) => {
console.error('Error:', err);
},
});
The chat() method accepts the same options as ask() (except voiceOptions), plus an additional smoothTyping option (defaults to true) that adds a slight delay between tokens for a natural typing effect.
Ask Options
Both ask() and chat() accept an optional options parameter to configure the request. To view a full list of available options and their default values, refer to the API reference documentation.
await squid.ai().agent('banking-copilot').ask('Which credit card is best for students?', {
maxOutputTokens: 4096,
temperature: 0.7,
model: 'claude-sonnet-5-5',
});
Memory and Chat History
By default, agents remember previous messages within a session. Use memoryOptions to control this behavior:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What did I ask earlier?', {
memoryOptions: {
memoryMode: 'read-write', // 'none' | 'read-only' | 'read-write'
memoryId: 'user-123-session', // Unique ID for this conversation
expirationMinutes: 60, // How long to keep the history
},
});
'none': No history is used. Each prompt is answered independently.'read-only': The agent can reference past messages but will not save new ones.'read-write': The agent reads and writes to history (default behavior).
The memoryId identifies a conversation. Using the same memoryId across requests continues the same conversation. Treat memory IDs with the same security as access tokens since they grant access to the chat history.
To retrieve past messages for a given conversation, use getChatHistory():
const messages = await squid
.ai()
.agent('banking-copilot')
.getChatHistory('user-123-session');
Response Format
Control the format of the agent's response using responseFormat:
// Get a JSON response
const json = await squid
.ai()
.agent('banking-copilot')
.ask('List our credit cards with their fees', {
responseFormat: 'json_object',
});
// Get a response that strictly conforms to a JSON schema
const structured = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze the sentiment of this review', {
model: 'claude-sonnet-5-5',
responseFormat: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
confidence: { type: 'number' },
},
required: ['sentiment', 'confidence'],
},
},
});
Available formats:
'text'(default): Plain text response.'json_object': The model attempts to return valid JSON.{ type: 'json_schema', schema: ... }: Structured output that guarantees the response conforms to the provided JSON schema. Supported by the vendor chat models (Anthropic, OpenAI, Gemini, and Grok): the schema is sent to the model's provider, which constrains decoding to it, so the response matches the schema exactly and does not need to be validated again.
A schema the provider rejects comes back as a 400 carrying the provider's own diagnostic. Models whose protocol cannot carry a schema at all reject the request with STRUCTURED_OUTPUT_NOT_SUPPORTED rather than answering without the requested shape. That applies to the CLI agent models and to models served through a custom @llmService; use 'json_object' and describe the shape in the prompt for those.
For an integration-based model, whether a schema is honored depends on the provider behind the integration, so fall back to 'json_object' when you need one answer that works across providers.
Including Files in the Prompt
Pass images or documents as part of the prompt using fileUrls:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What does this document say?', {
fileUrls: [
{
id: 'doc-1',
type: 'document',
purpose: 'context',
url: 'https://example.com/statement.pdf',
description: 'Customer bank statement',
},
],
});
Each file URL requires an id (unique per request), a type ('image' or 'document'), and a purpose:
'context': The file is included directly in the prompt for the AI to reference.'tools': The file is returned as part of a tool/function call result.
You can also set fileName (optional): it gives the model a name to reference the file by, and supplies the file extension when the URL path lacks one.
Spreadsheet files (.csv, .tsv, .xlsx, .xlsm, .xls, and .xlsb) get special handling: for each attached spreadsheet, the agent receives a tool that answers questions about it by running Python against the file, so lookups and aggregations are computed from actual cell values. Spreadsheets are recognized by file extension, taken from fileName or, when it is absent, from the URL path with any query string ignored, so a signed URL ending in .xlsx?signature=... is detected without help. Set fileName when the URL path itself carries no extension (for example, an opaque download endpoint):
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What was the total revenue in Q2?', {
fileUrls: [
{
id: 'sales-1',
type: 'document',
purpose: 'context',
url: downloadUrl, // path has no file extension
fileName: 'sales.xlsx',
},
],
});
Overriding the Model Per-Request
Override the agent's default model for a single request:
const response = await squid.ai().agent('banking-copilot').ask('Summarize this data', {
model: 'gpt-6.2-sol',
});
Additional Options
| Option | Type | Default | Description |
|---|---|---|---|
maxTokens | number | Model max | Maximum input tokens Squid can send to the model |
maxOutputTokens | number | - | Maximum tokens the model should generate |
temperature | number | 0.5 | Sampling temperature (0-1) |
timeoutMs | number | 240000 | Request timeout in milliseconds |
instructions | string | - | Additional instructions appended to the agent's default instructions |
guardrails | object | - | Override guardrail settings per-request |
pii | object | - | Not overridable per-request. Prompt privacy is read from the stored agent and a value passed here is ignored |
backupModel | string or object | - | Model to retry on when the primary provider is unavailable. See Falling Back to a Backup Model |
disableContext | boolean | false | Skip knowledge base context for this request |
citation | boolean | false | Cite the sources behind the answer. See Grounding and Source References |
includeReference | boolean | false | Deprecated in favor of citation; renders the legacy Quote/Source format on the legacy upfront-RAG path only |
reasoningEffort | string | - | 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', or 'ultra', where the model supports the level. The Console's Reasoning Effort select shows each model's levels |
useCodeInterpreter | string | 'none' | 'llm' lets the model run Python in Squid's sandbox through a tool call. See the note below |
validation | object | - | Have a judge model check the answer. See Validating Answers |
session | object | - | The session the request runs in; every AI function it calls receives it |
advisor | object | - | Give the model a tool to consult a stronger model. See Consulting an Advisor Model |
executionPlanOptions | object | - | Enable the agent to plan before acting |
Code interpreter
useCodeInterpreter: 'llm' lets the model run Python in Squid's sandbox through a tool call (the same executePythonCode function the built-in AI functions provide), so it works with any model that supports tool calling. If the backend bundle lacks executePythonCode, the request fails with a 412 CODE_INTERPRETER_UNAVAILABLE. With the interpreter on, fileIds are mounted into the sandbox for the code to read rather than attached to the conversation. Uploaded AI files expire after 1 day by default.
Options on public agents
On a public agent (isPublic: true), per-request options that could widen what the agent can do are honored only from callers using the app API key. For other callers, the stored agent's values apply and the request's functions, connectedIntegrations, connectedAgents, agentContext, and useCodeInterpreter are ignored. The knowledge base options connectedKnowledgeBases, contextMetadataFilter, and contextMetadataFilterForKnowledgeBase can only narrow the stored scope: request filters are ANDed with the stored ones.
Filtering 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' } },
},
});
For the full list of supported filter operators, combining filters with $and and $or, and how agents construct filters on their own, see Filtering Knowledge Base Context with Metadata.
AI Functions
Squid AI Agents can handle specific use cases and create more consistent responses using AI functions.
Adding Functions to an Agent
You can attach AI functions to an agent using setAgentOptionInPath(), which updates only the function list without affecting other agent configuration:
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('functions', ['getCreditLimit']);
To update the function list, call setAgentOptionInPath() again with the new set of functions. Passing an empty array removes all functions. You can also use upsert() to set functions along with all other agent values in a single call, but note that upsert() replaces the entire agent configuration.
Passing Functions at Ask Time
Alternatively, pass AI function names per-request using the functions option. This overrides the agent's stored function list for that request:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What is my current credit limit?', {
functions: ['getCreditLimit', 'getAccountBalance'],
});
To learn more about AI functions, view the documentation. To see an example application that uses AI functions, check out this AI agent tutorial.
Connected Agents
Agents can delegate tasks to other agents, enabling multi-agent workflows. A connected agent appears as a callable tool that the parent agent can invoke when it determines the sub-agent is best suited to handle a specific part of the user's request.
Configuring Connected Agents
Use updateConnectedAgents() to set the list of agents connected to this agent. The description tells the parent agent when to delegate to each connected agent:
await squid
.ai()
.agent('banking-copilot')
.updateConnectedAgents([
{
agentId: 'fraud-detection-agent',
description: 'Call this agent when the user asks about suspicious transactions or potential fraud',
},
]);
To disconnect all agents, pass an empty array:
await squid.ai().agent('banking-copilot').updateConnectedAgents([]);
Passing Connected Agents at Ask Time
You can also specify connected agents per-request, which overrides the stored configuration:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Is this transaction suspicious?', {
connectedAgents: [
{
agentId: 'fraud-detection-agent',
description: 'Call this agent for fraud analysis',
},
{
agentId: 'compliance-agent',
description: 'Call this agent for regulatory compliance checks',
},
],
});
By default, nested agent calls can recurse up to 5 levels deep. You can adjust this using the quotas option:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze this portfolio', {
quotas: { maxAiCallStackSize: 3 },
});
Connected Integrations
Agents can connect to your data sources and external services, allowing them to query databases, call APIs, and interact with SaaS tools as part of answering a prompt.
Configuring Connected Integrations
Use setAgentOptionInPath() to give the agent access to connectors without affecting other agent configuration:
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedIntegrations', [
{
integrationId: 'my-postgres',
integrationType: 'postgres',
description: 'Use this database to look up customer account information',
},
]);
The description helps the agent understand when to use this integration. The integrationType must match the type of connector configured in the Squid Console.
For connectors that support it, a connection can also set access to choose whose identity its tools run with: the signed-in user's own permissions, or the connector's stored credentials. See Connector access modes.
To disconnect all integrations, call setAgentOptionInPath() with an empty array. You can also use upsert() to set connected integrations along with all other agent values in a single call, but note that upsert() replaces the entire agent configuration.
Passing Connected Integrations at Ask Time
Like connected agents, integrations can also be specified per-request:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What are my recent transactions?', {
connectedIntegrations: [
{
integrationId: 'my-postgres',
integrationType: 'postgres',
description: 'Customer transaction database',
},
],
});
Connected Ontologies and Glossaries
Ontologies tell an agent how your tables relate and which business entities they hold. Glossaries tell it what your business terms mean. Lineages tell it which columns feed which. To create them, see the Semantic Layer documentation.
Connect an Ontology or a Global Glossary
Only your app's API key can attach an ontology or a global glossary to an agent, so do it from backend code. addOntology() and addGlossary() add one id at a time, and removeOntology() and removeGlossary() remove one, without affecting other agent configuration:
import { SquidService, executable } from '@squidcloud/backend';
export class AgentSemanticLayerService extends SquidService {
@executable()
async connectSemanticLayer(ontologyId: string, glossaryId: string): Promise<void> {
const agent = this.squid.ai().agent('sales-copilot');
await agent.addOntology(ontologyId);
await agent.addGlossary(glossaryId);
}
@executable()
async disconnectSemanticLayer(ontologyId: string, glossaryId: string): Promise<void> {
const agent = this.squid.ai().agent('sales-copilot');
await agent.removeOntology(ontologyId);
await agent.removeGlossary(glossaryId);
}
}
The ids are stored in the agent's ontologyIds and glossaryIds options. You can also set them with upsert(), which replaces the entire agent configuration. These two options are read only from the agent's stored configuration: values passed at ask time are ignored.
Connect a Lineage
A lineage is attached the same way, with your app's API key, from backend code. addLineage() adds one id and removeLineage() removes one, without affecting other agent configuration:
import { SquidService, executable } from '@squidcloud/backend';
export class AgentLineageService extends SquidService {
@executable()
async connectLineage(lineageId: string): Promise<void> {
await this.squid.ai().agent('sales-copilot').addLineage(lineageId);
}
@executable()
async disconnectLineage(lineageId: string): Promise<void> {
await this.squid.ai().agent('sales-copilot').removeLineage(lineageId);
}
}
The ids are stored in the agent's lineageIds option, which you can also set with upsert(). Like ontologyIds and glossaryIds, it is read only from the agent's stored configuration: a value passed at ask time is ignored. An agent holds at most 10 lineages. Removing a lineage from an agent keeps the lineage itself.
What the Agent Receives
- Ontologies. The agent gets the relationships, business entities and properties of each attached ontology in its instructions, but only for the databases the agent has as connected integrations, and only for the collections each connection allows. Its database queries follow those relationships, and it gets a
followRelationshiptool that reads the rows on the other side of a relationship. Several ontologies share one size budget in the instructions. - Database glossaries. A connected database's glossary terms appear in the agent's instructions by name, synonyms and the first sentence of their description. To leave them out, set
includeGlossary: falsein the connection'soptions:
await squid
.ai()
.agent('sales-copilot')
.setAgentOptionInPath('connectedIntegrations', [
{
integrationId: 'sales_db',
integrationType: 'postgres',
description: 'Customers, orders and products',
options: { includeGlossary: false },
},
]);
- Global glossaries. The terms of each glossary in
glossaryIdsappear in the agent's instructions. A glossary too large for the instructions is listed by name, and the agent gets alookupGlossaryTermtool that finds a term by its name or a synonym. - Lineages. The agent's instructions list the mappings of each attached lineage as
source column -> target column, with the calculation when the target is calculated, under the lineage's name and the start of its description. The agent uses them to say where a value comes from and what a change to a column affects. They are guidance: they limit nothing the agent may query, and the agent gets no extra tool.- Trimmed to the agent's connections. A mapping is shown only when both of its columns are in a database the agent has as a connected integration, in a collection the connection allows, and not hidden in the schema. An agent with none of the lineage's databases connected is told nothing.
- Sized to fit. All the lineages of an agent share at most 5% of the model's input, and at most 8,000 characters, strongest mappings first. The instructions say how many mappings did not fit. An agent reads the 300 strongest mappings of each lineage, so an agent connected to a few tables of a larger lineage can miss mappings past them.
- Kept current. A saved change to a lineage reaches its agents without attaching it again. An agent whose lineage was deleted keeps answering, without it.
Errors
| Error | Cause | Solution |
|---|---|---|
ATTACHING_REQUIRES_APP_API_KEY | An agent API key or a user tried to change ontologyIds, glossaryIds or lineageIds | Make the change from backend code, with your app's API key |
GLOSSARY_NOT_FOUND | The glossary id does not exist | Check the id with squid.ai().glossary().listGlossaries() |
GLOSSARY_NOT_GLOBAL | The glossary is a database glossary | Connect its database instead: its terms come with it |
LINEAGE_NOT_FOUND | The lineage id does not exist | Check the id with squid.ai().lineage().listLineages() |
TOO_MANY_LINEAGES | The agent would hold more than 10 lineages | Remove one with removeLineage() first |
An ontology id is not checked when you attach it. An agent skips an ontology that does not exist when it answers, so check the id with squid.ai().ontology().listOntologies().
Execution Planning
For complex tasks involving multiple tools, connected agents, or integrations, you can enable execution planning. When enabled, the agent first creates a plan of what actions to take before executing them:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Compare our credit card offerings with competitor rates', {
executionPlanOptions: {
enabled: true,
reasoningEffort: 'high', // 'minimal' | 'low' | 'medium' | 'high'
allowClarificationQuestions: true, // Let the agent ask follow-up questions
},
});
You can optionally specify a different model for the planning step using the model field within executionPlanOptions.
Observing Status Updates
When an agent processes a complex request involving tool calls, connected agents, or integrations, you can observe real-time status updates via WebSocket:
const statusUpdates = squid.ai().agent('banking-copilot').observeStatusUpdates();
statusUpdates.subscribe({
next: (status) => {
console.log(`[${status.title}] ${status.body}`);
},
});
The returned Observable emits AiStatusMessage objects with title and body fields describing each step the agent takes.
Titles name the kind of step the agent is taking. For example, an ordinary knowledge base search reports Accessing Knowledge Base, while navigating a knowledge graph reports Querying Knowledge Base Graph and a literal text scan reports Searching Knowledge Base Text, so a chat UI can render each of them as its own step.
observeStatusUpdates() also accepts an optional job ID: observeStatusUpdates(jobId) only emits updates for that specific request, which is useful when tracking a single long-running ask such as a CLI agent model run. Without an argument, it emits all status updates for the agent.
Grounding and Source References
Squid AI agents give grounded answers: responses drawn from the records in the agent's connected knowledge bases rather than from the model's built-in knowledge alone. To make that grounding visible, set citation: true on ask() or chat() to have the agent cite the sources behind its statements, so users can verify a claim against its source:
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?', {
citation: true,
});
By default a citation names its source. To also link each citation to a download of the original file, set allowSourceDownloads: true in the agent's stored options; the links are presigned and expire after 1 hour. The option is honored only from the stored agent, never per-request, so callers of a public agent can never enable downloads. The Console exposes it as Allow source downloads in citations in the agent's settings, and the Studio's Test chat cites by default.
Two caveats: citation is rejected together with a structured responseFormat (CITATION_UNSUPPORTED_FOR_STRUCTURED_RESPONSE_FORMAT), and the older includeReference option is deprecated; citation takes precedence when both are set.
When using the Chat Widget, set the include-reference attribute to show citations in agent responses.
References only ever cite content the asking user is allowed to see. When a knowledge base respects source permissions, content a user cannot access is never retrieved, never reaches the model, and never appears in citations.
Agent Revisions
Every change to an agent's configuration automatically records a revision. Creating the agent records a created revision, each update (including upsert(), updateModel(), updateInstructions(), and setAgentOptionInPath()) records updated, and deleting the agent records a final deleted revision that preserves its last state. No setup is required.
Listing Revisions
Use listRevisions() to retrieve an agent's full history, sorted newest first:
- TypeScript
- Python
const { revisions } = await squid.ai().agent('banking-copilot').listRevisions();
console.log(revisions[0].revisionNumber, revisions[0].action);
revisions = await squid.ai().agent('banking-copilot').list_revisions()
print(revisions[0]['revisionNumber'], revisions[0]['action'])
Each revision contains:
| Field | Type | Description |
|---|---|---|
agentId | string | The agent this revision belongs to |
revisionNumber | number | Sequential number, incremented on each change |
action | 'created' | 'updated' | 'deleted' | The change that triggered the revision |
createdAt | Date | When the revision was recorded |
agentSnapshot | AiAgent | The full agent configuration at the time of the revision |
There is no separate change description; to see what changed, compare consecutive snapshots (the Squid Console does this for you).
Restoring and Deleting Revisions
Restore the agent to a previous revision with restoreRevision():
- TypeScript
- Python
await squid.ai().agent('banking-copilot').restoreRevision(3);
await squid.ai().agent('banking-copilot').restore_revision(3)
Restoring is non-destructive: the current state is first saved as a new revision, then the agent's configuration is replaced with the snapshot. History only grows, so a restore can itself be undone. A deleted revision cannot be restored.
To permanently remove a single revision, use deleteRevision():
- TypeScript
- Python
await squid.ai().agent('banking-copilot').deleteRevision(3);
await squid.ai().agent('banking-copilot').delete_revision(3)
Full method signatures are in the TypeScript and Python reference docs.
You can also browse revisions visually: the agent's page in the Squid Console has a Revisions tab showing what changed in each revision, with restore and delete actions.
Automations
Agents can run by themselves: a stored prompt runs on a cron schedule, or whenever an event is emitted with squid.events().emit(). See Agent Automations.
Audit Log
Separate from configuration revisions, each agent keeps a runtime audit log of its invocations: the user prompt, tool and integration calls, knowledge base searches, the final response, and token usage.
Logging is controlled by the agent's auditLog field, which is enabled by default for new agents. Toggle it in the console or by including it in upsert():
- TypeScript
- Python
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: { model: 'gpt-6.2-sol' },
isPublic: true,
auditLog: false,
});
await squid.ai().agent('banking-copilot').upsert(
is_public=True,
audit_log=False,
options={'model': 'gpt-6.2-sol'},
)
Read the log in the Audit Log tab of the agent's page in the Squid Console, or from backend code with auditLogs(), which requires the app API key:
// Newest first. Filter by type, userId, jobId, automationId, or a time range.
const { entries, nextCursor } = await this.squid
.ai()
.agent('banking-copilot')
.auditLogs({ limit: 50, where: { userId: 'user_123' } });
Runs started by an automation carry automation tags on their entries and can be filtered with where: { automationId }.
When the agent is exposed as an MCP server with OAuth, the validated caller becomes the request's user: entries carry a userName tag (from the token's preferred_username, upn, or email claim), and each authorized MCP request and each rejected credential writes an mcp_auth entry.
Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
| Agent not found | Calling delete(), get(), or other methods on a non-existent agent ID | Verify the agent ID exists by calling get() first, or use upsert() to ensure the agent is created |
| Context not found | Calling deleteContext() or getContext() with a context ID that does not exist | Use listContexts() to verify the context ID before deleting or retrieving |
| Request timeout | The agent takes longer than the configured timeoutMs (default: 4 minutes) | Increase timeoutMs in the options, simplify the prompt, or reduce the number of connected tools |
| Embedding model cannot be modified | Attempting to change the embeddingModel on an existing knowledge base | Create a new knowledge base with the desired embedding model instead |
Handling Errors in Streaming
When using chat(), errors are delivered through the Observable's error callback:
const stream = squid.ai().agent('banking-copilot').chat('Analyze this data');
stream.subscribe({
next: (response) => console.log(response),
error: (err) => {
console.error('Agent error:', err.message);
},
complete: () => console.log('Done'),
});
Best Practices
Instructions
- Keep instructions concise and direct. Describe the agent's role and what it should (and should not) do.
- Use instructions for behavioral rules (tone, scope, response style) rather than for factual content. Put factual content in knowledge bases instead.
- Test changes to instructions using the Test chat feature in the Agent Studio before deploying.
Knowledge Bases
- Use descriptive
descriptionvalues when connecting knowledge bases. The description is how the agent decides which knowledge base to consult, especially when multiple are connected.
For guidance on structuring knowledge base content and metadata, see the knowledge base best practices.
Multi-Agent Workflows
- Give each connected agent a clear, specific description. Vague descriptions lead to incorrect delegation.
- Set
quotas.maxAiCallStackSizeto a reasonable limit to avoid runaway recursive calls between agents. - Use
executionPlanOptionsfor complex multi-step tasks so the agent reasons about its approach before acting.
Performance
- Use
chat()for user-facing interactions where perceived speed matters. Streaming shows tokens as they arrive rather than waiting for the full response. - Set
disableContext: truewhen knowledge base context is not needed for a request to reduce latency. - Use
memoryOptions.memoryMode: 'none'for stateless, one-off requests that do not need conversation history.
Securing your Agent
Securing your data is vital when using the Squid Client SDK to create agents and enable chatting. The AI agent and the chats conducted with them may contain sensitive information, so it is crucial to restrict access and updates to prevent unauthorized usage or modification.
To learn about securing your AI agent, check out the Securing AI agents documentation.
Agent API Keys
Agent API Keys can provide a more granular level of security when calling Agent actions. View the Agent API Keys documentation for more details.