squidcloud
Squid Cloud Python client SDK.
Usage::
from squidcloud import Squid
squid = Squid(
app_id="my-app",
api_key="my-api-key",
region="us-east-1.aws",
environment_id="dev",
)
# AI agents
response = await squid.ai().agent("my-agent").ask("Hello!")
# Execute backend function
result = await squid.execute_function("MyService:greet", "World")
# Web utilities
content = await squid.web().get_url_content("https://example.com")
1"""Squid Cloud Python client SDK. 2 3Usage:: 4 5 from squidcloud import Squid 6 7 squid = Squid( 8 app_id="my-app", 9 api_key="my-api-key", 10 region="us-east-1.aws", 11 environment_id="dev", 12 ) 13 14 # AI agents 15 response = await squid.ai().agent("my-agent").ask("Hello!") 16 17 # Execute backend function 18 result = await squid.execute_function("MyService:greet", "World") 19 20 # Web utilities 21 content = await squid.web().get_url_content("https://example.com") 22""" 23 24from squidcloud.ai import ( 25 AgentClient, 26 AiClient, 27 AudioClient, 28 ImageClient, 29 KnowledgeBaseClient, 30) 31from squidcloud.client import Squid 32from squidcloud.extraction import ExtractionClient 33from squidcloud.http import SquidHttpError 34from squidcloud.matchmaking import MatchmakingClient 35from squidcloud.sessions import SessionsClient 36from squidcloud.types import ( 37 AgentAuditLogEntry, 38 AgentAuditLogFilter, 39 AgentAuditLogUpdateEntry, 40 AiAdvisorOptions, 41 AiAgent, 42 AiAgentExecutionPlanOptions, 43 AiAgentMcpServerConfig, 44 AiAgentMemoryOptions, 45 AiAgentResponseFormat, 46 AiAgentSecurityOptions, 47 AiAskModelSelection, 48 AiAskOptions, 49 AiAudioCreateSpeechOptions, 50 AiChatModelSelection, 51 AiChatOptions, 52 AiChatPromptQuotas, 53 AiConnectedAgentMetadata, 54 AiConnectedIntegrationMetadata, 55 AiConnectedKnowledgeBaseMetadata, 56 AiContextFileOptions, 57 AiContextTextOptions, 58 AiEmbeddingsModelSelection, 59 AiFileUrl, 60 AiFunctionAttributes, 61 AiFunctionMetadata, 62 AiFunctionParam, 63 AiKnowledgeBase, 64 AiKnowledgeBaseExternalSource, 65 AiKnowledgeBaseExternalSourceTraits, 66 AiKnowledgeBaseGraphConceptsConfig, 67 AiKnowledgeBaseGraphConfig, 68 AiKnowledgeBaseGraphFilter, 69 AiKnowledgeBaseGraphPathFacetConfig, 70 AiKnowledgeBaseGraphSearchOptions, 71 AiKnowledgeBaseMetadataField, 72 AiModelRoutingOptions, 73 AiModelRoutingResult, 74 AiModelRoutingStep, 75 AiPiiOptions, 76 AiPromptInjectionOptions, 77 AiQueryAnalyzeResultsOptions, 78 AiQueryCollectionsSelectionRunMode, 79 AiQueryGenerateQueryOptions, 80 AiQueryOptions, 81 AiQuerySelectCollectionsOptions, 82 AiQueryValidateWithAiOptions, 83 AiSecurityClassifierOptions, 84 AiSessionContext, 85 AiStructuredOutputFormat, 86 AiUsageAttribution, 87 ContextRequest, 88 CreatePdfDimensionsOptions, 89 CreatePdfFormatOptions, 90 CreatePdfOutputOptions, 91 EmbeddingModelIdSpec, 92 ExtractDataFromDocumentOptions, 93 FileContextRequest, 94 FluxOptions, 95 GptImageOptions, 96 GuardrailsOptions, 97 ImageGenerateOptions, 98 IntegrationEmbeddingModelSpec, 99 IntegrationModelSpec, 100 KnowledgeBaseAuditLogEntry, 101 KnowledgeBaseAuditLogFilter, 102 KnowledgeBaseAuditLogSource, 103 KnowledgeBaseGraphQueryOp, 104 KnowledgeBaseSearchOptions, 105 ListAgentAuditLogsResponse, 106 ListKnowledgeBaseAuditLogsResponse, 107 ListSessionsFilter, 108 ListSessionsResponse, 109 MmCategory, 110 MmEntity, 111 MmFindMatchesOptions, 112 MmListEntitiesOptions, 113 ModelIdSpec, 114 Session, 115 SessionExpiration, 116 SessionTtl, 117 StableDiffusionOptions, 118 TextContextRequest, 119 UpsertAgentOptions, 120 VectorDbType, 121 WebAiSearchResponse, 122 WebShortUrlBulkResponse, 123 WebShortUrlResponse, 124) 125from squidcloud.web import WebClient 126 127__all__ = [ 128 "AgentAuditLogEntry", 129 "AgentAuditLogFilter", 130 "AgentAuditLogUpdateEntry", 131 "AgentClient", 132 "AiAdvisorOptions", 133 "AiAgent", 134 "AiAgentExecutionPlanOptions", 135 "AiAgentMcpServerConfig", 136 "AiAgentMemoryOptions", 137 "AiAgentResponseFormat", 138 "AiAgentSecurityOptions", 139 "AiAskModelSelection", 140 "AiAskOptions", 141 "AiAudioCreateSpeechOptions", 142 "AiChatModelSelection", 143 # AI Chat 144 "AiChatOptions", 145 "AiChatPromptQuotas", 146 "AiClient", 147 "AiConnectedAgentMetadata", 148 "AiConnectedIntegrationMetadata", 149 "AiConnectedKnowledgeBaseMetadata", 150 "AiContextFileOptions", 151 "AiContextTextOptions", 152 "AiEmbeddingsModelSelection", 153 "AiFileUrl", 154 "AiFunctionAttributes", 155 "AiFunctionMetadata", 156 "AiFunctionParam", 157 # Knowledge Base 158 "AiKnowledgeBase", 159 "AiKnowledgeBaseExternalSource", 160 "AiKnowledgeBaseExternalSourceTraits", 161 "AiKnowledgeBaseGraphConceptsConfig", 162 "AiKnowledgeBaseGraphConfig", 163 "AiKnowledgeBaseGraphFilter", 164 "AiKnowledgeBaseGraphPathFacetConfig", 165 "AiKnowledgeBaseGraphSearchOptions", 166 "AiKnowledgeBaseMetadataField", 167 "AiModelRoutingOptions", 168 "AiModelRoutingResult", 169 "AiModelRoutingStep", 170 "AiPiiOptions", 171 "AiPromptInjectionOptions", 172 # AI Query 173 "AiQueryAnalyzeResultsOptions", 174 "AiQueryCollectionsSelectionRunMode", 175 "AiQueryGenerateQueryOptions", 176 "AiQueryOptions", 177 "AiQuerySelectCollectionsOptions", 178 "AiQueryValidateWithAiOptions", 179 "AiSecurityClassifierOptions", 180 "AiSessionContext", 181 "AiStructuredOutputFormat", 182 "AiUsageAttribution", 183 "AudioClient", 184 "ContextRequest", 185 "CreatePdfDimensionsOptions", 186 "CreatePdfFormatOptions", 187 # Extraction 188 "CreatePdfOutputOptions", 189 "EmbeddingModelIdSpec", 190 "ExtractDataFromDocumentOptions", 191 "ExtractionClient", 192 "FileContextRequest", 193 "FluxOptions", 194 "GptImageOptions", 195 "GuardrailsOptions", 196 # Image 197 "ImageClient", 198 "ImageGenerateOptions", 199 "IntegrationEmbeddingModelSpec", 200 "IntegrationModelSpec", 201 "KnowledgeBaseAuditLogEntry", 202 "KnowledgeBaseAuditLogFilter", 203 "KnowledgeBaseAuditLogSource", 204 "KnowledgeBaseClient", 205 "KnowledgeBaseGraphQueryOp", 206 "KnowledgeBaseSearchOptions", 207 "ListAgentAuditLogsResponse", 208 "ListKnowledgeBaseAuditLogsResponse", 209 # Sessions 210 "ListSessionsFilter", 211 "ListSessionsResponse", 212 # Matchmaking 213 "MatchmakingClient", 214 "MmCategory", 215 "MmEntity", 216 "MmFindMatchesOptions", 217 "MmListEntitiesOptions", 218 "ModelIdSpec", 219 "Session", 220 "SessionExpiration", 221 "SessionTtl", 222 "SessionsClient", 223 "Squid", 224 "SquidHttpError", 225 "StableDiffusionOptions", 226 "TextContextRequest", 227 "UpsertAgentOptions", 228 "VectorDbType", 229 # Web 230 "WebAiSearchResponse", 231 "WebClient", 232 "WebShortUrlBulkResponse", 233 "WebShortUrlResponse", 234]
1201class AgentAuditLogEntry(TypedDict): 1202 """One entry of an agent's audit log: a prompt it received, or a change to it. Dates are ISO strings.""" 1203 1204 # Identifies the entry; entries recorded with the same content in the same millisecond share it. 1205 id: str 1206 type: Literal["invocation", "management"] 1207 # Absent for a management entry, whose kind of change is in ``tags["action"]``. 1208 jobId: NotRequired[str] 1209 prompt: str 1210 # Present only when the agent logs its full context. 1211 systemInstructions: NotRequired[str] 1212 tags: dict[str, str] 1213 createdAt: str 1214 # Milliseconds from the prompt to the agent's response; absent until the response is recorded. 1215 durationMs: NotRequired[int] 1216 # The updates of the invocation's job, oldest first; present only when ``include_updates`` is set. 1217 updates: NotRequired[list[AgentAuditLogUpdateEntry]] 1218 # Set when the job's updates were too large to return in full; ``updates`` holds the oldest of them. 1219 updatesTruncated: NotRequired[bool]
One entry of an agent's audit log: a prompt it received, or a change to it. Dates are ISO strings.
1173class AgentAuditLogFilter(TypedDict, total=False): 1174 """Filters of an agent audit log listing. Dates are ISO strings.""" 1175 1176 type: Literal["invocation", "management"] 1177 # The subject of the caller's auth token. 1178 userId: str 1179 # Only the invocations of this job. 1180 jobId: str 1181 createdAfter: str 1182 createdBefore: str
Filters of an agent audit log listing. Dates are ISO strings.
1185class AgentAuditLogUpdateEntry(TypedDict): 1186 """One update recorded during an invocation's job: a status update or a response. Dates are ISO strings.""" 1187 1188 type: Literal["statusUpdate", "response"] 1189 # The agent that recorded the update; a job's updates include those of the connected agents it called. 1190 agentId: NotRequired[str] 1191 # The rows of one status update, such as its start and its result, share it. 1192 statusUpdateId: str 1193 parentStatusUpdateId: NotRequired[str] 1194 title: str 1195 body: str 1196 # A response carries its token usage here. 1197 tags: dict[str, str] 1198 createdAt: str
One update recorded during an invocation's job: a status update or a response. Dates are ISO strings.
174class AgentClient: 175 """Operations on a single AI agent. 176 177 Provides methods for chatting with an agent, managing its configuration, 178 updating guardrails, and working with revisions. 179 180 Obtained via :meth:`AiClient.agent`. 181 182 Example:: 183 184 agent = squid.ai().agent("my-agent") 185 response = await agent.ask("What is the weather?", options={"temperature": 0.7}) 186 await agent.update_instructions("Always respond in haiku format.") 187 """ 188 189 def __init__(self, http: HttpTransport, agent_id: str) -> None: 190 self._http = http 191 self._agent_id = agent_id 192 193 # --- Chat --- 194 195 async def ask( 196 self, 197 prompt: str, 198 options: AiChatOptions | AiAskOptions | None = None, 199 ) -> str: 200 """Ask the agent a question and get a text response. 201 202 Args: 203 prompt: The user's question or instruction. 204 options: Chat options controlling model, temperature, memory, 205 functions, guardrails, and more. See :class:`AiChatOptions`. With 206 :class:`AiAskOptions`, ``model`` may be an :class:`AiModelRoutingOptions` 207 to let a routing model pick the answering model; 208 :meth:`ask_with_annotations` also reports which one it chose. 209 210 Returns: 211 The agent's response as a string. 212 213 Raises: 214 SquidHttpError: If the agent is not found or the request fails. 215 216 Example:: 217 218 response = await agent.ask( 219 "Summarize this document", 220 options={ 221 "model": "gemini-3.8-flash", 222 "temperature": 0.3, 223 "memoryOptions": {"memoryId": "session-1", "memoryMode": "read-write"}, 224 }, 225 ) 226 """ 227 result = await self._http.post( 228 "squid-api/v1/ai/agent/ask", 229 {"agentId": self._agent_id, "prompt": prompt, "options": options or {}}, 230 ) 231 return result.get("responseString", "") if result else "" 232 233 async def ask_with_annotations( 234 self, 235 prompt: str, 236 options: AiChatOptions | AiAskOptions | None = None, 237 ) -> dict: 238 """Ask the agent and get a response with annotations. 239 240 Annotations include file references, citations, and other metadata 241 the agent may attach to its response. 242 243 Args: 244 prompt: The user's question or instruction. 245 options: Chat options. See :class:`AiChatOptions` and :class:`AiAskOptions`. 246 247 Returns: 248 A dict with: 249 - ``responseString`` (str): The text response. 250 - ``annotations`` (dict): Annotation metadata keyed by ID. 251 - ``routing`` (:class:`AiModelRoutingResult`): Present when ``model`` 252 was an :class:`AiModelRoutingOptions`: the chosen model and effort, 253 the routing model's rating and reason and the routing call's usage. 254 255 Example:: 256 257 result = await agent.ask_with_annotations("Find relevant docs") 258 print(result["responseString"]) 259 for ann_id, ann in result.get("annotations", {}).items(): 260 print(f" Annotation: {ann}") 261 """ 262 return await self._http.post( 263 "squid-api/v1/ai/agent/askWithAnnotations", 264 {"agentId": self._agent_id, "prompt": prompt, "options": options or {}}, 265 ) 266 267 # --- Management --- 268 269 async def get(self) -> dict | None: 270 """Get the agent's configuration. 271 272 Returns: 273 An ``AiAgent`` dict with keys: ``id``, ``createdAt``, ``updatedAt``, 274 ``description``, ``isPublic``, ``auditLog``, ``auditLogFullContext``, 275 ``options``, ``apiKey``. 276 Returns ``None`` if the agent does not exist. 277 """ 278 return await self._http.get(f"squid-api/v1/ai/agent/get/{self._agent_id}") 279 280 async def upsert( 281 self, 282 *, 283 description: str | None = None, 284 is_public: bool | None = None, 285 audit_log: bool | None = None, 286 audit_log_full_context: bool | None = None, 287 api_key: str | None = None, 288 mcp_server: AiAgentMcpServerConfig | None = None, 289 options: AiChatOptions | None = None, 290 ) -> None: 291 """Create or update the agent. 292 293 If the agent does not exist, it is created. If it exists, the provided 294 fields are updated (fields set to ``None`` are left unchanged). 295 296 Args: 297 description: A description of the agent's purpose or capabilities. 298 is_public: Whether the agent is publicly accessible (default ``False``). A caller 299 without the app API key can narrow its stored knowledge bases and metadata 300 filters per request, not widen them. 301 audit_log: Enable audit logging for the agent's activities. 302 audit_log_full_context: Record the full agent context (system 303 instructions and retrieved knowledge-base content) in the audit 304 log; requires ``audit_log``. 305 api_key: Optional API key used specifically for this agent. 306 mcp_server: Configuration for exposing the agent as an MCP server 307 at ``/mcp/<agentId>``. See :class:`AiAgentMcpServerConfig`. 308 options: Default chat options applied to every request unless 309 overridden per-call. See :class:`AiChatOptions`. 310 311 Example:: 312 313 await agent.upsert( 314 description="Customer support agent", 315 options={"model": "gemini-3.8-flash", "temperature": 0.5}, 316 ) 317 """ 318 body: dict[str, Any] = {"id": self._agent_id} 319 if description is not None: 320 body["description"] = description 321 if is_public is not None: 322 body["isPublic"] = is_public 323 if audit_log is not None: 324 body["auditLog"] = audit_log 325 if audit_log_full_context is not None: 326 body["auditLogFullContext"] = audit_log_full_context 327 if api_key is not None: 328 body["apiKey"] = api_key 329 if mcp_server is not None: 330 body["mcpServer"] = mcp_server 331 if options is not None: 332 body["options"] = options 333 await self._http.post("squid-api/v1/ai/agent/upsert", body) 334 335 async def delete(self) -> None: 336 """Delete the agent permanently.""" 337 await self._http.post("squid-api/v1/ai/agent/delete", {"agentId": self._agent_id}) 338 339 async def update_instructions(self, instructions: str) -> None: 340 """Update the agent's system instructions. 341 342 Args: 343 instructions: The new system prompt / instructions text. 344 """ 345 await self._http.post( 346 "squid-api/v1/ai/agent/updateInstructions", 347 {"agentId": self._agent_id, "instructions": instructions}, 348 ) 349 350 async def update_model(self, model: AiChatModelSelection) -> None: 351 """Update the agent's default LLM model. 352 353 Args: 354 model: A model name string (e.g., ``'gemini-3.8-flash'``) or an 355 ``IntegrationModelSpec`` dict (``{'integrationId': str, 'model': str}``). 356 """ 357 await self._http.post( 358 "squid-api/v1/ai/agent/updateModel", 359 {"agentId": self._agent_id, "model": model}, 360 ) 361 362 async def update_connected_agents( 363 self, connected_agents: list[AiConnectedAgentMetadata] 364 ) -> None: 365 """Update the list of connected agents. 366 367 Connected agents can be called by this agent during conversations. 368 369 Args: 370 connected_agents: List of ``{'agentId': str, 'description': str}`` dicts. 371 """ 372 await self._http.post( 373 "squid-api/v1/ai/agent/updateConnectedAgents", 374 {"agentId": self._agent_id, "connectedAgents": connected_agents}, 375 ) 376 377 async def update_guardrails(self, guardrails: GuardrailsOptions) -> None: 378 """Update the agent's guardrail settings. 379 380 Args: 381 guardrails: A :class:`GuardrailsOptions` dict with optional keys: 382 ``custom``, ``disablePii``, ``professionalTone``, 383 ``offTopicAnswers``, ``disableProfanity``. 384 385 Example:: 386 387 await agent.update_guardrails( 388 { 389 "professionalTone": True, 390 "disableProfanity": True, 391 } 392 ) 393 """ 394 await self._http.post( 395 "squid-api/v1/ai/agent/updateGuardrails", 396 {"agentId": self._agent_id, "guardrails": guardrails}, 397 ) 398 399 async def update_custom_guardrails(self, custom_guardrail: str) -> None: 400 """Update the custom guardrail instruction text. 401 402 Args: 403 custom_guardrail: Free-form guardrail instruction string. 404 """ 405 await self._http.post( 406 "squid-api/v1/ai/agent/updateCustomGuardrails", 407 {"agentId": self._agent_id, "customGuardrail": custom_guardrail}, 408 ) 409 410 async def delete_custom_guardrails(self) -> None: 411 """Delete the custom guardrail, reverting to defaults.""" 412 await self._http.post( 413 "squid-api/v1/ai/agent/deleteCustomGuardrails", 414 {"agentId": self._agent_id}, 415 ) 416 417 async def update_pii(self, pii: AiPiiOptions) -> None: 418 """Update the agent's PII screening, merging with its existing settings. 419 420 With ``onDetect`` set to ``"reject"`` the agent refuses any prompt carrying 421 PII before it reaches the model, so the prompt is never answered and never 422 stored. This is the inverse of ``GuardrailsOptions.disablePii``, which asks 423 the agent's own model not to emit PII in its answer. 424 425 Args: 426 pii: An :class:`AiPiiOptions` dict with optional keys: ``onDetect``, 427 ``entities``, ``customRules``, ``classifierModel``, ``allowList``. 428 429 Example:: 430 431 await agent.update_pii( 432 { 433 "onDetect": "reject", 434 "customRules": ["internal case numbers like CASE-12345"], 435 } 436 ) 437 """ 438 await self._http.post( 439 "squid-api/v1/ai/agent/updatePii", 440 {"agentId": self._agent_id, "pii": pii}, 441 ) 442 443 async def update_security(self, security: AiAgentSecurityOptions) -> None: 444 """Replaces runtime security policies. Omitted models inherit platform defaults.""" 445 await self._http.post( 446 "squid-api/v1/ai/agent/updateSecurity", 447 {"agentId": self._agent_id, "security": security}, 448 ) 449 450 # --- Revisions --- 451 452 async def list_revisions(self) -> list[dict]: 453 """List all revisions of this agent. 454 455 Returns: 456 A list of ``AiAgentRevision`` dicts, each containing: 457 ``agentId``, ``revisionNumber``, ``action``, ``createdAt``, 458 ``agentSnapshot``. 459 """ 460 result = await self._http.get(f"squid-api/v1/ai/agent/revisions/{self._agent_id}") 461 return result.get("revisions", []) if result else [] 462 463 async def restore_revision(self, revision_number: int) -> None: 464 """Restore the agent to a previous revision. 465 466 Args: 467 revision_number: The revision number to restore. 468 """ 469 await self._http.post( 470 "squid-api/v1/ai/agent/restoreRevision", 471 {"agentId": self._agent_id, "revisionNumber": revision_number}, 472 ) 473 474 async def delete_revision(self, revision_number: int) -> None: 475 """Delete a specific revision. 476 477 Args: 478 revision_number: The revision number to delete. 479 """ 480 await self._http.post( 481 "squid-api/v1/ai/agent/deleteRevision", 482 {"agentId": self._agent_id, "revisionNumber": revision_number}, 483 ) 484 485 # --- Audit logs --- 486 487 async def list_audit_logs( 488 self, 489 *, 490 limit: int | None = None, 491 cursor: str | None = None, 492 where: AgentAuditLogFilter | None = None, 493 include_updates: bool = False, 494 ) -> ListAgentAuditLogsResponse: 495 """Return a page of this agent's audit log, newest first: the prompts it received and the changes made to it. 496 497 Entries are recorded only while the agent has ``auditLog`` on. Pass a response's ``nextCursor`` as 498 ``cursor`` to get the next page; a page may hold fewer entries than ``limit``. 499 500 Args: 501 limit: The page size: 100 by default, at most 1000. 502 cursor: The ``nextCursor`` of the previous page. 503 where: Filters: ``type`` (``"invocation"`` or ``"management"``), ``userId``, ``jobId``, 504 ``createdAfter`` and ``createdBefore`` (ISO timestamps). 505 include_updates: Return the updates of each invocation's job in ``updates``; the entries of one job carry 506 the same updates. 507 """ 508 body = _audit_log_request(limit, cursor, where) 509 body["agentId"] = self._agent_id 510 if include_updates: 511 body["include"] = {"updates": True} 512 return await self._http.post("squid-api/v1/ai/agent/listAuditLogs", body)
Operations on a single AI agent.
Provides methods for chatting with an agent, managing its configuration, updating guardrails, and working with revisions.
Obtained via AiClient.agent().
Example::
agent = squid.ai().agent("my-agent")
response = await agent.ask("What is the weather?", options={"temperature": 0.7})
await agent.update_instructions("Always respond in haiku format.")
195 async def ask( 196 self, 197 prompt: str, 198 options: AiChatOptions | AiAskOptions | None = None, 199 ) -> str: 200 """Ask the agent a question and get a text response. 201 202 Args: 203 prompt: The user's question or instruction. 204 options: Chat options controlling model, temperature, memory, 205 functions, guardrails, and more. See :class:`AiChatOptions`. With 206 :class:`AiAskOptions`, ``model`` may be an :class:`AiModelRoutingOptions` 207 to let a routing model pick the answering model; 208 :meth:`ask_with_annotations` also reports which one it chose. 209 210 Returns: 211 The agent's response as a string. 212 213 Raises: 214 SquidHttpError: If the agent is not found or the request fails. 215 216 Example:: 217 218 response = await agent.ask( 219 "Summarize this document", 220 options={ 221 "model": "gemini-3.8-flash", 222 "temperature": 0.3, 223 "memoryOptions": {"memoryId": "session-1", "memoryMode": "read-write"}, 224 }, 225 ) 226 """ 227 result = await self._http.post( 228 "squid-api/v1/ai/agent/ask", 229 {"agentId": self._agent_id, "prompt": prompt, "options": options or {}}, 230 ) 231 return result.get("responseString", "") if result else ""
Ask the agent a question and get a text response.
Arguments:
- prompt: The user's question or instruction.
- options: Chat options controlling model, temperature, memory,
functions, guardrails, and more. See
AiChatOptions. WithAiAskOptions,modelmay be anAiModelRoutingOptionsto let a routing model pick the answering model;ask_with_annotations()also reports which one it chose.
Returns:
The agent's response as a string.
Raises:
- SquidHttpError: If the agent is not found or the request fails.
Example::
response = await agent.ask(
"Summarize this document",
options={
"model": "gemini-3.8-flash",
"temperature": 0.3,
"memoryOptions": {"memoryId": "session-1", "memoryMode": "read-write"},
},
)
233 async def ask_with_annotations( 234 self, 235 prompt: str, 236 options: AiChatOptions | AiAskOptions | None = None, 237 ) -> dict: 238 """Ask the agent and get a response with annotations. 239 240 Annotations include file references, citations, and other metadata 241 the agent may attach to its response. 242 243 Args: 244 prompt: The user's question or instruction. 245 options: Chat options. See :class:`AiChatOptions` and :class:`AiAskOptions`. 246 247 Returns: 248 A dict with: 249 - ``responseString`` (str): The text response. 250 - ``annotations`` (dict): Annotation metadata keyed by ID. 251 - ``routing`` (:class:`AiModelRoutingResult`): Present when ``model`` 252 was an :class:`AiModelRoutingOptions`: the chosen model and effort, 253 the routing model's rating and reason and the routing call's usage. 254 255 Example:: 256 257 result = await agent.ask_with_annotations("Find relevant docs") 258 print(result["responseString"]) 259 for ann_id, ann in result.get("annotations", {}).items(): 260 print(f" Annotation: {ann}") 261 """ 262 return await self._http.post( 263 "squid-api/v1/ai/agent/askWithAnnotations", 264 {"agentId": self._agent_id, "prompt": prompt, "options": options or {}}, 265 )
Ask the agent and get a response with annotations.
Annotations include file references, citations, and other metadata the agent may attach to its response.
Arguments:
- prompt: The user's question or instruction.
- options: Chat options. See
AiChatOptionsandAiAskOptions.
Returns:
A dict with: -
responseString(str): The text response. -annotations(dict): Annotation metadata keyed by ID. -routing(AiModelRoutingResult): Present whenmodelwas anAiModelRoutingOptions: the chosen model and effort, the routing model's rating and reason and the routing call's usage.
Example::
result = await agent.ask_with_annotations("Find relevant docs")
print(result["responseString"])
for ann_id, ann in result.get("annotations", {}).items():
print(f" Annotation: {ann}")
269 async def get(self) -> dict | None: 270 """Get the agent's configuration. 271 272 Returns: 273 An ``AiAgent`` dict with keys: ``id``, ``createdAt``, ``updatedAt``, 274 ``description``, ``isPublic``, ``auditLog``, ``auditLogFullContext``, 275 ``options``, ``apiKey``. 276 Returns ``None`` if the agent does not exist. 277 """ 278 return await self._http.get(f"squid-api/v1/ai/agent/get/{self._agent_id}")
Get the agent's configuration.
Returns:
An
AiAgentdict with keys:id,createdAt,updatedAt,description,isPublic,auditLog,auditLogFullContext,options,apiKey. ReturnsNoneif the agent does not exist.
280 async def upsert( 281 self, 282 *, 283 description: str | None = None, 284 is_public: bool | None = None, 285 audit_log: bool | None = None, 286 audit_log_full_context: bool | None = None, 287 api_key: str | None = None, 288 mcp_server: AiAgentMcpServerConfig | None = None, 289 options: AiChatOptions | None = None, 290 ) -> None: 291 """Create or update the agent. 292 293 If the agent does not exist, it is created. If it exists, the provided 294 fields are updated (fields set to ``None`` are left unchanged). 295 296 Args: 297 description: A description of the agent's purpose or capabilities. 298 is_public: Whether the agent is publicly accessible (default ``False``). A caller 299 without the app API key can narrow its stored knowledge bases and metadata 300 filters per request, not widen them. 301 audit_log: Enable audit logging for the agent's activities. 302 audit_log_full_context: Record the full agent context (system 303 instructions and retrieved knowledge-base content) in the audit 304 log; requires ``audit_log``. 305 api_key: Optional API key used specifically for this agent. 306 mcp_server: Configuration for exposing the agent as an MCP server 307 at ``/mcp/<agentId>``. See :class:`AiAgentMcpServerConfig`. 308 options: Default chat options applied to every request unless 309 overridden per-call. See :class:`AiChatOptions`. 310 311 Example:: 312 313 await agent.upsert( 314 description="Customer support agent", 315 options={"model": "gemini-3.8-flash", "temperature": 0.5}, 316 ) 317 """ 318 body: dict[str, Any] = {"id": self._agent_id} 319 if description is not None: 320 body["description"] = description 321 if is_public is not None: 322 body["isPublic"] = is_public 323 if audit_log is not None: 324 body["auditLog"] = audit_log 325 if audit_log_full_context is not None: 326 body["auditLogFullContext"] = audit_log_full_context 327 if api_key is not None: 328 body["apiKey"] = api_key 329 if mcp_server is not None: 330 body["mcpServer"] = mcp_server 331 if options is not None: 332 body["options"] = options 333 await self._http.post("squid-api/v1/ai/agent/upsert", body)
Create or update the agent.
If the agent does not exist, it is created. If it exists, the provided
fields are updated (fields set to None are left unchanged).
Arguments:
- description: A description of the agent's purpose or capabilities.
- is_public: Whether the agent is publicly accessible (default
False). A caller without the app API key can narrow its stored knowledge bases and metadata filters per request, not widen them. - audit_log: Enable audit logging for the agent's activities.
- audit_log_full_context: Record the full agent context (system
instructions and retrieved knowledge-base content) in the audit
log; requires
audit_log. - api_key: Optional API key used specifically for this agent.
- mcp_server: Configuration for exposing the agent as an MCP server
at
/mcp/<agentId>. SeeAiAgentMcpServerConfig. - options: Default chat options applied to every request unless
overridden per-call. See
AiChatOptions.
Example::
await agent.upsert(
description="Customer support agent",
options={"model": "gemini-3.8-flash", "temperature": 0.5},
)
335 async def delete(self) -> None: 336 """Delete the agent permanently.""" 337 await self._http.post("squid-api/v1/ai/agent/delete", {"agentId": self._agent_id})
Delete the agent permanently.
339 async def update_instructions(self, instructions: str) -> None: 340 """Update the agent's system instructions. 341 342 Args: 343 instructions: The new system prompt / instructions text. 344 """ 345 await self._http.post( 346 "squid-api/v1/ai/agent/updateInstructions", 347 {"agentId": self._agent_id, "instructions": instructions}, 348 )
Update the agent's system instructions.
Arguments:
- instructions: The new system prompt / instructions text.
350 async def update_model(self, model: AiChatModelSelection) -> None: 351 """Update the agent's default LLM model. 352 353 Args: 354 model: A model name string (e.g., ``'gemini-3.8-flash'``) or an 355 ``IntegrationModelSpec`` dict (``{'integrationId': str, 'model': str}``). 356 """ 357 await self._http.post( 358 "squid-api/v1/ai/agent/updateModel", 359 {"agentId": self._agent_id, "model": model}, 360 )
Update the agent's default LLM model.
Arguments:
- model: A model name string (e.g.,
'gemini-3.8-flash') or anIntegrationModelSpecdict ({'integrationId': str, 'model': str}).
362 async def update_connected_agents( 363 self, connected_agents: list[AiConnectedAgentMetadata] 364 ) -> None: 365 """Update the list of connected agents. 366 367 Connected agents can be called by this agent during conversations. 368 369 Args: 370 connected_agents: List of ``{'agentId': str, 'description': str}`` dicts. 371 """ 372 await self._http.post( 373 "squid-api/v1/ai/agent/updateConnectedAgents", 374 {"agentId": self._agent_id, "connectedAgents": connected_agents}, 375 )
Update the list of connected agents.
Connected agents can be called by this agent during conversations.
Arguments:
- connected_agents: List of
{'agentId': str, 'description': str}dicts.
377 async def update_guardrails(self, guardrails: GuardrailsOptions) -> None: 378 """Update the agent's guardrail settings. 379 380 Args: 381 guardrails: A :class:`GuardrailsOptions` dict with optional keys: 382 ``custom``, ``disablePii``, ``professionalTone``, 383 ``offTopicAnswers``, ``disableProfanity``. 384 385 Example:: 386 387 await agent.update_guardrails( 388 { 389 "professionalTone": True, 390 "disableProfanity": True, 391 } 392 ) 393 """ 394 await self._http.post( 395 "squid-api/v1/ai/agent/updateGuardrails", 396 {"agentId": self._agent_id, "guardrails": guardrails}, 397 )
Update the agent's guardrail settings.
Arguments:
- guardrails: A
GuardrailsOptionsdict with optional keys:custom,disablePii,professionalTone,offTopicAnswers,disableProfanity.
Example::
await agent.update_guardrails(
{
"professionalTone": True,
"disableProfanity": True,
}
)
399 async def update_custom_guardrails(self, custom_guardrail: str) -> None: 400 """Update the custom guardrail instruction text. 401 402 Args: 403 custom_guardrail: Free-form guardrail instruction string. 404 """ 405 await self._http.post( 406 "squid-api/v1/ai/agent/updateCustomGuardrails", 407 {"agentId": self._agent_id, "customGuardrail": custom_guardrail}, 408 )
Update the custom guardrail instruction text.
Arguments:
- custom_guardrail: Free-form guardrail instruction string.
410 async def delete_custom_guardrails(self) -> None: 411 """Delete the custom guardrail, reverting to defaults.""" 412 await self._http.post( 413 "squid-api/v1/ai/agent/deleteCustomGuardrails", 414 {"agentId": self._agent_id}, 415 )
Delete the custom guardrail, reverting to defaults.
417 async def update_pii(self, pii: AiPiiOptions) -> None: 418 """Update the agent's PII screening, merging with its existing settings. 419 420 With ``onDetect`` set to ``"reject"`` the agent refuses any prompt carrying 421 PII before it reaches the model, so the prompt is never answered and never 422 stored. This is the inverse of ``GuardrailsOptions.disablePii``, which asks 423 the agent's own model not to emit PII in its answer. 424 425 Args: 426 pii: An :class:`AiPiiOptions` dict with optional keys: ``onDetect``, 427 ``entities``, ``customRules``, ``classifierModel``, ``allowList``. 428 429 Example:: 430 431 await agent.update_pii( 432 { 433 "onDetect": "reject", 434 "customRules": ["internal case numbers like CASE-12345"], 435 } 436 ) 437 """ 438 await self._http.post( 439 "squid-api/v1/ai/agent/updatePii", 440 {"agentId": self._agent_id, "pii": pii}, 441 )
Update the agent's PII screening, merging with its existing settings.
With onDetect set to "reject" the agent refuses any prompt carrying
PII before it reaches the model, so the prompt is never answered and never
stored. This is the inverse of GuardrailsOptions.disablePii, which asks
the agent's own model not to emit PII in its answer.
Arguments:
- pii: An
AiPiiOptionsdict with optional keys:onDetect,entities,customRules,classifierModel,allowList.
Example::
await agent.update_pii(
{
"onDetect": "reject",
"customRules": ["internal case numbers like CASE-12345"],
}
)
443 async def update_security(self, security: AiAgentSecurityOptions) -> None: 444 """Replaces runtime security policies. Omitted models inherit platform defaults.""" 445 await self._http.post( 446 "squid-api/v1/ai/agent/updateSecurity", 447 {"agentId": self._agent_id, "security": security}, 448 )
Replaces runtime security policies. Omitted models inherit platform defaults.
452 async def list_revisions(self) -> list[dict]: 453 """List all revisions of this agent. 454 455 Returns: 456 A list of ``AiAgentRevision`` dicts, each containing: 457 ``agentId``, ``revisionNumber``, ``action``, ``createdAt``, 458 ``agentSnapshot``. 459 """ 460 result = await self._http.get(f"squid-api/v1/ai/agent/revisions/{self._agent_id}") 461 return result.get("revisions", []) if result else []
List all revisions of this agent.
Returns:
A list of
AiAgentRevisiondicts, each containing:agentId,revisionNumber,action,createdAt,agentSnapshot.
463 async def restore_revision(self, revision_number: int) -> None: 464 """Restore the agent to a previous revision. 465 466 Args: 467 revision_number: The revision number to restore. 468 """ 469 await self._http.post( 470 "squid-api/v1/ai/agent/restoreRevision", 471 {"agentId": self._agent_id, "revisionNumber": revision_number}, 472 )
Restore the agent to a previous revision.
Arguments:
- revision_number: The revision number to restore.
474 async def delete_revision(self, revision_number: int) -> None: 475 """Delete a specific revision. 476 477 Args: 478 revision_number: The revision number to delete. 479 """ 480 await self._http.post( 481 "squid-api/v1/ai/agent/deleteRevision", 482 {"agentId": self._agent_id, "revisionNumber": revision_number}, 483 )
Delete a specific revision.
Arguments:
- revision_number: The revision number to delete.
487 async def list_audit_logs( 488 self, 489 *, 490 limit: int | None = None, 491 cursor: str | None = None, 492 where: AgentAuditLogFilter | None = None, 493 include_updates: bool = False, 494 ) -> ListAgentAuditLogsResponse: 495 """Return a page of this agent's audit log, newest first: the prompts it received and the changes made to it. 496 497 Entries are recorded only while the agent has ``auditLog`` on. Pass a response's ``nextCursor`` as 498 ``cursor`` to get the next page; a page may hold fewer entries than ``limit``. 499 500 Args: 501 limit: The page size: 100 by default, at most 1000. 502 cursor: The ``nextCursor`` of the previous page. 503 where: Filters: ``type`` (``"invocation"`` or ``"management"``), ``userId``, ``jobId``, 504 ``createdAfter`` and ``createdBefore`` (ISO timestamps). 505 include_updates: Return the updates of each invocation's job in ``updates``; the entries of one job carry 506 the same updates. 507 """ 508 body = _audit_log_request(limit, cursor, where) 509 body["agentId"] = self._agent_id 510 if include_updates: 511 body["include"] = {"updates": True} 512 return await self._http.post("squid-api/v1/ai/agent/listAuditLogs", body)
Return a page of this agent's audit log, newest first: the prompts it received and the changes made to it.
Entries are recorded only while the agent has auditLog on. Pass a response's nextCursor as
cursor to get the next page; a page may hold fewer entries than limit.
Arguments:
- limit: The page size: 100 by default, at most 1000.
- cursor: The
nextCursorof the previous page. - where: Filters:
type("invocation"or"management"),userId,jobId,createdAfterandcreatedBefore(ISO timestamps). - include_updates: Return the updates of each invocation's job in
updates; the entries of one job carry the same updates.
242class AiAdvisorOptions(TypedDict): 243 """Gives the answering model a tool that consults a stronger model mid-turn. 244 245 The turn stays on its own model, so its prompt cache survives, and the advisor gets only what 246 the answering model passes it. 247 """ 248 249 model: AiChatModelSelection 250 """The model that gives the advice.""" 251 shareFunctions: NotRequired[bool] 252 """Lets the advisor call the turn's functions, including ones with side effects. Defaults to false.""" 253 reasoningEffort: NotRequired[AiReasoningEffort] 254 """The effort the advisor runs at. A vendor model runs at the nearest level it accepts.""" 255 instructions: NotRequired[str] 256 """Added to the advisor's prompt, to steer what it answers and how.""" 257 maxConsultations: NotRequired[int] 258 """Consultations allowed per turn, 1 to 10. Defaults to 3."""
Gives the answering model a tool that consults a stronger model mid-turn.
The turn stays on its own model, so its prompt cache survives, and the advisor gets only what the answering model passes it.
568class AiAgent(TypedDict, total=False): 569 """A definition of an AI agent with its properties and default chat options. 570 571 Returned by :meth:`AiClient.list_agents`. 572 """ 573 574 id: str 575 """The unique identifier of the AI agent. Required.""" 576 createdAt: str 577 """ISO 8601 timestamp of when the agent was created. Required.""" 578 updatedAt: str 579 """ISO 8601 timestamp of when the agent was last updated. Required.""" 580 description: str 581 """An optional description of the agent's purpose or capabilities.""" 582 isPublic: bool 583 """Whether the agent is publicly accessible; defaults to False.""" 584 auditLog: bool 585 """Whether audit logging is enabled for the agent's activities; defaults to False.""" 586 auditLogFullContext: bool 587 """Whether the full agent context (system instructions and retrieved knowledge-base content) is recorded in the audit log; requires auditLog; defaults to False.""" 588 options: AiChatOptions 589 """The agent's default chat options, overridable by the user during use. Required.""" 590 apiKey: str 591 """Optional API key used specifically for operations on this agent.""" 592 mcpServer: AiAgentMcpServerConfig 593 """Optional configuration for exposing the agent as an MCP server."""
A definition of an AI agent with its properties and default chat options.
Returned by AiClient.list_agents().
Whether the full agent context (system instructions and retrieved knowledge-base content) is recorded in the audit log; requires auditLog; defaults to False.
The agent's default chat options, overridable by the user during use. Required.
166class AiAgentExecutionPlanOptions(TypedDict, total=False): 167 """Options for AI agent execution plan.""" 168 169 enabled: bool
Options for AI agent execution plan.
534class AiAgentMcpServerConfig(TypedDict, total=False): 535 """Configuration for exposing an AI agent as an MCP server at ``/mcp/<agentId>``.""" 536 537 enabled: bool 538 """Whether the agent is exposed as an MCP server. Required.""" 539 description: str 540 """Description of the MCP server, served as the ``instructions`` field of the MCP initialize result.""" 541 toolDescription: str 542 """Description of the MCP ``ask`` tool, exposed in the tools manifest.""" 543 oauthIntegrationId: str 544 """ID of an auth integration used to OAuth-protect the MCP server.""" 545 requireApiKey: bool 546 """Require the agent's API key as a bearer token; combinable with OAuth (either is accepted)."""
Configuration for exposing an AI agent as an MCP server at /mcp/<agentId>.
92class AiAgentMemoryOptions(TypedDict, total=False): 93 """Memory/session configuration for agent chat.""" 94 95 memoryId: str 96 """Unique memory ID. Reuse to continue a conversation.""" 97 memoryMode: AiMemoryMode 98 """How memory is used: 'read-write', 'read-only', 'write-only', 'disabled'."""
Memory/session configuration for agent chat.
203class AiAgentSecurityOptions(TypedDict, total=False): 204 """Stored security policies inherited by delegated agents.""" 205 206 promptInjection: AiPromptInjectionOptions
Stored security policies inherited by delegated agents.
408class AiAskOptions(_AiChatOptionsBase, total=False): 409 """Options of :meth:`AgentClient.ask` and :meth:`AgentClient.ask_with_annotations`. 410 411 The same fields as :class:`AiChatOptions`, except that ``model`` may also be an 412 :class:`AiModelRoutingOptions` routing choice. 413 """ 414 415 model: AiAskModelSelection 416 """LLM model to use: a name, an IntegrationModelSpec, or an AiModelRoutingOptions."""
Options of AgentClient.ask() and AgentClient.ask_with_annotations().
The same fields as AiChatOptions, except that model may also be an
AiModelRoutingOptions routing choice.
LLM model to use: a name, an IntegrationModelSpec, or an AiModelRoutingOptions.
227class AiAudioCreateSpeechOptions(TypedDict, total=False): 228 """Options for text-to-speech.""" 229 230 modelName: str 231 """'tts-1' or 'tts-1-hd'.""" 232 voice: str 233 """'alloy'|'ash'|'ballad'|'coral'|'echo'|'fable'|'onyx'|'nova'|'sage'|'shimmer'|'verse'.""" 234 responseFormat: str 235 """Audio output format.""" 236 instructions: str 237 """Extra instructions for speech generation.""" 238 speed: float 239 """Speech speed."""
Options for text-to-speech.
397class AiChatOptions(_AiChatOptionsBase, total=False): 398 """Full chat options for AI agent chat operations and agent profiles. 399 400 Mirrors BaseAiChatOptions from the TypeScript SDK. 401 All fields are optional. 402 """ 403 404 model: AiChatModelSelection 405 """LLM model to use. String name or IntegrationModelSpec."""
Full chat options for AI agent chat operations and agent profiles.
Mirrors BaseAiChatOptions from the TypeScript SDK. All fields are optional.
160class AiChatPromptQuotas(TypedDict, total=False): 161 """Budget for nested/recursive AI chat calls.""" 162 163 maxNestedCalls: int
Budget for nested/recursive AI chat calls.
44class AiClient: 45 """Entry point for AI operations: agents, knowledge base, audio, image. 46 47 Obtained via :meth:`Squid.ai()`. 48 49 Example:: 50 51 ai = squid.ai() 52 agent = ai.agent("my-agent") 53 kb = ai.knowledge_base("my-kb") 54 image_url = await ai.image().generate("a cat in space") 55 """ 56 57 def __init__(self, http: HttpTransport) -> None: 58 self._http = http 59 60 def agent(self, agent_id: str) -> AgentClient: 61 """Get a client for a specific AI agent. 62 63 Args: 64 agent_id: The unique agent identifier. 65 66 Returns: 67 An :class:`AgentClient` bound to the given agent ID. 68 """ 69 return AgentClient(self._http, agent_id) 70 71 def knowledge_base(self, knowledge_base_id: str) -> KnowledgeBaseClient: 72 """Get a client for a specific knowledge base. 73 74 Args: 75 knowledge_base_id: The unique knowledge base identifier. 76 77 Returns: 78 A :class:`KnowledgeBaseClient` bound to the given knowledge base ID. 79 """ 80 return KnowledgeBaseClient(self._http, knowledge_base_id) 81 82 def image(self) -> ImageClient: 83 """Get a client for image generation and processing. 84 85 Returns: 86 An :class:`ImageClient` instance. 87 """ 88 return ImageClient(self._http) 89 90 def audio(self) -> AudioClient: 91 """Get a client for audio transcription and speech synthesis. 92 93 Returns: 94 An :class:`AudioClient` instance. 95 """ 96 return AudioClient(self._http) 97 98 async def list_agents(self) -> list[AiAgent]: 99 """List all AI agents defined for the application. 100 101 Returns: 102 A list of ``AiAgent`` dicts. Empty list if no agents are defined. 103 """ 104 result = await self._http.get("squid-api/v1/ai/agent/listAgents") 105 return result.get("agents", []) if result else [] 106 107 async def list_knowledge_bases(self) -> list[AiKnowledgeBase]: 108 """List all AI knowledge bases defined for the application. 109 110 Returns: 111 A list of ``AiKnowledgeBase`` dicts. Empty list if no knowledge 112 bases are defined. 113 """ 114 result = await self._http.get("squid-api/v1/ai/knowledge-base/listKnowledgeBases") 115 return result.get("knowledgeBases", []) if result else [] 116 117 async def list_chat_models(self, include_deprecated: bool = False) -> list[ModelIdSpec]: 118 """List all AI chat models available to the application. 119 120 Includes both Squid-provided vendor models and any custom integration 121 models configured for the app. 122 123 Args: 124 include_deprecated: When True, deprecated vendor models are 125 included and marked with ``replacedBy``. Defaults to False. 126 127 Returns: 128 A list of ``ModelIdSpec`` dicts, each with ``modelId``, an optional 129 ``integrationId``, and a human-readable ``displayName``. Vendor 130 models also carry a ``description``, and deprecated vendor models a 131 ``replacedBy`` with the active model their calls are routed to. 132 """ 133 params = {"includeDeprecated": "true"} if include_deprecated else None 134 result = await self._http.get("squid-api/v1/ai/settings/listChatModels", params=params) 135 return result.get("models", []) if result else [] 136 137 async def list_embedding_models( 138 self, include_deprecated: bool = False 139 ) -> list[EmbeddingModelIdSpec]: 140 """List the embedding models a new knowledge base can be created on. 141 142 Includes Squid-provided vendor models and the app's custom integration 143 models. Exactly one entry carries ``isDefault``. 144 145 Args: 146 include_deprecated: When True, deprecated vendor models are 147 included and marked with ``replacedBy``. Defaults to False. 148 149 Returns: 150 A list of ``EmbeddingModelIdSpec`` dicts, each with ``modelId``, 151 ``displayName`` and ``source``, plus ``integrationId`` and 152 ``dimensions`` for integration models. 153 """ 154 params = {"includeDeprecated": "true"} if include_deprecated else None 155 result = await self._http.get("squid-api/v1/ai/settings/listEmbeddingModels", params=params) 156 return result.get("models", []) if result else [] 157 158 async def list_functions(self) -> list[AiFunctionMetadata]: 159 """List all AI functions registered for the application's deployed bundle. 160 161 Returns: 162 A list of ``AiFunctionMetadata`` dicts. Empty list if no functions 163 are registered. 164 """ 165 result = await self._http.get("squid-api/v1/ai/function/listFunctions") 166 return result.get("functions", []) if result else []
Entry point for AI operations: agents, knowledge base, audio, image.
Obtained via Squid.ai()().
Example::
ai = squid.ai()
agent = ai.agent("my-agent")
kb = ai.knowledge_base("my-kb")
image_url = await ai.image().generate("a cat in space")
60 def agent(self, agent_id: str) -> AgentClient: 61 """Get a client for a specific AI agent. 62 63 Args: 64 agent_id: The unique agent identifier. 65 66 Returns: 67 An :class:`AgentClient` bound to the given agent ID. 68 """ 69 return AgentClient(self._http, agent_id)
Get a client for a specific AI agent.
Arguments:
- agent_id: The unique agent identifier.
Returns:
An
AgentClientbound to the given agent ID.
71 def knowledge_base(self, knowledge_base_id: str) -> KnowledgeBaseClient: 72 """Get a client for a specific knowledge base. 73 74 Args: 75 knowledge_base_id: The unique knowledge base identifier. 76 77 Returns: 78 A :class:`KnowledgeBaseClient` bound to the given knowledge base ID. 79 """ 80 return KnowledgeBaseClient(self._http, knowledge_base_id)
Get a client for a specific knowledge base.
Arguments:
- knowledge_base_id: The unique knowledge base identifier.
Returns:
A
KnowledgeBaseClientbound to the given knowledge base ID.
98 async def list_agents(self) -> list[AiAgent]: 99 """List all AI agents defined for the application. 100 101 Returns: 102 A list of ``AiAgent`` dicts. Empty list if no agents are defined. 103 """ 104 result = await self._http.get("squid-api/v1/ai/agent/listAgents") 105 return result.get("agents", []) if result else []
List all AI agents defined for the application.
Returns:
A list of
AiAgentdicts. Empty list if no agents are defined.
107 async def list_knowledge_bases(self) -> list[AiKnowledgeBase]: 108 """List all AI knowledge bases defined for the application. 109 110 Returns: 111 A list of ``AiKnowledgeBase`` dicts. Empty list if no knowledge 112 bases are defined. 113 """ 114 result = await self._http.get("squid-api/v1/ai/knowledge-base/listKnowledgeBases") 115 return result.get("knowledgeBases", []) if result else []
List all AI knowledge bases defined for the application.
Returns:
A list of
AiKnowledgeBasedicts. Empty list if no knowledge bases are defined.
117 async def list_chat_models(self, include_deprecated: bool = False) -> list[ModelIdSpec]: 118 """List all AI chat models available to the application. 119 120 Includes both Squid-provided vendor models and any custom integration 121 models configured for the app. 122 123 Args: 124 include_deprecated: When True, deprecated vendor models are 125 included and marked with ``replacedBy``. Defaults to False. 126 127 Returns: 128 A list of ``ModelIdSpec`` dicts, each with ``modelId``, an optional 129 ``integrationId``, and a human-readable ``displayName``. Vendor 130 models also carry a ``description``, and deprecated vendor models a 131 ``replacedBy`` with the active model their calls are routed to. 132 """ 133 params = {"includeDeprecated": "true"} if include_deprecated else None 134 result = await self._http.get("squid-api/v1/ai/settings/listChatModels", params=params) 135 return result.get("models", []) if result else []
List all AI chat models available to the application.
Includes both Squid-provided vendor models and any custom integration models configured for the app.
Arguments:
- include_deprecated: When True, deprecated vendor models are
included and marked with
replacedBy. Defaults to False.
Returns:
A list of
ModelIdSpecdicts, each withmodelId, an optionalintegrationId, and a human-readabledisplayName. Vendor models also carry adescription, and deprecated vendor models areplacedBywith the active model their calls are routed to.
137 async def list_embedding_models( 138 self, include_deprecated: bool = False 139 ) -> list[EmbeddingModelIdSpec]: 140 """List the embedding models a new knowledge base can be created on. 141 142 Includes Squid-provided vendor models and the app's custom integration 143 models. Exactly one entry carries ``isDefault``. 144 145 Args: 146 include_deprecated: When True, deprecated vendor models are 147 included and marked with ``replacedBy``. Defaults to False. 148 149 Returns: 150 A list of ``EmbeddingModelIdSpec`` dicts, each with ``modelId``, 151 ``displayName`` and ``source``, plus ``integrationId`` and 152 ``dimensions`` for integration models. 153 """ 154 params = {"includeDeprecated": "true"} if include_deprecated else None 155 result = await self._http.get("squid-api/v1/ai/settings/listEmbeddingModels", params=params) 156 return result.get("models", []) if result else []
List the embedding models a new knowledge base can be created on.
Includes Squid-provided vendor models and the app's custom integration
models. Exactly one entry carries isDefault.
Arguments:
- include_deprecated: When True, deprecated vendor models are
included and marked with
replacedBy. Defaults to False.
Returns:
A list of
EmbeddingModelIdSpecdicts, each withmodelId,displayNameandsource, plusintegrationIdanddimensionsfor integration models.
158 async def list_functions(self) -> list[AiFunctionMetadata]: 159 """List all AI functions registered for the application's deployed bundle. 160 161 Returns: 162 A list of ``AiFunctionMetadata`` dicts. Empty list if no functions 163 are registered. 164 """ 165 result = await self._http.get("squid-api/v1/ai/function/listFunctions") 166 return result.get("functions", []) if result else []
List all AI functions registered for the application's deployed bundle.
Returns:
A list of
AiFunctionMetadatadicts. Empty list if no functions are registered.
101class AiConnectedAgentMetadata(TypedDict): 102 """Metadata for a connected agent.""" 103 104 agentId: str 105 description: str
Metadata for a connected agent.
108class AiConnectedIntegrationMetadata(TypedDict, total=False): 109 """Metadata for a connected integration. 110 111 ``integrationId`` and ``integrationType`` are required by the platform API; 112 the remaining fields are optional. 113 """ 114 115 integrationId: str 116 """The ID of the connected integration. Required.""" 117 integrationType: str 118 """The integration type, e.g. 'hubspot', 'slack', 'api'. Required.""" 119 description: str 120 """Optional description used as the AI function description for the parent agent.""" 121 instructions: str 122 """Optional instructions for the connected integration agent, overriding the default.""" 123 functionsToUse: list[str] 124 """AI function IDs the agent may use. Omit for all functions; [] for none.""" 125 options: dict[str, Any] 126 """Additional integration options interpreted by Squid Core or connector AI functions.""" 127 connectedAsMcp: bool 128 """Treat this integration as an MCP server (API integrations with exposeAsMcpServer)."""
Metadata for a connected integration.
integrationId and integrationType are required by the platform API;
the remaining fields are optional.
Optional instructions for the connected integration agent, overriding the default.
131class AiConnectedKnowledgeBaseMetadata(TypedDict, total=False): 132 """Metadata for a connected knowledge base.""" 133 134 knowledgeBaseId: str 135 description: str 136 includeMetadata: bool
Metadata for a connected knowledge base.
834class AiContextFileOptions(TypedDict, total=False): 835 """Options for file context processing.""" 836 837 chunkOverlap: int 838 ragType: str 839 reuseChunkContext: bool 840 """Contextual RAG without GraphRAG only. When the new text starts with exactly the previously ingested 841 text, unchanged chunks keep their stored blurbs and only new chunks are sent to the LLM - until the text 842 has grown past twice the shortest text any reused blurb was written against, when every blurb is written 843 anew, as is a chunk that carries an image. A reused blurb was written against the shorter document; set 844 False when appended text can change the meaning of earlier text. Defaults to True."""
Options for file context processing.
Contextual RAG without GraphRAG only. When the new text starts with exactly the previously ingested text, unchanged chunks keep their stored blurbs and only new chunks are sent to the LLM - until the text has grown past twice the shortest text any reused blurb was written against, when every blurb is written anew, as is a chunk that carries an image. A reused blurb was written against the shorter document; set False when appended text can change the meaning of earlier text. Defaults to True.
792class AiContextTextOptions(TypedDict, total=False): 793 """Options for text context processing.""" 794 795 chunkOverlap: int 796 """Amount of chunk overlap in characters.""" 797 ragType: str 798 """The type of RAG to use.""" 799 reuseChunkContext: bool 800 """Contextual RAG without GraphRAG only. When the new text starts with exactly the previously ingested 801 text, unchanged chunks keep their stored blurbs and only new chunks are sent to the LLM - until the text 802 has grown past twice the shortest text any reused blurb was written against, when every blurb is written 803 anew, as is a chunk that carries an image. A reused blurb was written against the shorter document; set 804 False when appended text can change the meaning of earlier text. Defaults to True."""
Options for text context processing.
Contextual RAG without GraphRAG only. When the new text starts with exactly the previously ingested text, unchanged chunks keep their stored blurbs and only new chunks are sent to the LLM - until the text has grown past twice the shortest text any reused blurb was written against, when every blurb is written anew, as is a chunk that carries an image. A reused blurb was written against the shorter document; set False when appended text can change the meaning of earlier text. Defaults to True.
139class AiFileUrl(TypedDict, total=False): 140 """File URL to include in chat context.""" 141 142 id: str 143 type: str 144 purpose: str 145 url: str 146 description: str 147 fileName: str
File URL to include in chat context.
969class AiFunctionAttributes(TypedDict, total=False): 970 """Additional optional readonly metadata for an AI function.""" 971 972 integrationType: list[str] 973 """Types of integration this function is used for. Functions with a defined 974 'integrationType' require 'integrationId' to be passed as part of the function context."""
Additional optional readonly metadata for an AI function.
977class AiFunctionMetadata(TypedDict, total=False): 978 """Metadata describing an AI function available in the application. 979 980 Returned by :meth:`AiClient.list_functions`. 981 """ 982 983 serviceFunction: str 984 """The fully qualified name of the function ('ServiceName:functionName'). Required.""" 985 description: str 986 """Description of what the function does.""" 987 promptId: str 988 """Opaque ID of a registered prompt that supplies this function's description; 989 resolved server-side.""" 990 params: list[AiFunctionParam] 991 """Parameters that the function accepts. Required.""" 992 attributes: AiFunctionAttributes 993 """Additional attributes for the function.""" 994 categories: list[str] 995 """Categories this function belongs to.""" 996 internal: bool 997 """Whether this function is internal and not meant for direct use."""
Metadata describing an AI function available in the application.
Returned by AiClient.list_functions().
The fully qualified name of the function ('ServiceName:functionName'). Required.
952class AiFunctionParam(TypedDict, total=False): 953 """Defines the structure of a parameter for an AI function.""" 954 955 name: str 956 """Name of the parameter. Required.""" 957 description: str 958 """Description of the parameter's purpose. Required.""" 959 type: AiFunctionParamType 960 """Data type of the parameter. Required.""" 961 required: bool 962 """Indicates if the parameter is mandatory. Required.""" 963 enum: list[str] 964 """List of possible values for the parameter, if applicable.""" 965 schema: dict[str, Any] 966 """JSON Schema of an ``object`` parameter's value, which Squid validates every call against."""
Defines the structure of a parameter for an AI function.
760class AiKnowledgeBase(TypedDict, total=False): 761 """An AI knowledge base that can be attached to an AI agent. 762 763 Returned by :meth:`AiClient.list_knowledge_bases`. 764 """ 765 766 id: str 767 """The unique identifier of the knowledge base. Required.""" 768 appId: str 769 """The app ID that the knowledge base belongs to. Required.""" 770 description: str 771 """The user's description of the knowledge base. Required.""" 772 metadataFields: list[AiKnowledgeBaseMetadataField] 773 """Predefined metadata fields that can be used for filtering. Required.""" 774 embeddingModel: AiEmbeddingsModelSelection 775 """The embedding model used by this knowledge base. Required.""" 776 chatModel: AiChatModelSelection 777 """The model used when asking questions of this knowledge base. Required.""" 778 vectorDbType: VectorDbType 779 """The vector store backend the knowledge base reads/writes from. Set at creation 780 and immutable thereafter. Absent on older records.""" 781 graphRag: AiKnowledgeBaseGraphConfig 782 """Opt-in GraphRAG configuration. Only honored for ``vectorDbType: 'mongoAtlas'`` 783 knowledge bases; enables per-chunk entity/relationship extraction at ingest and 784 ``searchMode: 'graph'`` at query time.""" 785 externalSource: AiKnowledgeBaseExternalSource 786 """Binds the knowledge base to content that lives outside Squid. Such a knowledge base is 787 read-only. It is set by the integration whose ``knowledgeBaseId`` names the knowledge base.""" 788 updatedAt: str 789 """ISO 8601 timestamp of when the knowledge base was last updated. Required."""
An AI knowledge base that can be attached to an AI agent.
Returned by AiClient.list_knowledge_bases().
Predefined metadata fields that can be used for filtering. Required.
The embedding model used by this knowledge base. Required.
The model used when asking questions of this knowledge base. Required.
The vector store backend the knowledge base reads/writes from. Set at creation and immutable thereafter. Absent on older records.
Opt-in GraphRAG configuration. Only honored for vectorDbType: 'mongoAtlas'
knowledge bases; enables per-chunk entity/relationship extraction at ingest and
searchMode: 'graph' at query time.
Binds the knowledge base to content that lives outside Squid. Such a knowledge base is
read-only. It is set by the integration whose knowledgeBaseId names the knowledge base.
744class AiKnowledgeBaseExternalSource(TypedDict): 745 """Where the content of an external, read-only knowledge base lives. 746 747 Squid reads the source with the access the integration grants and never modifies it. 748 """ 749 750 type: str 751 """The type of the integration that serves the source.""" 752 integrationId: str 753 """The integration that holds the connection to the source.""" 754 traits: AiKnowledgeBaseExternalSourceTraits 755 """What Squid knows about the source whatever its type.""" 756 settings: dict[str, Any] 757 """How the integration's connector reads the source. Only that connector reads them."""
Where the content of an external, read-only knowledge base lives.
Squid reads the source with the access the integration grants and never modifies it.
717class AiKnowledgeBaseExternalSourceTraits(TypedDict): 718 """What Squid knows about an external source whatever its type. 719 720 The integration's connector reports it when the integration is saved. 721 """ 722 723 label: str 724 """A one-line name of the source for people and agents.""" 725 target: str 726 """What the integration reads in the source, such as an index name. Fixed once the knowledge 727 base is bound.""" 728 documentSecurity: Literal["none", "callerScopes", "callerToken"] 729 """How a read is restricted to what its caller may see. ``'none'``: no document-level 730 security. ``'callerScopes'``: a record is visible when it holds one of the scopes 731 ``accessControl.scopeResolver`` resolves for the caller. ``'callerToken'``: the source enforces 732 its own ACLs with the caller's token.""" 733 chunked: bool 734 """True when a document spans several records of the source.""" 735 embedsQueries: bool 736 """True when the source embeds the text of a vector query itself.""" 737 incrementalSync: bool 738 """True when the source records when each record last changed, so a sync reads only what 739 changed.""" 740 metadataFields: list[str] 741 """The source fields the knowledge base exposes as metadata."""
What Squid knows about an external source whatever its type.
The integration's connector reports it when the integration is saved.
What the integration reads in the source, such as an index name. Fixed once the knowledge base is bound.
How a read is restricted to what its caller may see. 'none': no document-level
security. 'callerScopes': a record is visible when it holds one of the scopes
accessControl.scopeResolver resolves for the caller. 'callerToken': the source enforces
its own ACLs with the caller's token.
651class AiKnowledgeBaseGraphConceptsConfig(TypedDict, total=False): 652 """Configuration of the graph's concept layer (facet taxonomies).""" 653 654 facets: Union[list[str], Literal["auto"]] 655 """Which metadata fields become value facets. ``'auto'`` (the default) profiles the KB's 656 context metadata and selects the categorical fields; an explicit list overrides 657 auto-selection; an empty list disables value facets.""" 658 pathFacets: list[AiKnowledgeBaseGraphPathFacetConfig] 659 """Explicit path facets, e.g. ``[{'field': 'folderPath', 'type': 'path'}]``. A path facet 660 always builds when its field has values, independent of ``facets``."""
Configuration of the graph's concept layer (facet taxonomies).
Which metadata fields become value facets. 'auto' (the default) profiles the KB's
context metadata and selects the categorical fields; an explicit list overrides
auto-selection; an empty list disables value facets.
Explicit path facets, e.g. [{'field': 'folderPath', 'type': 'path'}]. A path facet
always builds when its field has values, independent of facets.
675class AiKnowledgeBaseGraphConfig(_AiKnowledgeBaseGraphConfigRequired, total=False): 676 """Per-knowledge-base GraphRAG configuration. 677 678 Opt-in and mutable (unlike ``embeddingModel``/``vectorDbType``); only honored for 679 ``vectorDbType: 'mongoAtlas'`` knowledge bases. Enabling it on a knowledge base that 680 already has content backfills the graph automatically once the KB goes quiet. 681 682 On upsert the supplied value replaces the stored config rather than merging into it, 683 so include every key that should remain set. 684 """ 685 686 extractionModel: AiChatModelSelection 687 """Chat model used for per-chunk entity/relationship extraction. Defaults to the server's 688 graph model.""" 689 entityTypes: list[str] 690 """Optional domain taxonomy hint (entity types) injected into the extraction prompt.""" 691 extractionDepth: Literal["standard", "thorough"] 692 """How hard per-chunk extraction works: ``'standard'`` (the default) or ``'thorough'``, which allows 693 about 40 entities per chunk instead of 15 and runs at high reasoning effort on OpenAI extraction models: 694 more entities and relationships, a bigger graph (a listing yields ~40 entities per chunk) and about 1.5x 695 the extraction cost. A change reaches already-indexed content on the next ``full`` rebuild.""" 696 autoBuildDebounceMs: int 697 """Quiet window (milliseconds) after the last graph activity before the sweep auto-builds 698 the structure. Must be a positive integer. Defaults to the server's window (5 minutes).""" 699 autoBuildPaused: bool 700 """When true, the sweep starts no automatic build, entity resolution included: activity keeps 701 arming the build, and the first quiet window after the flag is cleared runs it. ``rebuild_graph`` 702 stays available. To hold only the structural build, use ``structuralBuildSchedule``. Defaults to 703 false.""" 704 structuralBuildSchedule: str 705 """When the sweep may start an automatic structural build: ``'debounced'`` (one quiet window 706 after activity), ``'off'`` (manual ``rebuild_graph`` only) or a 5-field cron expression. 707 Entity resolution keeps running either way. Omitted means the server's default.""" 708 structuralBuildTimeZone: str 709 """IANA time zone of a cron ``structuralBuildSchedule``. Omitted means the server's default (UTC).""" 710 structuralBuildCatchUpMs: int 711 """How long after a cron slot its structural build may still start (milliseconds); past it, the 712 build waits for the next slot. Omitted means the server's default (3 hours).""" 713 concepts: AiKnowledgeBaseGraphConceptsConfig 714 """Concept-layer (facet taxonomy) configuration. Omitted means ``facets: 'auto'``."""
Per-knowledge-base GraphRAG configuration.
Opt-in and mutable (unlike embeddingModel/vectorDbType); only honored for
vectorDbType: 'mongoAtlas' knowledge bases. Enabling it on a knowledge base that
already has content backfills the graph automatically once the KB goes quiet.
On upsert the supplied value replaces the stored config rather than merging into it, so include every key that should remain set.
Chat model used for per-chunk entity/relationship extraction. Defaults to the server's graph model.
Optional domain taxonomy hint (entity types) injected into the extraction prompt.
How hard per-chunk extraction works: 'standard' (the default) or 'thorough', which allows
about 40 entities per chunk instead of 15 and runs at high reasoning effort on OpenAI extraction models:
more entities and relationships, a bigger graph (a listing yields ~40 entities per chunk) and about 1.5x
the extraction cost. A change reaches already-indexed content on the next full rebuild.
Quiet window (milliseconds) after the last graph activity before the sweep auto-builds the structure. Must be a positive integer. Defaults to the server's window (5 minutes).
When true, the sweep starts no automatic build, entity resolution included: activity keeps
arming the build, and the first quiet window after the flag is cleared runs it. rebuild_graph
stays available. To hold only the structural build, use structuralBuildSchedule. Defaults to
false.
When the sweep may start an automatic structural build: 'debounced' (one quiet window
after activity), 'off' (manual rebuild_graph only) or a 5-field cron expression.
Entity resolution keeps running either way. Omitted means the server's default.
IANA time zone of a cron structuralBuildSchedule. Omitted means the server's default (UTC).
How long after a cron slot its structural build may still start (milliseconds); past it, the build waits for the next slot. Omitted means the server's default (3 hours).
Concept-layer (facet taxonomy) configuration. Omitted means facets: 'auto'.
889class AiKnowledgeBaseGraphFilter(TypedDict): 890 """Graph scope for a knowledge-base search: restricts results to the documents under one 891 concept of the KB's graph. Composes with every ``searchMode``. Requires ``graphRag.enabled``.""" 892 893 underConcept: str 894 """The concept to scope to: a facet nodeId (``facet_…`` — exact) or a concept name, 895 resolved server-side (exact, then alias, then similarity). An unresolvable ref fails with 896 ``CONCEPT_NOT_FOUND`` and the nearest matching concept names."""
Graph scope for a knowledge-base search: restricts results to the documents under one
concept of the KB's graph. Composes with every searchMode. Requires graphRag.enabled.
642class AiKnowledgeBaseGraphPathFacetConfig( 643 _AiKnowledgeBaseGraphPathFacetConfigRequired, total=False 644): 645 """A path facet: a deterministic tree built by splitting a hierarchical path field.""" 646 647 separator: str 648 """Path segment separator. Defaults to ``'/'``."""
A path facet: a deterministic tree built by splitting a hierarchical path field.
875class AiKnowledgeBaseGraphSearchOptions(TypedDict, total=False): 876 """Tuning for ``searchMode: 'graph'`` (GraphRAG) retrieval. Ignored for other search modes.""" 877 878 seedLimit: int 879 """Entities seeded via vector search before graph expansion. Default 8, max 25.""" 880 maxHops: int 881 """Number of hops to expand from each seed (traversal depth + 1). Default 2, max 3.""" 882 includeGraphContext: bool 883 """When True, the server attaches the traversed subgraph to the search response as 884 ``graphContext``. Default False. Read it via 885 :meth:`~squidcloud.ai.KnowledgeBaseClient.search_with_graph_context`; 886 :meth:`~squidcloud.ai.KnowledgeBaseClient.search` returns only the chunks."""
Tuning for searchMode: 'graph' (GraphRAG) retrieval. Ignored for other search modes.
When True, the server attaches the traversed subgraph to the search response as
graphContext. Default False. Read it via
~squidcloud.ai.KnowledgeBaseClient.search_with_graph_context();
~squidcloud.ai.KnowledgeBaseClient.search() returns only the chunks.
599class AiKnowledgeBaseMetadataField(TypedDict, total=False): 600 """Metadata field definition for a knowledge base.""" 601 602 name: str 603 dataType: str 604 required: bool 605 description: str
Metadata field definition for a knowledge base.
274class AiModelRoutingOptions(TypedDict): 275 """Lets a routing model pick which model of a ladder answers an ``ask``. 276 277 The routing model rates how demanding the question is (``simple``, ``moderate`` or ``complex``), 278 given the agent's instructions, and the ladder step for that rating serves it. Only single 279 questions are routed. 280 """ 281 282 models: NotRequired[list[Union[AiChatModelName, AiModelRoutingStep]]] 283 """The ladder, cheapest first: two or three distinct steps, each a vendor model name or a model 284 with its own effort. Omitted, the platform's fast, medium and capable chat models form the 285 ladder, at low, default and high effort.""" 286 routingModel: AiChatModelName 287 """The vendor model that rates the question.""" 288 instructions: NotRequired[str] 289 """How to rate questions, in plain language, up to 2000 characters. Replaces the default rule, 290 which takes the lower of two levels a question sits between."""
Lets a routing model pick which model of a ladder answers an ask.
The routing model rates how demanding the question is (simple, moderate or complex),
given the agent's instructions, and the ladder step for that rating serves it. Only single
questions are routed.
The ladder, cheapest first: two or three distinct steps, each a vendor model name or a model with its own effort. Omitted, the platform's fast, medium and capable chat models form the ladder, at low, default and high effort.
297class AiModelRoutingResult(TypedDict, total=False): 298 """Which ladder model answered an ``ask``, the routing model's rating, and what the routing call cost.""" 299 300 model: AiChatModelName 301 """The ladder model the request was sent to. A ``backupModel`` may still have served the answer.""" 302 reasoningEffort: str 303 """The reasoning effort the chosen model ran at, resolved to a level the model accepts: the step's 304 own effort, else the request's or agent's, else the platform ladder step's. Absent when the model 305 ran at its default.""" 306 routingModel: AiChatModelName 307 """The model that rated the question.""" 308 level: Literal["simple", "moderate", "complex"] 309 """How demanding the routing model rated the question.""" 310 reason: str 311 """The routing model's one-line justification of the rating.""" 312 inputTokens: int 313 """Input tokens of the routing call.""" 314 outputTokens: int 315 """Output tokens of the routing call.""" 316 costUsd: float 317 """Cost of the routing call in USD, when known."""
Which ladder model answered an ask, the routing model's rating, and what the routing call cost.
The ladder model the request was sent to. A backupModel may still have served the answer.
261class AiModelRoutingStep(TypedDict): 262 """One step of a routing ladder: a model with its own reasoning effort. 263 264 A bare model name in the ladder runs at the request's or agent's effort, else the model's default. 265 """ 266 267 model: AiChatModelName 268 """The vendor model of the step.""" 269 reasoningEffort: NotRequired[AiReasoningEffort] 270 """The effort the step runs at, resolved to a level the model accepts. Overrides the request's and 271 agent's effort."""
One step of a routing ladder: a model with its own reasoning effort.
A bare model name in the ladder runs at the request's or agent's effort, else the model's default.
209class AiPiiOptions(TypedDict, total=False): 210 """Inspects selected boundaries for PII, secrets and custom sensitive data.""" 211 212 onDetect: Literal["off", "reject", "monitor", "redact"] 213 """Reject blocks detections; monitor warns; redact replaces values. Defaults to off.""" 214 entities: list[str] 215 """PII kinds to inspect, optionally including 'secret' for credentials and keys.""" 216 customRules: list[str] 217 """App-specific PII described in plain language, screened by classifierModel.""" 218 classifierModel: AiChatModelSelection | None 219 """Classifier override. None restores the default model.""" 220 allowList: list[str] 221 scopes: list[Literal["input", "context", "output", "toolArguments"]] 222 reasoningEffort: AiReasoningEffort 223 timeoutMs: int 224 """Literal values that never count as PII."""
Inspects selected boundaries for PII, secrets and custom sensitive data.
Reject blocks detections; monitor warns; redact replaces values. Defaults to off.
Classifier override. None restores the default model.
196class AiPromptInjectionOptions(AiSecurityClassifierOptions, total=False): 197 """Detects instruction overrides in user prompts and retrieved text.""" 198 199 onDetect: Literal["off", "monitor", "block"] 200 scopes: list[Literal["input", "context"]]
Detects instruction overrides in user prompts and retrieved text.
479class AiQueryAnalyzeResultsOptions(TypedDict, total=False): 480 """Options for the result-analysis stage of AI query.""" 481 482 disabled: bool 483 """When true, skip analysis and return raw results only.""" 484 enableCodeInterpreter: bool 485 """Enable code interpreter mode (default false).""" 486 aiOptions: AiChatOptions 487 """Customize AI agent behavior used by the stage.""" 488 agentId: AiAgentId 489 """If set, use this agent to analyze results and produce the final answer."""
Options for the result-analysis stage of AI query.
465class AiQueryGenerateQueryOptions(TypedDict, total=False): 466 """Options for the query-generation stage of AI query.""" 467 468 aiOptions: AiChatOptions 469 """Customize AI agent behavior used by the stage.""" 470 maxErrorCorrections: int 471 """Number of retries due to errors in a generated AI query (default 2).""" 472 agentId: AiAgentId 473 """If set, use this agent to generate the query.""" 474 allowClarification: bool 475 """When true, allow the AI to ask a clarifying question instead of 476 generating a query for ambiguous prompts (default false)."""
Options for the query-generation stage of AI query.
501class AiQueryOptions(TypedDict, total=False): 502 """Options for configuring AI query execution. 503 504 Mirrors ``AiQueryOptions`` from the TypeScript SDK. All fields optional. 505 """ 506 507 instructions: str 508 """Custom instructions applied to all stages unless overridden per-stage.""" 509 enableRawResults: bool 510 """Enable raw results output.""" 511 largeResultsAsFiles: bool 512 """Return results too large to analyze inline as files instead of analyzing them.""" 513 selectCollectionsOptions: AiQuerySelectCollectionsOptions 514 """Collection-selection stage options.""" 515 generateQueryOptions: AiQueryGenerateQueryOptions 516 """Query-generation stage options.""" 517 analyzeResultsOptions: AiQueryAnalyzeResultsOptions 518 """Result-analysis stage options.""" 519 sessionContext: AiSessionContext 520 """Session information (``agentId`` may be omitted).""" 521 memoryOptions: AiAgentMemoryOptions 522 """Memory/session configuration.""" 523 generateQueriesOnly: bool 524 """If true, return generated queries without executing or analyzing them.""" 525 validateWithAiOptions: AiQueryValidateWithAiOptions 526 """Optional AI validation of generated queries.""" 527 usageAttribution: AiUsageAttribution 528 """The agent ask this query runs for; its model usage is reported under that ask's tags."""
Options for configuring AI query execution.
Mirrors AiQueryOptions from the TypeScript SDK. All fields optional.
Return results too large to analyze inline as files instead of analyzing them.
The agent ask this query runs for; its model usage is reported under that ask's tags.
454class AiQuerySelectCollectionsOptions(TypedDict, total=False): 455 """Options for the collection-selection stage of AI query.""" 456 457 collectionsToUse: list[str] 458 """Restrict query to these collections. Defaults to all collections.""" 459 runMode: AiQueryCollectionsSelectionRunMode 460 """Stage behavior: 'default', 'force', or 'disable'.""" 461 aiOptions: AiChatOptions 462 """Customize AI agent behavior used by the stage."""
Options for the collection-selection stage of AI query.
492class AiQueryValidateWithAiOptions(TypedDict, total=False): 493 """Options for AI-based validation of generated queries.""" 494 495 enabled: bool 496 """Whether AI validation is enabled.""" 497 aiOptions: AiChatOptions 498 """Defaults to the same model used for query generation."""
Options for AI-based validation of generated queries.
187class AiSecurityClassifierOptions(TypedDict, total=False): 188 """Classifier configuration. Omitted models inherit the detector's platform default.""" 189 190 model: AiChatModelSelection 191 reasoningEffort: AiReasoningEffort 192 timeoutMs: int 193 customRules: list[str]
Classifier configuration. Omitted models inherit the detector's platform default.
425class AiSessionContext(TypedDict, total=False): 426 """Session context for AI query execution. 427 428 Mirrors the TypeScript ``AiSessionContext`` type. All fields optional 429 here because the query endpoint accepts a partial context (``agentId`` 430 may be omitted). 431 """ 432 433 clientId: str 434 agentId: str 435 jobId: str 436 metricAnnotations: dict[str, str] 437 """Metric annotations of the root request, reported on nested AI usage."""
Session context for AI query execution.
Mirrors the TypeScript AiSessionContext type. All fields optional
here because the query endpoint accepts a partial context (agentId
may be omitted).
150class AiStructuredOutputFormat(TypedDict): 151 """Structured output format for JSON responses.""" 152 153 type: Literal["json_schema"] 154 schema: dict[str, Any]
Structured output format for JSON responses.
440class AiUsageAttribution(TypedDict, total=False): 441 """Identifies the agent ask that AI usage is reported under. 442 443 Mirrors the TypeScript ``AiUsageAttribution`` type. 444 """ 445 446 jobId: str 447 """Job ID of the ask, reported as the ``aiJobId`` metric tag. Required.""" 448 agentId: str 449 """ID of the agent that ran the ask, reported as the ``aiProfile`` metric tag. Required.""" 450 metricAnnotations: dict[str, str] 451 """Metric annotations of the ask, reported as ``annotation.<key>`` metric tags."""
Identifies the agent ask that AI usage is reported under.
Mirrors the TypeScript AiUsageAttribution type.
1134class AudioClient: 1135 """Audio transcription and speech synthesis. 1136 1137 Obtained via :meth:`AiClient.audio`. 1138 1139 Example:: 1140 1141 text = await squid.ai().audio().transcribe(audio_bytes) 1142 speech = await squid.ai().audio().create_speech("Hello!", options={"voice": "nova"}) 1143 """ 1144 1145 def __init__(self, http: HttpTransport) -> None: 1146 self._http = http 1147 1148 async def transcribe( 1149 self, 1150 audio_data: bytes, 1151 filename: str = "audio.wav", 1152 content_type: str = "audio/wav", 1153 *, 1154 options: dict[str, Any] | None = None, 1155 ) -> str: 1156 """Transcribe audio to text. 1157 1158 Args: 1159 audio_data: The audio file content as bytes. 1160 filename: The filename (used in the multipart upload). 1161 content_type: The MIME type of the audio file. 1162 options: Provider-specific transcription options. 1163 1164 Returns: 1165 The transcribed text. 1166 """ 1167 form_data: dict[str, str] = { 1168 "optionsJson": json.dumps(options or {}), 1169 } 1170 result = await self._http.post_form( 1171 "squid-api/v1/ai/audio/transcribe", 1172 data=form_data, 1173 files=[("file", (filename, audio_data, content_type))], 1174 ) 1175 return result if isinstance(result, str) else str(result) 1176 1177 async def create_speech( 1178 self, 1179 text: str, 1180 options: AiAudioCreateSpeechOptions, 1181 ) -> bytes: 1182 """Generate speech audio from text. 1183 1184 Args: 1185 text: The text to convert to speech. 1186 options: Speech generation options. See :class:`AiAudioCreateSpeechOptions`. 1187 Required keys: ``modelName`` (e.g., ``'tts-1'``), ``voice`` 1188 (e.g., ``'nova'``, ``'alloy'``). 1189 1190 Returns: 1191 Raw audio file bytes (e.g., MP3 format by default). 1192 1193 Example:: 1194 1195 audio_data = ( 1196 await squid.ai() 1197 .audio() 1198 .create_speech( 1199 "Hello!", 1200 options={ 1201 "modelName": "tts-1", 1202 "voice": "nova", 1203 }, 1204 ) 1205 ) 1206 with open("speech.mp3", "wb") as f: 1207 f.write(audio_data) 1208 """ 1209 return await self._http.post( 1210 "squid-api/v1/ai/audio/createSpeech", 1211 {"input": text, "options": options}, 1212 )
Audio transcription and speech synthesis.
Obtained via AiClient.audio().
Example::
text = await squid.ai().audio().transcribe(audio_bytes)
speech = await squid.ai().audio().create_speech("Hello!", options={"voice": "nova"})
1148 async def transcribe( 1149 self, 1150 audio_data: bytes, 1151 filename: str = "audio.wav", 1152 content_type: str = "audio/wav", 1153 *, 1154 options: dict[str, Any] | None = None, 1155 ) -> str: 1156 """Transcribe audio to text. 1157 1158 Args: 1159 audio_data: The audio file content as bytes. 1160 filename: The filename (used in the multipart upload). 1161 content_type: The MIME type of the audio file. 1162 options: Provider-specific transcription options. 1163 1164 Returns: 1165 The transcribed text. 1166 """ 1167 form_data: dict[str, str] = { 1168 "optionsJson": json.dumps(options or {}), 1169 } 1170 result = await self._http.post_form( 1171 "squid-api/v1/ai/audio/transcribe", 1172 data=form_data, 1173 files=[("file", (filename, audio_data, content_type))], 1174 ) 1175 return result if isinstance(result, str) else str(result)
Transcribe audio to text.
Arguments:
- audio_data: The audio file content as bytes.
- filename: The filename (used in the multipart upload).
- content_type: The MIME type of the audio file.
- options: Provider-specific transcription options.
Returns:
The transcribed text.
1177 async def create_speech( 1178 self, 1179 text: str, 1180 options: AiAudioCreateSpeechOptions, 1181 ) -> bytes: 1182 """Generate speech audio from text. 1183 1184 Args: 1185 text: The text to convert to speech. 1186 options: Speech generation options. See :class:`AiAudioCreateSpeechOptions`. 1187 Required keys: ``modelName`` (e.g., ``'tts-1'``), ``voice`` 1188 (e.g., ``'nova'``, ``'alloy'``). 1189 1190 Returns: 1191 Raw audio file bytes (e.g., MP3 format by default). 1192 1193 Example:: 1194 1195 audio_data = ( 1196 await squid.ai() 1197 .audio() 1198 .create_speech( 1199 "Hello!", 1200 options={ 1201 "modelName": "tts-1", 1202 "voice": "nova", 1203 }, 1204 ) 1205 ) 1206 with open("speech.mp3", "wb") as f: 1207 f.write(audio_data) 1208 """ 1209 return await self._http.post( 1210 "squid-api/v1/ai/audio/createSpeech", 1211 {"input": text, "options": options}, 1212 )
Generate speech audio from text.
Arguments:
- text: The text to convert to speech.
- options: Speech generation options. See
AiAudioCreateSpeechOptions. Required keys:modelName(e.g.,'tts-1'),voice(e.g.,'nova','alloy').
Returns:
Raw audio file bytes (e.g., MP3 format by default).
Example::
audio_data = (
await squid.ai()
.audio()
.create_speech(
"Hello!",
options={
"modelName": "tts-1",
"voice": "nova",
},
)
)
with open("speech.mp3", "wb") as f:
f.write(audio_data)
1106class CreatePdfDimensionsOptions(TypedDict): 1107 """PDF output options by custom dimensions.""" 1108 1109 type: Literal["dimensions"] 1110 width: int 1111 """Width in pixels.""" 1112 height: int 1113 """Height in pixels."""
PDF output options by custom dimensions.
1087class CreatePdfFormatOptions(TypedDict): 1088 """PDF output options by format.""" 1089 1090 type: Literal["format"] 1091 format: Literal[ 1092 "letter", 1093 "legal", 1094 "tabloid", 1095 "ledger", 1096 "a0", 1097 "a1", 1098 "a2", 1099 "a3", 1100 "a4", 1101 "a5", 1102 "a6", 1103 ]
PDF output options by format.
68class EmbeddingModelIdSpec(TypedDict, total=False): 69 """An embedding model a new knowledge base can be created on. 70 71 Returned by :meth:`AiClient.list_embedding_models`. 72 """ 73 74 modelId: str 75 """The embedding model ID used for API calls. Required.""" 76 integrationId: str 77 """The integration ID if this model comes from an integration. Absent for Squid-provided models.""" 78 dimensions: int 79 """The embedding dimensions, present for integration-based models.""" 80 displayName: str 81 """Human-readable display name for the model. Required.""" 82 source: AiModelSource 83 """Where the model comes from: 'vendor' (Squid-provided) or 'connector' (an integration 84 configured on the app). Required.""" 85 replacedBy: str 86 """Set only on a deprecated vendor model, listed on request: the model a new knowledge base 87 asking for this one is created on. Absent for active models.""" 88 isDefault: bool 89 """True on exactly one entry of a non-empty list: the model to create on with no preference."""
An embedding model a new knowledge base can be created on.
Returned by AiClient.list_embedding_models().
The integration ID if this model comes from an integration. Absent for Squid-provided models.
Where the model comes from: 'vendor' (Squid-provided) or 'connector' (an integration configured on the app). Required.
1119class ExtractDataFromDocumentOptions(TypedDict, total=False): 1120 """Options for document data extraction.""" 1121 1122 extractImages: bool 1123 """Whether to extract embedded images. Defaults to True.""" 1124 imageMinSizePixels: int 1125 """Minimum image size to extract.""" 1126 pageIndexes: list[int] 1127 """Specific pages to extract (0-based).""" 1128 preferredExtractionMethod: str 1129 discardOriginalFile: bool
Options for document data extraction.
17class ExtractionClient: 18 """Document extraction and PDF creation.""" 19 20 def __init__(self, http: HttpTransport) -> None: 21 self._http = http 22 23 async def create_pdf_from_html( 24 self, 25 inner_html: str, 26 *, 27 title: str | None = None, 28 css_url: str | None = None, 29 output_options: CreatePdfOutputOptions | None = None, 30 ) -> dict: 31 """Create a PDF from HTML content. 32 33 Returns CreatePdfResponse with 'url' and 'fileName'. 34 """ 35 body: dict[str, Any] = {"type": "html", "innerHtml": inner_html} 36 if title is not None: 37 body["title"] = title 38 if css_url is not None: 39 body["cssUrl"] = css_url 40 if output_options is not None: 41 body["outputOptions"] = output_options 42 return await self._http.post("squid-api/v1/extraction/createPdf", body) 43 44 async def create_pdf_from_url( 45 self, 46 url: str, 47 *, 48 title: str | None = None, 49 output_options: CreatePdfOutputOptions | None = None, 50 ) -> dict: 51 """Create a PDF from a URL. 52 53 Returns CreatePdfResponse with 'url' and 'fileName'. 54 """ 55 body: dict[str, Any] = {"type": "url", "url": url} 56 if title is not None: 57 body["title"] = title 58 if output_options is not None: 59 body["outputOptions"] = output_options 60 return await self._http.post("squid-api/v1/extraction/createPdf", body) 61 62 async def extract_data_from_document_url( 63 self, 64 url: str, 65 options: ExtractDataFromDocumentOptions | None = None, 66 ) -> dict: 67 """Extract structured data from a document URL. 68 69 Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'. 70 """ 71 body: dict[str, Any] = {"url": url} 72 if options is not None: 73 body["options"] = options 74 return await self._http.post("squid-api/v1/extraction/extractDataFromDocumentUrl", body) 75 76 async def extract_data_from_document_file( 77 self, 78 file_data: bytes, 79 filename: str, 80 content_type: str = "application/pdf", 81 options: ExtractDataFromDocumentOptions | None = None, 82 ) -> dict: 83 """Extract structured data from a document file. 84 85 Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'. 86 """ 87 request: dict[str, Any] = {} 88 if options is not None: 89 request["options"] = options 90 form_data = {"request": json.dumps(request)} 91 92 return await self._http.post_form( 93 "squid-api/v1/extraction/extractDataFromDocumentFile", 94 data=form_data, 95 files=[("file", (filename, file_data, content_type))], 96 )
Document extraction and PDF creation.
23 async def create_pdf_from_html( 24 self, 25 inner_html: str, 26 *, 27 title: str | None = None, 28 css_url: str | None = None, 29 output_options: CreatePdfOutputOptions | None = None, 30 ) -> dict: 31 """Create a PDF from HTML content. 32 33 Returns CreatePdfResponse with 'url' and 'fileName'. 34 """ 35 body: dict[str, Any] = {"type": "html", "innerHtml": inner_html} 36 if title is not None: 37 body["title"] = title 38 if css_url is not None: 39 body["cssUrl"] = css_url 40 if output_options is not None: 41 body["outputOptions"] = output_options 42 return await self._http.post("squid-api/v1/extraction/createPdf", body)
Create a PDF from HTML content.
Returns CreatePdfResponse with 'url' and 'fileName'.
44 async def create_pdf_from_url( 45 self, 46 url: str, 47 *, 48 title: str | None = None, 49 output_options: CreatePdfOutputOptions | None = None, 50 ) -> dict: 51 """Create a PDF from a URL. 52 53 Returns CreatePdfResponse with 'url' and 'fileName'. 54 """ 55 body: dict[str, Any] = {"type": "url", "url": url} 56 if title is not None: 57 body["title"] = title 58 if output_options is not None: 59 body["outputOptions"] = output_options 60 return await self._http.post("squid-api/v1/extraction/createPdf", body)
Create a PDF from a URL.
Returns CreatePdfResponse with 'url' and 'fileName'.
62 async def extract_data_from_document_url( 63 self, 64 url: str, 65 options: ExtractDataFromDocumentOptions | None = None, 66 ) -> dict: 67 """Extract structured data from a document URL. 68 69 Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'. 70 """ 71 body: dict[str, Any] = {"url": url} 72 if options is not None: 73 body["options"] = options 74 return await self._http.post("squid-api/v1/extraction/extractDataFromDocumentUrl", body)
Extract structured data from a document URL.
Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'.
76 async def extract_data_from_document_file( 77 self, 78 file_data: bytes, 79 filename: str, 80 content_type: str = "application/pdf", 81 options: ExtractDataFromDocumentOptions | None = None, 82 ) -> dict: 83 """Extract structured data from a document file. 84 85 Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'. 86 """ 87 request: dict[str, Any] = {} 88 if options is not None: 89 request["options"] = options 90 form_data = {"request": json.dumps(request)} 91 92 return await self._http.post_form( 93 "squid-api/v1/extraction/extractDataFromDocumentFile", 94 data=form_data, 95 files=[("file", (filename, file_data, content_type))], 96 )
Extract structured data from a document file.
Returns ExtractDataFromDocumentResponse with 'pages' and optional 'longTermStoragePath'.
847class FileContextRequest(TypedDict, total=False): 848 """Request to upsert a file context.""" 849 850 contextId: str 851 type: Literal["file"] 852 metadata: dict[str, Any] 853 extractImages: bool 854 """Whether to extract and describe images in the file. Defaults to True. 855 856 This is the opposite of the text context default, which is False: a file's charts and 857 scanned pages carry content its text layer does not, while images referenced from pasted 858 markdown/HTML are usually layout chrome. 859 """ 860 imageMinSizePixels: int 861 imageExtractionModel: AiChatModelSelection 862 options: AiContextFileOptions 863 preferredExtractionMethod: str 864 discardOriginalFile: bool 865 scopes: list[str] 866 """Access scopes granting read access to this context. Only meaningful on a knowledge base 867 with ``accessControl.mode: 'enforced'``. Omitted on a re-ingest keeps existing scopes; an 868 empty list makes the context visible to every caller. 869 """
Request to upsert a file context.
Whether to extract and describe images in the file. Defaults to True.
This is the opposite of the text context default, which is False: a file's charts and scanned pages carry content its text layer does not, while images referenced from pasted markdown/HTML are usually layout chrome.
1019class FluxOptions(TypedDict, total=False): 1020 """Options for Flux image generation.""" 1021 1022 modelName: Literal["flux-pro-1.1", "flux-kontext-pro"] 1023 width: int 1024 """Must be multiple of 32, min 256, max 1440.""" 1025 height: int 1026 """Must be multiple of 32, min 256, max 1440.""" 1027 prompt_upsampling: bool 1028 seed: int 1029 safety_tolerance: int 1030 """1 (strict) to 5 (permissive)."""
Options for Flux image generation.
1003class GptImageOptions(TypedDict, total=False): 1004 """Options for OpenAI gpt-image-* family image generation.""" 1005 1006 modelName: Literal[ 1007 "gpt-image-1", 1008 "gpt-image-1-mini", 1009 "gpt-image-1.5", 1010 "gpt-image-2", 1011 "gpt-image-2-2026-04-21", 1012 "chatgpt-image-latest", 1013 ] 1014 quality: Literal["auto", "high", "medium", "low"] 1015 size: Literal["1024x1024", "1024x1536", "1536x1024", "auto"] 1016 numberOfImagesToGenerate: int
Options for OpenAI gpt-image-* family image generation.
172class GuardrailsOptions(TypedDict, total=False): 173 """Guardrail options for agent responses.""" 174 175 custom: str 176 """A custom guardrail instruction.""" 177 disablePii: bool 178 """Disables personally identifiable information if true.""" 179 professionalTone: bool 180 """Enforces a professional tone if true.""" 181 offTopicAnswers: bool 182 """Prevents off-topic answers if true.""" 183 disableProfanity: bool 184 """Disables profanity if true."""
Guardrail options for agent responses.
1060class ImageClient: 1061 """Image generation and processing. 1062 1063 Supports DALL-E, Stable Diffusion Core, and Flux models. 1064 1065 Obtained via :meth:`AiClient.image`. 1066 1067 Example:: 1068 1069 image_url = ( 1070 await squid.ai() 1071 .image() 1072 .generate( 1073 "a cat astronaut on the moon", 1074 options={"modelName": "gpt-image-1", "quality": "high"}, 1075 ) 1076 ) 1077 """ 1078 1079 def __init__(self, http: HttpTransport) -> None: 1080 self._http = http 1081 1082 async def generate( 1083 self, 1084 prompt: str, 1085 options: ImageGenerateOptions | None = None, 1086 ) -> str: 1087 """Generate an image from a text prompt. 1088 1089 Args: 1090 prompt: A text description of the image to generate. 1091 options: Provider-specific generation options. Use one of: 1092 - :class:`GptImageOptions`: ``{'modelName': 'gpt-image-1', 'quality': 'high', 'size': '1024x1024'}`` 1093 - :class:`FluxOptions`: ``{'modelName': 'flux-pro-1.1', 'width': 1024, 'height': 768}`` 1094 - :class:`StableDiffusionOptions`: ``{'modelName': 'stable-diffusion-core', 'aspectRatio': '16:9'}`` 1095 1096 Returns: 1097 The URL of the generated image. 1098 """ 1099 result = await self._http.post( 1100 "squid-api/v1/ai/image/generate", 1101 {"prompt": prompt, "options": options or {}}, 1102 ) 1103 return result if isinstance(result, str) else str(result) 1104 1105 async def remove_background( 1106 self, 1107 image_data: bytes, 1108 filename: str = "image.png", 1109 content_type: str = "image/png", 1110 ) -> str: 1111 """Remove the background from an image. 1112 1113 Args: 1114 image_data: The image file content as bytes. 1115 filename: The filename (used in the multipart upload). 1116 content_type: The MIME type of the image. 1117 1118 Returns: 1119 The URL of the processed image with the background removed. 1120 """ 1121 result = await self._http.post_form( 1122 "squid-api/v1/ai/image/removeBackground", 1123 data={}, 1124 files=[("file", (filename, image_data, content_type))], 1125 ) 1126 return result if isinstance(result, str) else str(result)
Image generation and processing.
Supports DALL-E, Stable Diffusion Core, and Flux models.
Obtained via AiClient.image().
Example::
image_url = (
await squid.ai()
.image()
.generate(
"a cat astronaut on the moon",
options={"modelName": "gpt-image-1", "quality": "high"},
)
)
1082 async def generate( 1083 self, 1084 prompt: str, 1085 options: ImageGenerateOptions | None = None, 1086 ) -> str: 1087 """Generate an image from a text prompt. 1088 1089 Args: 1090 prompt: A text description of the image to generate. 1091 options: Provider-specific generation options. Use one of: 1092 - :class:`GptImageOptions`: ``{'modelName': 'gpt-image-1', 'quality': 'high', 'size': '1024x1024'}`` 1093 - :class:`FluxOptions`: ``{'modelName': 'flux-pro-1.1', 'width': 1024, 'height': 768}`` 1094 - :class:`StableDiffusionOptions`: ``{'modelName': 'stable-diffusion-core', 'aspectRatio': '16:9'}`` 1095 1096 Returns: 1097 The URL of the generated image. 1098 """ 1099 result = await self._http.post( 1100 "squid-api/v1/ai/image/generate", 1101 {"prompt": prompt, "options": options or {}}, 1102 ) 1103 return result if isinstance(result, str) else str(result)
Generate an image from a text prompt.
Arguments:
- prompt: A text description of the image to generate.
- options: Provider-specific generation options. Use one of:
GptImageOptions:{'modelName': 'gpt-image-1', 'quality': 'high', 'size': '1024x1024'}FluxOptions:{'modelName': 'flux-pro-1.1', 'width': 1024, 'height': 768}StableDiffusionOptions:{'modelName': 'stable-diffusion-core', 'aspectRatio': '16:9'}
Returns:
The URL of the generated image.
1105 async def remove_background( 1106 self, 1107 image_data: bytes, 1108 filename: str = "image.png", 1109 content_type: str = "image/png", 1110 ) -> str: 1111 """Remove the background from an image. 1112 1113 Args: 1114 image_data: The image file content as bytes. 1115 filename: The filename (used in the multipart upload). 1116 content_type: The MIME type of the image. 1117 1118 Returns: 1119 The URL of the processed image with the background removed. 1120 """ 1121 result = await self._http.post_form( 1122 "squid-api/v1/ai/image/removeBackground", 1123 data={}, 1124 files=[("file", (filename, image_data, content_type))], 1125 ) 1126 return result if isinstance(result, str) else str(result)
Remove the background from an image.
Arguments:
- image_data: The image file content as bytes.
- filename: The filename (used in the multipart upload).
- content_type: The MIME type of the image.
Returns:
The URL of the processed image with the background removed.
608class IntegrationEmbeddingModelSpec(TypedDict): 609 """Specifies an embedding model from a specific integration.""" 610 611 integrationId: str 612 """The ID of the integration providing the embedding model.""" 613 model: str 614 """The model name as recognized by the provider.""" 615 dimensions: int 616 """The number of dimensions in the embedding vector output."""
Specifies an embedding model from a specific integration.
31class IntegrationModelSpec(TypedDict): 32 """Specifies a model from a specific integration.""" 33 34 integrationId: str 35 model: str
Specifies a model from a specific integration.
1244class KnowledgeBaseAuditLogEntry(TypedDict): 1245 """One audited search of a knowledge base that enforces access control. Dates are ISO strings.""" 1246 1247 source: KnowledgeBaseAuditLogSource 1248 agentId: NotRequired[str] 1249 jobId: NotRequired[str] 1250 prompt: str 1251 searchMode: str 1252 scopes: list[str] 1253 contextIds: list[str] 1254 chunkCount: int 1255 durationMs: int 1256 tags: dict[str, str] 1257 createdAt: str
One audited search of a knowledge base that enforces access control. Dates are ISO strings.
1234class KnowledgeBaseAuditLogFilter(TypedDict, total=False): 1235 """Filters of a knowledge-base audit log listing. Dates are ISO strings.""" 1236 1237 agentId: str 1238 jobId: str 1239 source: KnowledgeBaseAuditLogSource 1240 createdAfter: str 1241 createdBefore: str
Filters of a knowledge-base audit log listing. Dates are ISO strings.
520class KnowledgeBaseClient: 521 """Operations on a single knowledge base. 522 523 Provides methods for managing knowledge base configuration, upserting 524 and searching text/file contexts, and retrieving individual contexts. 525 526 Obtained via :meth:`AiClient.knowledge_base`. 527 528 Example:: 529 530 kb = squid.ai().knowledge_base("my-kb") 531 await kb.upsert(description="Product documentation") 532 await kb.upsert_contexts( 533 [ 534 { 535 "contextId": "doc-1", 536 "type": "text", 537 "title": "Getting Started", 538 "text": "Welcome to our product...", 539 } 540 ] 541 ) 542 results = await kb.search("How do I get started?") 543 """ 544 545 def __init__(self, http: HttpTransport, kb_id: str) -> None: 546 self._http = http 547 self._kb_id = kb_id 548 549 async def get(self) -> dict | None: 550 """Get the knowledge base details. 551 552 Returns: 553 An ``AiKnowledgeBase`` dict with keys: ``id``, ``appId``, 554 ``description``, ``metadataFields``, ``embeddingModel``, 555 ``chatModel``, ``updatedAt``. Returns ``None`` if not found. 556 """ 557 return await self._http.get(f"squid-api/v1/ai/knowledge-base/get/{self._kb_id}") 558 559 async def upsert( 560 self, 561 *, 562 description: str | None = None, 563 metadata_fields: list[AiKnowledgeBaseMetadataField] | None = None, 564 embedding_model: str | None = None, 565 chat_model: AiChatModelSelection | None = None, 566 name: str | None = None, 567 vector_db_type: VectorDbType | None = None, 568 graph_rag: AiKnowledgeBaseGraphConfig | None = None, 569 ) -> None: 570 """Create or update the knowledge base. 571 572 Args: 573 description: Description of the knowledge base's content. 574 metadata_fields: Schema for metadata fields used in filtering. 575 Each field: ``{'name': str, 'dataType': str, 'required': bool, 'description'?: str}``. 576 embedding_model: The embedding model name for vectorization. 577 Required when creating a new knowledge base. 578 chat_model: The LLM model for answering questions over this KB. 579 name: Display name for the knowledge base. 580 vector_db_type: The vector store backend. Set at creation (defaulting to the 581 server's default) and immutable thereafter. The knowledge graph requires 582 ``'mongoAtlas'``. 583 graph_rag: Opt-in GraphRAG configuration (``{'enabled': True, ...}``). Only 584 honored on ``'mongoAtlas'`` knowledge bases; mutable, unlike 585 ``vector_db_type``. The value replaces the stored config rather than 586 merging into it. See :class:`AiKnowledgeBaseGraphConfig`. 587 """ 588 kb: dict[str, Any] = {"id": self._kb_id} 589 if description is not None: 590 kb["description"] = description 591 if metadata_fields is not None: 592 kb["metadataFields"] = metadata_fields 593 if embedding_model is not None: 594 kb["embeddingModel"] = embedding_model 595 if chat_model is not None: 596 kb["chatModel"] = chat_model 597 if name is not None: 598 kb["name"] = name 599 if vector_db_type is not None: 600 kb["vectorDbType"] = vector_db_type 601 if graph_rag is not None: 602 kb["graphRag"] = graph_rag 603 await self._http.post("squid-api/v1/ai/knowledge-base/upsert", {"knowledgeBase": kb}) 604 605 async def delete(self) -> None: 606 """Delete the knowledge base and all its contexts permanently.""" 607 await self._http.post("squid-api/v1/ai/knowledge-base/delete", {"id": self._kb_id}) 608 609 # --- Contexts --- 610 611 async def get_context( 612 self, context_id: str, *, truncate_text_after: int | None = None 613 ) -> dict | None: 614 """Get a specific context entry. 615 616 Args: 617 context_id: The unique context identifier. 618 truncate_text_after: The number of characters after which the context's 619 text is truncated. Pass ``0`` to return an empty text. 620 621 Returns: 622 An ``AiKnowledgeBaseContext`` dict with keys: ``id``, ``appId``, 623 ``knowledgeBaseId``, ``createdAt``, ``updatedAt``, ``type``, 624 ``title``, ``text``, ``preview``, ``sizeBytes``, ``metadata``, 625 ``requestConfig``. Returns ``None`` if not found. 626 """ 627 params = ( 628 {"truncateTextAfter": str(truncate_text_after)} 629 if truncate_text_after is not None 630 else None 631 ) 632 return await self._http.get( 633 f"squid-api/v1/ai/knowledge-base/getContext/{self._kb_id}/{context_id}", 634 params=params, 635 ) 636 637 async def list_contexts(self, *, truncate_text_after: int | None = None) -> list[dict]: 638 """List all contexts in the knowledge base. 639 640 Deprecated: fetches every context in one call with no pagination — expensive for large 641 knowledge bases. Use :meth:`list_contexts_page` instead, which supports 642 ``offset``/``limit``/``search``. 643 644 Args: 645 truncate_text_after: The number of characters after which each context's 646 text is truncated. 647 648 Returns: 649 A list of ``AiKnowledgeBaseContext`` dicts. 650 """ 651 params = ( 652 {"truncateTextAfter": str(truncate_text_after)} 653 if truncate_text_after is not None 654 else None 655 ) 656 result = await self._http.get( 657 f"squid-api/v1/ai/knowledge-base/listContexts/{self._kb_id}", params=params 658 ) 659 return result.get("contexts", []) if result else [] 660 661 async def list_contexts_page( 662 self, 663 *, 664 offset: int | None = None, 665 limit: int | None = None, 666 search: str | None = None, 667 truncate_text_after: int | None = None, 668 ) -> dict: 669 """List a page of contexts in the knowledge base. 670 671 Args: 672 offset: The number of contexts to skip, for pagination. 673 limit: The maximum number of contexts to return, for pagination. 674 search: Case-insensitive substring search across id/title only. 675 truncate_text_after: The number of characters after which each context's 676 text is truncated. 677 678 Returns: 679 A dict with ``contexts`` (a list of ``AiKnowledgeBaseContext`` dicts for the 680 requested page) and ``totalCount`` (the total number of contexts in the 681 knowledge base, ignoring ``offset``/``limit``). 682 """ 683 params = { 684 key: str(value) 685 for key, value in { 686 "offset": offset, 687 "limit": limit, 688 "search": search, 689 "truncateTextAfter": truncate_text_after, 690 }.items() 691 if value is not None 692 } 693 result = await self._http.get( 694 f"squid-api/v1/ai/knowledge-base/listContextsPage/{self._kb_id}", 695 params=params or None, 696 ) 697 return result if result else {"contexts": [], "totalCount": 0} 698 699 async def upsert_contexts( 700 self, 701 contexts: list[ContextRequest], 702 files: list[tuple[str, bytes, str]] | None = None, 703 ) -> dict: 704 """Add or update contexts in the knowledge base. 705 706 Args: 707 contexts: A list of context request objects. Each must be either: 708 - A :class:`TextContextRequest`: ``{'contextId', 'type': 'text', 'title', 'text', ...}`` 709 - A :class:`FileContextRequest`: ``{'contextId', 'type': 'file', ...}`` 710 files: For file contexts, provide the actual file data as a list of 711 ``(filename, data_bytes, content_type)`` tuples. Must match the 712 order of file contexts in the ``contexts`` list. 713 714 Returns: 715 A dict with ``failures``: a list of ``UpsertContextStatusError`` dicts 716 for any contexts that failed to upsert. 717 718 Example:: 719 720 await kb.upsert_contexts( 721 [ 722 {"contextId": "doc-1", "type": "text", "title": "FAQ", "text": "..."}, 723 {"contextId": "doc-2", "type": "file"}, 724 ], 725 files=[ 726 ("manual.pdf", pdf_bytes, "application/pdf"), 727 ], 728 ) 729 """ 730 form_data = { 731 "knowledgeBaseId": self._kb_id, 732 "contexts": json.dumps(contexts), 733 } 734 file_tuples: list[tuple[str, tuple[str, bytes, str]]] = [] 735 if files: 736 for fname, fdata, ftype in files: 737 file_tuples.append(("files", (fname, fdata, ftype))) 738 return await self._http.post_form( 739 "squid-api/v1/ai/knowledge-base/upsertContexts", 740 data=form_data, 741 files=file_tuples, 742 ) 743 744 async def delete_contexts(self, context_ids: list[str]) -> None: 745 """Delete contexts by their IDs. 746 747 Args: 748 context_ids: List of context IDs to delete. 749 """ 750 await self._http.post( 751 "squid-api/v1/ai/knowledge-base/deleteContexts", 752 {"knowledgeBaseId": self._kb_id, "contextIds": context_ids}, 753 ) 754 755 # --- Search --- 756 757 async def search( 758 self, 759 prompt: str, 760 options: KnowledgeBaseSearchOptions | None = None, 761 ) -> list[dict]: 762 """Search the knowledge base using semantic search. 763 764 Without an API key, allowed only on a knowledge base whose ``accessControl.mode`` is 765 ``'enforced'``. 766 767 Args: 768 prompt: The search query in natural language. 769 options: Search options. See :class:`KnowledgeBaseSearchOptions`. 770 Supports: ``limit``, ``chunkLimit``, ``rerankProvider``, ``rerankScoreThreshold``, 771 ``chatModel``, ``searchMode``, ``graphOptions``, ``graphFilter``. 772 773 Returns: 774 A list of ``AiKnowledgeBaseSearchResultChunk`` dicts, each with: 775 ``contextId``, ``data``, ``metadata``, ``score``. 776 777 Example:: 778 779 chunks = await kb.search( 780 "How do I reset my password?", 781 options={ 782 "limit": 5, 783 "chatModel": "gemini-3.8-flash", 784 }, 785 ) 786 for chunk in chunks: 787 print(f"Score: {chunk['score']}, Data: {chunk['data'][:100]}") 788 """ 789 response = await self.search_with_graph_context(prompt, options) 790 return response.get("chunks", []) 791 792 # --- Knowledge graph --- 793 794 async def search_with_graph_context( 795 self, 796 prompt: str, 797 options: KnowledgeBaseSearchOptions | None = None, 798 ) -> dict: 799 """Like :meth:`search`, but return the full search response instead of only the chunks. 800 801 Without an API key, allowed only on a knowledge base whose ``accessControl.mode`` is 802 ``'enforced'``. 803 804 With ``searchMode: 'graph'`` and ``graphOptions: {'includeGraphContext': True}`` the 805 response also carries ``graphContext``, the subgraph the search traversed. 806 807 Args: 808 prompt: The search query in natural language. 809 options: Search options. See :class:`KnowledgeBaseSearchOptions`. 810 811 Returns: 812 An ``AiKnowledgeBaseSearchResponse`` dict: ``chunks`` (list of result chunk dicts) 813 and, when requested via ``includeGraphContext``, ``graphContext`` 814 (``{'entities': [...], 'relationships': [...]}``). 815 """ 816 search_options: dict[str, Any] = {"prompt": prompt, **(options or {})} 817 result = await self._http.post( 818 "squid-api/v1/ai/knowledge-base/search", 819 { 820 "knowledgeBaseId": self._kb_id, 821 "prompt": prompt, 822 "options": search_options, 823 }, 824 ) 825 return result or {"chunks": []} 826 827 async def get_graph_status(self, *, include_topics: bool | None = None) -> dict: 828 """Get the knowledge base's graph build/readiness status. 829 830 Args: 831 include_topics: Whether to include the topic table (``topics``, ``topicEdges``). 832 Default True; pass False to poll the build state without it. 833 834 Returns: 835 A ``GetKnowledgeBaseGraphStatusResponse`` dict with ``enabled``, ``entityCount``, 836 ``relationshipCount``, ``contextsIndexed``, ``contextsTotal``, and, where available, 837 ``facets``, ``topics``, ``structureStale``, LLM usage fields, and ``buildJob`` 838 (``{'status': 'in_progress' | 'completed' | 'failed', ...}``) for the most recent 839 rebuild. Poll it after :meth:`rebuild_graph` until ``buildJob`` leaves 840 ``'in_progress'``. 841 """ 842 params: dict[str, str] | None = None 843 if include_topics is not None: 844 params = {"includeTopics": "true" if include_topics else "false"} 845 return await self._http.get( 846 f"squid-api/v1/ai/knowledge-base/getGraphStatus/{self._kb_id}", params=params 847 ) 848 849 async def get_file_status(self, path: str) -> dict: 850 """Look up the durable ingestion status of one file by path. 851 852 Args: 853 path: The file's path: ``folderPath/filename``, or just ``filename`` at the 854 upload root. 855 856 Returns: 857 An ``AiKnowledgeBaseFileStatusInfo`` dict: ``status`` is one of ``'completed'``, 858 ``'failed'`` (with ``errorMessage``/``errorCode``), ``'in_progress'``, or 859 ``'no_record'`` when the knowledge base has no trace of that path. 860 """ 861 return await self._http.get( 862 f"squid-api/v1/ai/knowledge-base/getFileStatus/{self._kb_id}", 863 params={"path": path}, 864 ) 865 866 async def get_folder_status(self, folder_path: str, *, file_limit: int | None = None) -> dict: 867 """Search and aggregate the durable ingestion status of every file matching ``folder_path``. 868 869 Read three ways and unioned: a folder subtree (matched the same segment-safe way as 870 ``$underPath`` metadata filters), a bare filename anywhere in the knowledge base, and, 871 when it contains a ``/``, an exact ``folder_path/filename`` path. 872 873 Args: 874 folder_path: The folder subtree, bare filename, or exact file path to search for. 875 file_limit: Maximum number of files to return in ``files``, prioritizing failures. 876 Defaults to 50. 877 878 Returns: 879 An ``AiKnowledgeBaseFolderStatusResponse`` dict with ``counts`` (per-status totals), 880 ``totalFiles``, ``hasAnyRecords``, ``files`` (capped, failures first), and 881 ``truncated``. 882 """ 883 params = { 884 key: str(value) 885 for key, value in {"folderPath": folder_path, "fileLimit": file_limit}.items() 886 if value is not None 887 } 888 return await self._http.get( 889 f"squid-api/v1/ai/knowledge-base/getFolderStatus/{self._kb_id}", 890 params=params, 891 ) 892 893 async def rebuild_graph( 894 self, 895 *, 896 mode: Literal["full", "structural"] | None = None, 897 ignore_active_bulk_jobs: bool | None = None, 898 ) -> None: 899 """Enqueue a graph rebuild/backfill. Requires ``graphRag.enabled``. 900 901 Only one rebuild can run per knowledge base at a time; track progress via 902 :meth:`get_graph_status`. A rebuild while a bulk-ingestion job on the knowledge base is 903 still active is refused (``GRAPH_REBUILD_BLOCKED_BY_BULK_JOB``). 904 905 Args: 906 mode: ``'structural'`` (the default) keeps the already-extracted entity graph and 907 rebuilds just the concept layer; ``'full'`` wipes the graph and re-extracts every 908 context with an LLM — expensive, and only needed when the extraction itself must 909 be redone (e.g. after changing ``entityTypes``, ``extractionModel`` or 910 ``extractionDepth``). 911 ignore_active_bulk_jobs: start the rebuild even while a bulk-ingestion job is active. 912 For a wedged job only: the rebuild re-extracts what a live job is still merging. 913 """ 914 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id} 915 if mode is not None: 916 request["mode"] = mode 917 if ignore_active_bulk_jobs is not None: 918 request["ignoreActiveBulkJobs"] = ignore_active_bulk_jobs 919 await self._http.post("squid-api/v1/ai/knowledge-base/rebuildGraph", request) 920 921 async def query_graph( 922 self, 923 op: KnowledgeBaseGraphQueryOp, 924 *, 925 ref: str | None = None, 926 ref_b: str | None = None, 927 context_id: str | None = None, 928 query: str | None = None, 929 depth: int | None = None, 930 hops: int | None = None, 931 recursive: bool | None = None, 932 limit: int | None = None, 933 context_metadata_filter: dict[str, Any] | None = None, 934 ) -> dict: 935 """Query the knowledge base's graph (documents, entities, themes, facets). 936 937 Requires ``graphRag.enabled`` on the knowledge base. 938 939 Args: 940 op: The operation to run. 941 ref: Node ref (name, facet nodeId, or a topic or entity id from 942 :meth:`explore_graph`). Required by resolve/describe/subtree/docsUnder/ 943 neighborhood/pathBetween/relationship. 944 ref_b: Second node ref for ``pathBetween``, and the target entity for ``relationship``. 945 context_id: The document's contextId for ``conceptsOf``. 946 query: The free-text question for ``globalSummary``. 947 depth: ``subtree``: maximum depth below the resolved node. Default (and cap) 3. 948 hops: ``neighborhood``: expansion hops from the resolved entity. Default 1, max 2. 949 recursive: ``docsUnder``: when True (the default), include documents under the whole 950 subtree, not just the node itself. 951 limit: ``docsUnder`` and ``relationship``: maximum documents returned. Default 25, max 100. 952 context_metadata_filter: ``docsUnder`` and ``relationship``: keeps only the documents 953 whose context matches this metadata filter (context-record metadata only). 954 955 Returns: 956 A ``QueryKnowledgeBaseGraphResponse`` dict; which keys are present depends on ``op`` 957 (e.g. ``overview`` for 'overview', ``matches`` for 'resolve', ``node``/``path``/ 958 ``related`` for 'describe', ``tree``, ``documents``/``totalDocs``, ``concepts``, 959 ``graph``, ``pathBetween``, ``summaries``, ``relationship``). 960 """ 961 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id, "op": op} 962 if ref is not None: 963 request["ref"] = ref 964 if ref_b is not None: 965 request["refB"] = ref_b 966 if context_id is not None: 967 request["contextId"] = context_id 968 if query is not None: 969 request["query"] = query 970 if depth is not None: 971 request["depth"] = depth 972 if hops is not None: 973 request["hops"] = hops 974 if recursive is not None: 975 request["recursive"] = recursive 976 if limit is not None: 977 request["limit"] = limit 978 if context_metadata_filter is not None: 979 request["contextMetadataFilter"] = context_metadata_filter 980 return await self._http.post("squid-api/v1/ai/knowledge-base/queryGraph", request) 981 982 async def explore_graph( 983 self, 984 *, 985 node_limit: int | None = None, 986 topic_id: str | None = None, 987 entity_id: str | None = None, 988 search: str | None = None, 989 context_metadata_filter: dict[str, Any] | None = None, 990 include_topics: bool | None = None, 991 ) -> dict: 992 """Get a bounded slice of the knowledge base's entity graph for exploration/visualization. 993 994 By default returns the highest-degree entities and the relationships among them. Requires 995 ``graphRag.enabled``. ``topic_id``, ``entity_id`` and ``search`` select other entity pools; 996 pass at most one of them. 997 998 Args: 999 node_limit: Hard cap on returned nodes. Default 200, max 1000. 1000 topic_id: Restricts the subgraph to entities under the given topic node id. Ids come 1001 from :meth:`get_graph_status`'s ``topics`` and churn on rebuild. 1002 entity_id: Centers the subgraph on one entity: the entity plus its neighbors, strongest 1003 relationships first. Ids come from the returned nodes and churn on rebuild. 1004 search: Finds entities by name (exact, then prefix, then substring); when no name 1005 matches, returns the entities nearest in meaning. 1006 context_metadata_filter: Keeps only the entities mentioned by contexts matching this 1007 metadata filter (context-record metadata only). 1008 include_topics: Whether to attach the topic table (``topics``). Default True; pass 1009 False when the caller already holds it. 1010 1011 Returns: 1012 An ``ExploreKnowledgeBaseGraphResponse`` dict: ``nodes``, ``edges`` (the heaviest, 1013 capped; ``edgesTruncated`` when cut), ``totalCount`` when counted, ``searchMatch`` for 1014 a search, ``scopeTruncated`` when the filter matched too many contexts, and, once the 1015 concept layer has been built, ``topics``. 1016 """ 1017 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id} 1018 if node_limit is not None: 1019 request["nodeLimit"] = node_limit 1020 if topic_id is not None: 1021 request["topicId"] = topic_id 1022 if entity_id is not None: 1023 request["entityId"] = entity_id 1024 if search is not None: 1025 request["search"] = search 1026 if context_metadata_filter is not None: 1027 request["contextMetadataFilter"] = context_metadata_filter 1028 if include_topics is not None: 1029 request["includeTopics"] = include_topics 1030 return await self._http.post("squid-api/v1/ai/knowledge-base/exploreGraph", request) 1031 1032 async def list_audit_logs( 1033 self, 1034 *, 1035 limit: int | None = None, 1036 cursor: str | None = None, 1037 where: KnowledgeBaseAuditLogFilter | None = None, 1038 ) -> ListKnowledgeBaseAuditLogsResponse: 1039 """Return a page of this knowledge base's audit log, newest first: one entry per search. 1040 1041 Searches are recorded only while the knowledge base enforces access control. Pass a response's 1042 ``nextCursor`` as ``cursor`` to get the next page; a page may hold fewer entries than ``limit``. 1043 1044 Args: 1045 limit: The page size: 100 by default, at most 1000. 1046 cursor: The ``nextCursor`` of the previous page. 1047 where: Filters: ``agentId``, ``jobId``, ``source``, ``createdAfter`` and ``createdBefore`` 1048 (ISO timestamps). 1049 """ 1050 body = _audit_log_request(limit, cursor, where) 1051 body["knowledgeBaseId"] = self._kb_id 1052 return await self._http.post("squid-api/v1/ai/knowledge-base/listAuditLogs", body)
Operations on a single knowledge base.
Provides methods for managing knowledge base configuration, upserting and searching text/file contexts, and retrieving individual contexts.
Obtained via AiClient.knowledge_base().
Example::
kb = squid.ai().knowledge_base("my-kb")
await kb.upsert(description="Product documentation")
await kb.upsert_contexts(
[
{
"contextId": "doc-1",
"type": "text",
"title": "Getting Started",
"text": "Welcome to our product...",
}
]
)
results = await kb.search("How do I get started?")
549 async def get(self) -> dict | None: 550 """Get the knowledge base details. 551 552 Returns: 553 An ``AiKnowledgeBase`` dict with keys: ``id``, ``appId``, 554 ``description``, ``metadataFields``, ``embeddingModel``, 555 ``chatModel``, ``updatedAt``. Returns ``None`` if not found. 556 """ 557 return await self._http.get(f"squid-api/v1/ai/knowledge-base/get/{self._kb_id}")
Get the knowledge base details.
Returns:
An
AiKnowledgeBasedict with keys:id,appId,description,metadataFields,embeddingModel,chatModel,updatedAt. ReturnsNoneif not found.
559 async def upsert( 560 self, 561 *, 562 description: str | None = None, 563 metadata_fields: list[AiKnowledgeBaseMetadataField] | None = None, 564 embedding_model: str | None = None, 565 chat_model: AiChatModelSelection | None = None, 566 name: str | None = None, 567 vector_db_type: VectorDbType | None = None, 568 graph_rag: AiKnowledgeBaseGraphConfig | None = None, 569 ) -> None: 570 """Create or update the knowledge base. 571 572 Args: 573 description: Description of the knowledge base's content. 574 metadata_fields: Schema for metadata fields used in filtering. 575 Each field: ``{'name': str, 'dataType': str, 'required': bool, 'description'?: str}``. 576 embedding_model: The embedding model name for vectorization. 577 Required when creating a new knowledge base. 578 chat_model: The LLM model for answering questions over this KB. 579 name: Display name for the knowledge base. 580 vector_db_type: The vector store backend. Set at creation (defaulting to the 581 server's default) and immutable thereafter. The knowledge graph requires 582 ``'mongoAtlas'``. 583 graph_rag: Opt-in GraphRAG configuration (``{'enabled': True, ...}``). Only 584 honored on ``'mongoAtlas'`` knowledge bases; mutable, unlike 585 ``vector_db_type``. The value replaces the stored config rather than 586 merging into it. See :class:`AiKnowledgeBaseGraphConfig`. 587 """ 588 kb: dict[str, Any] = {"id": self._kb_id} 589 if description is not None: 590 kb["description"] = description 591 if metadata_fields is not None: 592 kb["metadataFields"] = metadata_fields 593 if embedding_model is not None: 594 kb["embeddingModel"] = embedding_model 595 if chat_model is not None: 596 kb["chatModel"] = chat_model 597 if name is not None: 598 kb["name"] = name 599 if vector_db_type is not None: 600 kb["vectorDbType"] = vector_db_type 601 if graph_rag is not None: 602 kb["graphRag"] = graph_rag 603 await self._http.post("squid-api/v1/ai/knowledge-base/upsert", {"knowledgeBase": kb})
Create or update the knowledge base.
Arguments:
- description: Description of the knowledge base's content.
- metadata_fields: Schema for metadata fields used in filtering.
Each field:
{'name': str, 'dataType': str, 'required': bool, 'description'?: str}. - embedding_model: The embedding model name for vectorization. Required when creating a new knowledge base.
- chat_model: The LLM model for answering questions over this KB.
- name: Display name for the knowledge base.
- vector_db_type: The vector store backend. Set at creation (defaulting to the
server's default) and immutable thereafter. The knowledge graph requires
'mongoAtlas'. - graph_rag: Opt-in GraphRAG configuration (
{'enabled': True, ...}). Only honored on'mongoAtlas'knowledge bases; mutable, unlikevector_db_type. The value replaces the stored config rather than merging into it. SeeAiKnowledgeBaseGraphConfig.
605 async def delete(self) -> None: 606 """Delete the knowledge base and all its contexts permanently.""" 607 await self._http.post("squid-api/v1/ai/knowledge-base/delete", {"id": self._kb_id})
Delete the knowledge base and all its contexts permanently.
611 async def get_context( 612 self, context_id: str, *, truncate_text_after: int | None = None 613 ) -> dict | None: 614 """Get a specific context entry. 615 616 Args: 617 context_id: The unique context identifier. 618 truncate_text_after: The number of characters after which the context's 619 text is truncated. Pass ``0`` to return an empty text. 620 621 Returns: 622 An ``AiKnowledgeBaseContext`` dict with keys: ``id``, ``appId``, 623 ``knowledgeBaseId``, ``createdAt``, ``updatedAt``, ``type``, 624 ``title``, ``text``, ``preview``, ``sizeBytes``, ``metadata``, 625 ``requestConfig``. Returns ``None`` if not found. 626 """ 627 params = ( 628 {"truncateTextAfter": str(truncate_text_after)} 629 if truncate_text_after is not None 630 else None 631 ) 632 return await self._http.get( 633 f"squid-api/v1/ai/knowledge-base/getContext/{self._kb_id}/{context_id}", 634 params=params, 635 )
Get a specific context entry.
Arguments:
- context_id: The unique context identifier.
- truncate_text_after: The number of characters after which the context's
text is truncated. Pass
0to return an empty text.
Returns:
An
AiKnowledgeBaseContextdict with keys:id,appId,knowledgeBaseId,createdAt,updatedAt,type,title,text,preview,sizeBytes,metadata,requestConfig. ReturnsNoneif not found.
637 async def list_contexts(self, *, truncate_text_after: int | None = None) -> list[dict]: 638 """List all contexts in the knowledge base. 639 640 Deprecated: fetches every context in one call with no pagination — expensive for large 641 knowledge bases. Use :meth:`list_contexts_page` instead, which supports 642 ``offset``/``limit``/``search``. 643 644 Args: 645 truncate_text_after: The number of characters after which each context's 646 text is truncated. 647 648 Returns: 649 A list of ``AiKnowledgeBaseContext`` dicts. 650 """ 651 params = ( 652 {"truncateTextAfter": str(truncate_text_after)} 653 if truncate_text_after is not None 654 else None 655 ) 656 result = await self._http.get( 657 f"squid-api/v1/ai/knowledge-base/listContexts/{self._kb_id}", params=params 658 ) 659 return result.get("contexts", []) if result else []
List all contexts in the knowledge base.
Deprecated: fetches every context in one call with no pagination — expensive for large
knowledge bases. Use list_contexts_page() instead, which supports
offset/limit/search.
Arguments:
- truncate_text_after: The number of characters after which each context's text is truncated.
Returns:
A list of
AiKnowledgeBaseContextdicts.
661 async def list_contexts_page( 662 self, 663 *, 664 offset: int | None = None, 665 limit: int | None = None, 666 search: str | None = None, 667 truncate_text_after: int | None = None, 668 ) -> dict: 669 """List a page of contexts in the knowledge base. 670 671 Args: 672 offset: The number of contexts to skip, for pagination. 673 limit: The maximum number of contexts to return, for pagination. 674 search: Case-insensitive substring search across id/title only. 675 truncate_text_after: The number of characters after which each context's 676 text is truncated. 677 678 Returns: 679 A dict with ``contexts`` (a list of ``AiKnowledgeBaseContext`` dicts for the 680 requested page) and ``totalCount`` (the total number of contexts in the 681 knowledge base, ignoring ``offset``/``limit``). 682 """ 683 params = { 684 key: str(value) 685 for key, value in { 686 "offset": offset, 687 "limit": limit, 688 "search": search, 689 "truncateTextAfter": truncate_text_after, 690 }.items() 691 if value is not None 692 } 693 result = await self._http.get( 694 f"squid-api/v1/ai/knowledge-base/listContextsPage/{self._kb_id}", 695 params=params or None, 696 ) 697 return result if result else {"contexts": [], "totalCount": 0}
List a page of contexts in the knowledge base.
Arguments:
- offset: The number of contexts to skip, for pagination.
- limit: The maximum number of contexts to return, for pagination.
- search: Case-insensitive substring search across id/title only.
- truncate_text_after: The number of characters after which each context's text is truncated.
Returns:
A dict with
contexts(a list ofAiKnowledgeBaseContextdicts for the requested page) andtotalCount(the total number of contexts in the knowledge base, ignoringoffset/limit).
699 async def upsert_contexts( 700 self, 701 contexts: list[ContextRequest], 702 files: list[tuple[str, bytes, str]] | None = None, 703 ) -> dict: 704 """Add or update contexts in the knowledge base. 705 706 Args: 707 contexts: A list of context request objects. Each must be either: 708 - A :class:`TextContextRequest`: ``{'contextId', 'type': 'text', 'title', 'text', ...}`` 709 - A :class:`FileContextRequest`: ``{'contextId', 'type': 'file', ...}`` 710 files: For file contexts, provide the actual file data as a list of 711 ``(filename, data_bytes, content_type)`` tuples. Must match the 712 order of file contexts in the ``contexts`` list. 713 714 Returns: 715 A dict with ``failures``: a list of ``UpsertContextStatusError`` dicts 716 for any contexts that failed to upsert. 717 718 Example:: 719 720 await kb.upsert_contexts( 721 [ 722 {"contextId": "doc-1", "type": "text", "title": "FAQ", "text": "..."}, 723 {"contextId": "doc-2", "type": "file"}, 724 ], 725 files=[ 726 ("manual.pdf", pdf_bytes, "application/pdf"), 727 ], 728 ) 729 """ 730 form_data = { 731 "knowledgeBaseId": self._kb_id, 732 "contexts": json.dumps(contexts), 733 } 734 file_tuples: list[tuple[str, tuple[str, bytes, str]]] = [] 735 if files: 736 for fname, fdata, ftype in files: 737 file_tuples.append(("files", (fname, fdata, ftype))) 738 return await self._http.post_form( 739 "squid-api/v1/ai/knowledge-base/upsertContexts", 740 data=form_data, 741 files=file_tuples, 742 )
Add or update contexts in the knowledge base.
Arguments:
- contexts: A list of context request objects. Each must be either:
- A
TextContextRequest:{'contextId', 'type': 'text', 'title', 'text', ...} - A
FileContextRequest:{'contextId', 'type': 'file', ...}
- A
- files: For file contexts, provide the actual file data as a list of
(filename, data_bytes, content_type)tuples. Must match the order of file contexts in thecontextslist.
Returns:
A dict with
failures: a list ofUpsertContextStatusErrordicts for any contexts that failed to upsert.
Example::
await kb.upsert_contexts(
[
{"contextId": "doc-1", "type": "text", "title": "FAQ", "text": "..."},
{"contextId": "doc-2", "type": "file"},
],
files=[
("manual.pdf", pdf_bytes, "application/pdf"),
],
)
744 async def delete_contexts(self, context_ids: list[str]) -> None: 745 """Delete contexts by their IDs. 746 747 Args: 748 context_ids: List of context IDs to delete. 749 """ 750 await self._http.post( 751 "squid-api/v1/ai/knowledge-base/deleteContexts", 752 {"knowledgeBaseId": self._kb_id, "contextIds": context_ids}, 753 )
Delete contexts by their IDs.
Arguments:
- context_ids: List of context IDs to delete.
757 async def search( 758 self, 759 prompt: str, 760 options: KnowledgeBaseSearchOptions | None = None, 761 ) -> list[dict]: 762 """Search the knowledge base using semantic search. 763 764 Without an API key, allowed only on a knowledge base whose ``accessControl.mode`` is 765 ``'enforced'``. 766 767 Args: 768 prompt: The search query in natural language. 769 options: Search options. See :class:`KnowledgeBaseSearchOptions`. 770 Supports: ``limit``, ``chunkLimit``, ``rerankProvider``, ``rerankScoreThreshold``, 771 ``chatModel``, ``searchMode``, ``graphOptions``, ``graphFilter``. 772 773 Returns: 774 A list of ``AiKnowledgeBaseSearchResultChunk`` dicts, each with: 775 ``contextId``, ``data``, ``metadata``, ``score``. 776 777 Example:: 778 779 chunks = await kb.search( 780 "How do I reset my password?", 781 options={ 782 "limit": 5, 783 "chatModel": "gemini-3.8-flash", 784 }, 785 ) 786 for chunk in chunks: 787 print(f"Score: {chunk['score']}, Data: {chunk['data'][:100]}") 788 """ 789 response = await self.search_with_graph_context(prompt, options) 790 return response.get("chunks", [])
Search the knowledge base using semantic search.
Without an API key, allowed only on a knowledge base whose accessControl.mode is
'enforced'.
Arguments:
- prompt: The search query in natural language.
- options: Search options. See
KnowledgeBaseSearchOptions. Supports:limit,chunkLimit,rerankProvider,rerankScoreThreshold,chatModel,searchMode,graphOptions,graphFilter.
Returns:
A list of
AiKnowledgeBaseSearchResultChunkdicts, each with:contextId,data,metadata,score.
Example::
chunks = await kb.search(
"How do I reset my password?",
options={
"limit": 5,
"chatModel": "gemini-3.8-flash",
},
)
for chunk in chunks:
print(f"Score: {chunk['score']}, Data: {chunk['data'][:100]}")
794 async def search_with_graph_context( 795 self, 796 prompt: str, 797 options: KnowledgeBaseSearchOptions | None = None, 798 ) -> dict: 799 """Like :meth:`search`, but return the full search response instead of only the chunks. 800 801 Without an API key, allowed only on a knowledge base whose ``accessControl.mode`` is 802 ``'enforced'``. 803 804 With ``searchMode: 'graph'`` and ``graphOptions: {'includeGraphContext': True}`` the 805 response also carries ``graphContext``, the subgraph the search traversed. 806 807 Args: 808 prompt: The search query in natural language. 809 options: Search options. See :class:`KnowledgeBaseSearchOptions`. 810 811 Returns: 812 An ``AiKnowledgeBaseSearchResponse`` dict: ``chunks`` (list of result chunk dicts) 813 and, when requested via ``includeGraphContext``, ``graphContext`` 814 (``{'entities': [...], 'relationships': [...]}``). 815 """ 816 search_options: dict[str, Any] = {"prompt": prompt, **(options or {})} 817 result = await self._http.post( 818 "squid-api/v1/ai/knowledge-base/search", 819 { 820 "knowledgeBaseId": self._kb_id, 821 "prompt": prompt, 822 "options": search_options, 823 }, 824 ) 825 return result or {"chunks": []}
Like search(), but return the full search response instead of only the chunks.
Without an API key, allowed only on a knowledge base whose accessControl.mode is
'enforced'.
With searchMode: 'graph' and graphOptions: {'includeGraphContext': True} the
response also carries graphContext, the subgraph the search traversed.
Arguments:
- prompt: The search query in natural language.
- options: Search options. See
KnowledgeBaseSearchOptions.
Returns:
An
AiKnowledgeBaseSearchResponsedict:chunks(list of result chunk dicts) and, when requested viaincludeGraphContext,graphContext({'entities': [...], 'relationships': [...]}).
827 async def get_graph_status(self, *, include_topics: bool | None = None) -> dict: 828 """Get the knowledge base's graph build/readiness status. 829 830 Args: 831 include_topics: Whether to include the topic table (``topics``, ``topicEdges``). 832 Default True; pass False to poll the build state without it. 833 834 Returns: 835 A ``GetKnowledgeBaseGraphStatusResponse`` dict with ``enabled``, ``entityCount``, 836 ``relationshipCount``, ``contextsIndexed``, ``contextsTotal``, and, where available, 837 ``facets``, ``topics``, ``structureStale``, LLM usage fields, and ``buildJob`` 838 (``{'status': 'in_progress' | 'completed' | 'failed', ...}``) for the most recent 839 rebuild. Poll it after :meth:`rebuild_graph` until ``buildJob`` leaves 840 ``'in_progress'``. 841 """ 842 params: dict[str, str] | None = None 843 if include_topics is not None: 844 params = {"includeTopics": "true" if include_topics else "false"} 845 return await self._http.get( 846 f"squid-api/v1/ai/knowledge-base/getGraphStatus/{self._kb_id}", params=params 847 )
Get the knowledge base's graph build/readiness status.
Arguments:
- include_topics: Whether to include the topic table (
topics,topicEdges). Default True; pass False to poll the build state without it.
Returns:
A
GetKnowledgeBaseGraphStatusResponsedict withenabled,entityCount,relationshipCount,contextsIndexed,contextsTotal, and, where available,facets,topics,structureStale, LLM usage fields, andbuildJob({'status': 'in_progress' | 'completed' | 'failed', ...}) for the most recent rebuild. Poll it afterrebuild_graph()untilbuildJobleaves'in_progress'.
849 async def get_file_status(self, path: str) -> dict: 850 """Look up the durable ingestion status of one file by path. 851 852 Args: 853 path: The file's path: ``folderPath/filename``, or just ``filename`` at the 854 upload root. 855 856 Returns: 857 An ``AiKnowledgeBaseFileStatusInfo`` dict: ``status`` is one of ``'completed'``, 858 ``'failed'`` (with ``errorMessage``/``errorCode``), ``'in_progress'``, or 859 ``'no_record'`` when the knowledge base has no trace of that path. 860 """ 861 return await self._http.get( 862 f"squid-api/v1/ai/knowledge-base/getFileStatus/{self._kb_id}", 863 params={"path": path}, 864 )
Look up the durable ingestion status of one file by path.
Arguments:
- path: The file's path:
folderPath/filename, or justfilenameat the upload root.
Returns:
An
AiKnowledgeBaseFileStatusInfodict:statusis one of'completed','failed'(witherrorMessage/errorCode),'in_progress', or'no_record'when the knowledge base has no trace of that path.
866 async def get_folder_status(self, folder_path: str, *, file_limit: int | None = None) -> dict: 867 """Search and aggregate the durable ingestion status of every file matching ``folder_path``. 868 869 Read three ways and unioned: a folder subtree (matched the same segment-safe way as 870 ``$underPath`` metadata filters), a bare filename anywhere in the knowledge base, and, 871 when it contains a ``/``, an exact ``folder_path/filename`` path. 872 873 Args: 874 folder_path: The folder subtree, bare filename, or exact file path to search for. 875 file_limit: Maximum number of files to return in ``files``, prioritizing failures. 876 Defaults to 50. 877 878 Returns: 879 An ``AiKnowledgeBaseFolderStatusResponse`` dict with ``counts`` (per-status totals), 880 ``totalFiles``, ``hasAnyRecords``, ``files`` (capped, failures first), and 881 ``truncated``. 882 """ 883 params = { 884 key: str(value) 885 for key, value in {"folderPath": folder_path, "fileLimit": file_limit}.items() 886 if value is not None 887 } 888 return await self._http.get( 889 f"squid-api/v1/ai/knowledge-base/getFolderStatus/{self._kb_id}", 890 params=params, 891 )
Search and aggregate the durable ingestion status of every file matching folder_path.
Read three ways and unioned: a folder subtree (matched the same segment-safe way as
$underPath metadata filters), a bare filename anywhere in the knowledge base, and,
when it contains a /, an exact folder_path/filename path.
Arguments:
- folder_path: The folder subtree, bare filename, or exact file path to search for.
- file_limit: Maximum number of files to return in
files, prioritizing failures. Defaults to 50.
Returns:
An
AiKnowledgeBaseFolderStatusResponsedict withcounts(per-status totals),totalFiles,hasAnyRecords,files(capped, failures first), andtruncated.
893 async def rebuild_graph( 894 self, 895 *, 896 mode: Literal["full", "structural"] | None = None, 897 ignore_active_bulk_jobs: bool | None = None, 898 ) -> None: 899 """Enqueue a graph rebuild/backfill. Requires ``graphRag.enabled``. 900 901 Only one rebuild can run per knowledge base at a time; track progress via 902 :meth:`get_graph_status`. A rebuild while a bulk-ingestion job on the knowledge base is 903 still active is refused (``GRAPH_REBUILD_BLOCKED_BY_BULK_JOB``). 904 905 Args: 906 mode: ``'structural'`` (the default) keeps the already-extracted entity graph and 907 rebuilds just the concept layer; ``'full'`` wipes the graph and re-extracts every 908 context with an LLM — expensive, and only needed when the extraction itself must 909 be redone (e.g. after changing ``entityTypes``, ``extractionModel`` or 910 ``extractionDepth``). 911 ignore_active_bulk_jobs: start the rebuild even while a bulk-ingestion job is active. 912 For a wedged job only: the rebuild re-extracts what a live job is still merging. 913 """ 914 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id} 915 if mode is not None: 916 request["mode"] = mode 917 if ignore_active_bulk_jobs is not None: 918 request["ignoreActiveBulkJobs"] = ignore_active_bulk_jobs 919 await self._http.post("squid-api/v1/ai/knowledge-base/rebuildGraph", request)
Enqueue a graph rebuild/backfill. Requires graphRag.enabled.
Only one rebuild can run per knowledge base at a time; track progress via
get_graph_status(). A rebuild while a bulk-ingestion job on the knowledge base is
still active is refused (GRAPH_REBUILD_BLOCKED_BY_BULK_JOB).
Arguments:
- mode:
'structural'(the default) keeps the already-extracted entity graph and rebuilds just the concept layer;'full'wipes the graph and re-extracts every context with an LLM — expensive, and only needed when the extraction itself must be redone (e.g. after changingentityTypes,extractionModelorextractionDepth). - ignore_active_bulk_jobs: start the rebuild even while a bulk-ingestion job is active. For a wedged job only: the rebuild re-extracts what a live job is still merging.
921 async def query_graph( 922 self, 923 op: KnowledgeBaseGraphQueryOp, 924 *, 925 ref: str | None = None, 926 ref_b: str | None = None, 927 context_id: str | None = None, 928 query: str | None = None, 929 depth: int | None = None, 930 hops: int | None = None, 931 recursive: bool | None = None, 932 limit: int | None = None, 933 context_metadata_filter: dict[str, Any] | None = None, 934 ) -> dict: 935 """Query the knowledge base's graph (documents, entities, themes, facets). 936 937 Requires ``graphRag.enabled`` on the knowledge base. 938 939 Args: 940 op: The operation to run. 941 ref: Node ref (name, facet nodeId, or a topic or entity id from 942 :meth:`explore_graph`). Required by resolve/describe/subtree/docsUnder/ 943 neighborhood/pathBetween/relationship. 944 ref_b: Second node ref for ``pathBetween``, and the target entity for ``relationship``. 945 context_id: The document's contextId for ``conceptsOf``. 946 query: The free-text question for ``globalSummary``. 947 depth: ``subtree``: maximum depth below the resolved node. Default (and cap) 3. 948 hops: ``neighborhood``: expansion hops from the resolved entity. Default 1, max 2. 949 recursive: ``docsUnder``: when True (the default), include documents under the whole 950 subtree, not just the node itself. 951 limit: ``docsUnder`` and ``relationship``: maximum documents returned. Default 25, max 100. 952 context_metadata_filter: ``docsUnder`` and ``relationship``: keeps only the documents 953 whose context matches this metadata filter (context-record metadata only). 954 955 Returns: 956 A ``QueryKnowledgeBaseGraphResponse`` dict; which keys are present depends on ``op`` 957 (e.g. ``overview`` for 'overview', ``matches`` for 'resolve', ``node``/``path``/ 958 ``related`` for 'describe', ``tree``, ``documents``/``totalDocs``, ``concepts``, 959 ``graph``, ``pathBetween``, ``summaries``, ``relationship``). 960 """ 961 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id, "op": op} 962 if ref is not None: 963 request["ref"] = ref 964 if ref_b is not None: 965 request["refB"] = ref_b 966 if context_id is not None: 967 request["contextId"] = context_id 968 if query is not None: 969 request["query"] = query 970 if depth is not None: 971 request["depth"] = depth 972 if hops is not None: 973 request["hops"] = hops 974 if recursive is not None: 975 request["recursive"] = recursive 976 if limit is not None: 977 request["limit"] = limit 978 if context_metadata_filter is not None: 979 request["contextMetadataFilter"] = context_metadata_filter 980 return await self._http.post("squid-api/v1/ai/knowledge-base/queryGraph", request)
Query the knowledge base's graph (documents, entities, themes, facets).
Requires graphRag.enabled on the knowledge base.
Arguments:
- op: The operation to run.
- ref: Node ref (name, facet nodeId, or a topic or entity id from
explore_graph()). Required by resolve/describe/subtree/docsUnder/ neighborhood/pathBetween/relationship. - ref_b: Second node ref for
pathBetween, and the target entity forrelationship. - context_id: The document's contextId for
conceptsOf. - query: The free-text question for
globalSummary. - depth:
subtree: maximum depth below the resolved node. Default (and cap) 3. - hops:
neighborhood: expansion hops from the resolved entity. Default 1, max 2. - recursive:
docsUnder: when True (the default), include documents under the whole subtree, not just the node itself. - limit:
docsUnderandrelationship: maximum documents returned. Default 25, max 100. - context_metadata_filter:
docsUnderandrelationship: keeps only the documents whose context matches this metadata filter (context-record metadata only).
Returns:
A
QueryKnowledgeBaseGraphResponsedict; which keys are present depends onop(e.g.overviewfor 'overview',matchesfor 'resolve',node/path/relatedfor 'describe',tree,documents/totalDocs,concepts,graph,pathBetween,summaries,relationship).
982 async def explore_graph( 983 self, 984 *, 985 node_limit: int | None = None, 986 topic_id: str | None = None, 987 entity_id: str | None = None, 988 search: str | None = None, 989 context_metadata_filter: dict[str, Any] | None = None, 990 include_topics: bool | None = None, 991 ) -> dict: 992 """Get a bounded slice of the knowledge base's entity graph for exploration/visualization. 993 994 By default returns the highest-degree entities and the relationships among them. Requires 995 ``graphRag.enabled``. ``topic_id``, ``entity_id`` and ``search`` select other entity pools; 996 pass at most one of them. 997 998 Args: 999 node_limit: Hard cap on returned nodes. Default 200, max 1000. 1000 topic_id: Restricts the subgraph to entities under the given topic node id. Ids come 1001 from :meth:`get_graph_status`'s ``topics`` and churn on rebuild. 1002 entity_id: Centers the subgraph on one entity: the entity plus its neighbors, strongest 1003 relationships first. Ids come from the returned nodes and churn on rebuild. 1004 search: Finds entities by name (exact, then prefix, then substring); when no name 1005 matches, returns the entities nearest in meaning. 1006 context_metadata_filter: Keeps only the entities mentioned by contexts matching this 1007 metadata filter (context-record metadata only). 1008 include_topics: Whether to attach the topic table (``topics``). Default True; pass 1009 False when the caller already holds it. 1010 1011 Returns: 1012 An ``ExploreKnowledgeBaseGraphResponse`` dict: ``nodes``, ``edges`` (the heaviest, 1013 capped; ``edgesTruncated`` when cut), ``totalCount`` when counted, ``searchMatch`` for 1014 a search, ``scopeTruncated`` when the filter matched too many contexts, and, once the 1015 concept layer has been built, ``topics``. 1016 """ 1017 request: dict[str, Any] = {"knowledgeBaseId": self._kb_id} 1018 if node_limit is not None: 1019 request["nodeLimit"] = node_limit 1020 if topic_id is not None: 1021 request["topicId"] = topic_id 1022 if entity_id is not None: 1023 request["entityId"] = entity_id 1024 if search is not None: 1025 request["search"] = search 1026 if context_metadata_filter is not None: 1027 request["contextMetadataFilter"] = context_metadata_filter 1028 if include_topics is not None: 1029 request["includeTopics"] = include_topics 1030 return await self._http.post("squid-api/v1/ai/knowledge-base/exploreGraph", request)
Get a bounded slice of the knowledge base's entity graph for exploration/visualization.
By default returns the highest-degree entities and the relationships among them. Requires
graphRag.enabled. topic_id, entity_id and search select other entity pools;
pass at most one of them.
Arguments:
- node_limit: Hard cap on returned nodes. Default 200, max 1000.
- topic_id: Restricts the subgraph to entities under the given topic node id. Ids come
from
get_graph_status()'stopicsand churn on rebuild. - entity_id: Centers the subgraph on one entity: the entity plus its neighbors, strongest relationships first. Ids come from the returned nodes and churn on rebuild.
- search: Finds entities by name (exact, then prefix, then substring); when no name matches, returns the entities nearest in meaning.
- context_metadata_filter: Keeps only the entities mentioned by contexts matching this metadata filter (context-record metadata only).
- include_topics: Whether to attach the topic table (
topics). Default True; pass False when the caller already holds it.
Returns:
An
ExploreKnowledgeBaseGraphResponsedict:nodes,edges(the heaviest, capped;edgesTruncatedwhen cut),totalCountwhen counted,searchMatchfor a search,scopeTruncatedwhen the filter matched too many contexts, and, once the concept layer has been built,topics.
1032 async def list_audit_logs( 1033 self, 1034 *, 1035 limit: int | None = None, 1036 cursor: str | None = None, 1037 where: KnowledgeBaseAuditLogFilter | None = None, 1038 ) -> ListKnowledgeBaseAuditLogsResponse: 1039 """Return a page of this knowledge base's audit log, newest first: one entry per search. 1040 1041 Searches are recorded only while the knowledge base enforces access control. Pass a response's 1042 ``nextCursor`` as ``cursor`` to get the next page; a page may hold fewer entries than ``limit``. 1043 1044 Args: 1045 limit: The page size: 100 by default, at most 1000. 1046 cursor: The ``nextCursor`` of the previous page. 1047 where: Filters: ``agentId``, ``jobId``, ``source``, ``createdAfter`` and ``createdBefore`` 1048 (ISO timestamps). 1049 """ 1050 body = _audit_log_request(limit, cursor, where) 1051 body["knowledgeBaseId"] = self._kb_id 1052 return await self._http.post("squid-api/v1/ai/knowledge-base/listAuditLogs", body)
Return a page of this knowledge base's audit log, newest first: one entry per search.
Searches are recorded only while the knowledge base enforces access control. Pass a response's
nextCursor as cursor to get the next page; a page may hold fewer entries than limit.
Arguments:
- limit: The page size: 100 by default, at most 1000.
- cursor: The
nextCursorof the previous page. - where: Filters:
agentId,jobId,source,createdAfterandcreatedBefore(ISO timestamps).
915class KnowledgeBaseSearchOptions(TypedDict, total=False): 916 """Options for knowledge base search.""" 917 918 prompt: str 919 """The search prompt.""" 920 limit: int 921 """Max number of results to return.""" 922 chunkLimit: int 923 """How many chunks to search over (default 100).""" 924 rerankProvider: AiRerankProvider 925 """Reranker provider (default 'cohere').""" 926 rerankScoreThreshold: float 927 """Minimum reranker relevance score a chunk must reach to stay once at least 10 chunks are 928 already kept (default 0.2). Score ranges differ per reranker.""" 929 chatModel: AiChatModelSelection 930 """Model to use for answering.""" 931 searchMode: Literal["vector", "hybrid", "keyword", "graph"] 932 """Retrieval mode: 'hybrid' (BM25+dense fusion where supported; default on non-graph KBs), 933 'vector' (dense only), 'keyword' (pure lexical — every whitespace-separated term must appear 934 as a literal, case-insensitive substring), or 'graph' (GraphRAG — seeds entities via vector 935 search, expands relationships via graph traversal, maps entities back to their chunks, fused 936 with a hybrid search; requires a ``vectorDbType: 'mongoAtlas'`` KB with ``graphRag.enabled`` 937 and is the default there).""" 938 graphOptions: AiKnowledgeBaseGraphSearchOptions 939 """Tuning for ``searchMode: 'graph'``. Ignored for other search modes.""" 940 graphFilter: AiKnowledgeBaseGraphFilter 941 """Scopes the search to the documents under one concept of the KB's graph. Requires 942 ``graphRag.enabled``."""
Options for knowledge base search.
Minimum reranker relevance score a chunk must reach to stay once at least 10 chunks are already kept (default 0.2). Score ranges differ per reranker.
Retrieval mode: 'hybrid' (BM25+dense fusion where supported; default on non-graph KBs),
'vector' (dense only), 'keyword' (pure lexical — every whitespace-separated term must appear
as a literal, case-insensitive substring), or 'graph' (GraphRAG — seeds entities via vector
search, expands relationships via graph traversal, maps entities back to their chunks, fused
with a hybrid search; requires a vectorDbType: 'mongoAtlas' KB with graphRag.enabled
and is the default there).
Tuning for searchMode: 'graph'. Ignored for other search modes.
Scopes the search to the documents under one concept of the KB's graph. Requires
graphRag.enabled.
1222class ListAgentAuditLogsResponse(TypedDict): 1223 """A page of an agent's audit log, newest first.""" 1224 1225 entries: list[AgentAuditLogEntry] 1226 nextCursor: NotRequired[str]
A page of an agent's audit log, newest first.
1260class ListKnowledgeBaseAuditLogsResponse(TypedDict): 1261 """A page of a knowledge base's audit log, newest first.""" 1262 1263 entries: list[KnowledgeBaseAuditLogEntry] 1264 nextCursor: NotRequired[str]
A page of a knowledge base's audit log, newest first.
1155class ListSessionsFilter(TypedDict, total=False): 1156 """Filters of a session listing.""" 1157 1158 data: dict[str, str | int | float | bool | None] 1159 createdAfter: str 1160 createdBefore: str
Filters of a session listing.
1163class ListSessionsResponse(TypedDict): 1164 """A page of sessions, newest first.""" 1165 1166 sessions: list[Session] 1167 nextCursor: NotRequired[str]
A page of sessions, newest first.
21class MatchmakingClient: 22 """AI-powered matchmaking: match makers, entities, matching.""" 23 24 def __init__(self, http: HttpTransport) -> None: 25 self._http = http 26 27 # --- Match makers --- 28 29 async def create_match_maker( 30 self, 31 match_maker_id: str, 32 description: str, 33 categories: list[MmCategory], 34 ) -> dict: 35 """Create a new match maker.""" 36 return await self._http.post( 37 "squid-api/v1/ai/matchmaking/createMatchMaker", 38 {"id": match_maker_id, "description": description, "categories": categories}, 39 ) 40 41 async def get_match_maker(self, match_maker_id: str) -> dict | None: 42 """Get a match maker by ID.""" 43 result = await self._http.get(f"squid-api/v1/ai/matchmaking/getMatchMaker/{match_maker_id}") 44 return result.get("matchMaker") if result else None 45 46 async def list_match_makers(self) -> list[dict]: 47 """List all match makers.""" 48 result = await self._http.get("squid-api/v1/ai/matchmaking/listMatchMakers") 49 return result.get("matchMakers", []) if result else [] 50 51 async def delete_match_maker(self, match_maker_id: str) -> None: 52 """Delete a match maker.""" 53 await self._http.post( 54 "squid-api/v1/ai/matchmaking/deleteMatchMaker", 55 {"matchMakerId": match_maker_id}, 56 ) 57 58 # --- Entities --- 59 60 async def insert_entities(self, match_maker_id: str, entities: list[MmEntity]) -> None: 61 """Insert entities into a match maker.""" 62 await self._http.post( 63 "squid-api/v1/ai/matchmaking/insertEntities", 64 {"matchMakerId": match_maker_id, "entities": entities}, 65 ) 66 67 async def delete_entity(self, match_maker_id: str, entity_id: str) -> None: 68 """Delete an entity.""" 69 await self._http.post( 70 "squid-api/v1/ai/matchmaking/deleteEntity", 71 {"matchMakerId": match_maker_id, "entityId": entity_id}, 72 ) 73 74 async def get_entity(self, match_maker_id: str, entity_id: str) -> dict | None: 75 """Get a specific entity.""" 76 result = await self._http.get( 77 f"squid-api/v1/ai/matchmaking/getEntity/{match_maker_id}/{entity_id}" 78 ) 79 return result.get("entity") if result else None 80 81 async def list_entities( 82 self, 83 match_maker_id: str, 84 category_id: str, 85 options: MmListEntitiesOptions | None = None, 86 ) -> list[dict]: 87 """List entities in a category.""" 88 result = await self._http.post( 89 "squid-api/v1/ai/matchmaking/listEntities", 90 { 91 "matchMakerId": match_maker_id, 92 "categoryId": category_id, 93 "options": options or {}, 94 }, 95 ) 96 return result.get("entities", []) if result else [] 97 98 # --- Matching --- 99 100 async def find_matches( 101 self, 102 match_maker_id: str, 103 entity_id: str, 104 options: MmFindMatchesOptions | None = None, 105 ) -> list[dict]: 106 """Find matches for an existing entity. 107 108 Returns list of MmEntityMatch dicts with: 109 id, content, categoryId, metadata, score, reasoning. 110 """ 111 result = await self._http.post( 112 "squid-api/v1/ai/matchmaking/findMatches", 113 { 114 "matchMakerId": match_maker_id, 115 "entityId": entity_id, 116 "options": options or {}, 117 }, 118 ) 119 return result.get("matches", []) if result else [] 120 121 async def find_matches_for_entity( 122 self, 123 match_maker_id: str, 124 entity: MmEntity, 125 options: MmFindMatchesOptions | None = None, 126 ) -> list[dict]: 127 """Find matches for a new entity (not yet inserted).""" 128 result = await self._http.post( 129 "squid-api/v1/ai/matchmaking/findMatchesForEntity", 130 { 131 "matchMakerId": match_maker_id, 132 "entity": entity, 133 "options": options or {}, 134 }, 135 ) 136 return result.get("matches", []) if result else []
AI-powered matchmaking: match makers, entities, matching.
29 async def create_match_maker( 30 self, 31 match_maker_id: str, 32 description: str, 33 categories: list[MmCategory], 34 ) -> dict: 35 """Create a new match maker.""" 36 return await self._http.post( 37 "squid-api/v1/ai/matchmaking/createMatchMaker", 38 {"id": match_maker_id, "description": description, "categories": categories}, 39 )
Create a new match maker.
41 async def get_match_maker(self, match_maker_id: str) -> dict | None: 42 """Get a match maker by ID.""" 43 result = await self._http.get(f"squid-api/v1/ai/matchmaking/getMatchMaker/{match_maker_id}") 44 return result.get("matchMaker") if result else None
Get a match maker by ID.
46 async def list_match_makers(self) -> list[dict]: 47 """List all match makers.""" 48 result = await self._http.get("squid-api/v1/ai/matchmaking/listMatchMakers") 49 return result.get("matchMakers", []) if result else []
List all match makers.
51 async def delete_match_maker(self, match_maker_id: str) -> None: 52 """Delete a match maker.""" 53 await self._http.post( 54 "squid-api/v1/ai/matchmaking/deleteMatchMaker", 55 {"matchMakerId": match_maker_id}, 56 )
Delete a match maker.
60 async def insert_entities(self, match_maker_id: str, entities: list[MmEntity]) -> None: 61 """Insert entities into a match maker.""" 62 await self._http.post( 63 "squid-api/v1/ai/matchmaking/insertEntities", 64 {"matchMakerId": match_maker_id, "entities": entities}, 65 )
Insert entities into a match maker.
67 async def delete_entity(self, match_maker_id: str, entity_id: str) -> None: 68 """Delete an entity.""" 69 await self._http.post( 70 "squid-api/v1/ai/matchmaking/deleteEntity", 71 {"matchMakerId": match_maker_id, "entityId": entity_id}, 72 )
Delete an entity.
74 async def get_entity(self, match_maker_id: str, entity_id: str) -> dict | None: 75 """Get a specific entity.""" 76 result = await self._http.get( 77 f"squid-api/v1/ai/matchmaking/getEntity/{match_maker_id}/{entity_id}" 78 ) 79 return result.get("entity") if result else None
Get a specific entity.
81 async def list_entities( 82 self, 83 match_maker_id: str, 84 category_id: str, 85 options: MmListEntitiesOptions | None = None, 86 ) -> list[dict]: 87 """List entities in a category.""" 88 result = await self._http.post( 89 "squid-api/v1/ai/matchmaking/listEntities", 90 { 91 "matchMakerId": match_maker_id, 92 "categoryId": category_id, 93 "options": options or {}, 94 }, 95 ) 96 return result.get("entities", []) if result else []
List entities in a category.
100 async def find_matches( 101 self, 102 match_maker_id: str, 103 entity_id: str, 104 options: MmFindMatchesOptions | None = None, 105 ) -> list[dict]: 106 """Find matches for an existing entity. 107 108 Returns list of MmEntityMatch dicts with: 109 id, content, categoryId, metadata, score, reasoning. 110 """ 111 result = await self._http.post( 112 "squid-api/v1/ai/matchmaking/findMatches", 113 { 114 "matchMakerId": match_maker_id, 115 "entityId": entity_id, 116 "options": options or {}, 117 }, 118 ) 119 return result.get("matches", []) if result else []
Find matches for an existing entity.
Returns list of MmEntityMatch dicts with: id, content, categoryId, metadata, score, reasoning.
121 async def find_matches_for_entity( 122 self, 123 match_maker_id: str, 124 entity: MmEntity, 125 options: MmFindMatchesOptions | None = None, 126 ) -> list[dict]: 127 """Find matches for a new entity (not yet inserted).""" 128 result = await self._http.post( 129 "squid-api/v1/ai/matchmaking/findMatchesForEntity", 130 { 131 "matchMakerId": match_maker_id, 132 "entity": entity, 133 "options": options or {}, 134 }, 135 ) 136 return result.get("matches", []) if result else []
Find matches for a new entity (not yet inserted).
1050class MmCategory(TypedDict): 1051 """Matchmaking category.""" 1052 1053 id: str 1054 description: str
Matchmaking category.
1057class MmEntity(TypedDict, total=False): 1058 """Matchmaking entity.""" 1059 1060 id: str 1061 content: str 1062 categoryId: str 1063 metadata: dict[str, Any]
Matchmaking entity.
1066class MmFindMatchesOptions(TypedDict, total=False): 1067 """Options for finding matches.""" 1068 1069 metadataFilter: dict[str, Any] 1070 """AiContextMetadataFilter conditions.""" 1071 limit: int 1072 """Max matches to return (default 100, max 100).""" 1073 matchToCategoryId: str 1074 """Category to match against."""
Options for finding matches.
1077class MmListEntitiesOptions(TypedDict, total=False): 1078 """Options for listing entities.""" 1079 1080 metadataFilter: dict[str, Any] 1081 limit: int
Options for listing entities.
45class ModelIdSpec(TypedDict, total=False): 46 """An AI chat model available to the app. 47 48 Returned by :meth:`AiClient.list_chat_models`. 49 """ 50 51 modelId: AiChatModelName 52 """The model ID used for API calls. Required.""" 53 integrationId: str 54 """The integration ID if this model comes from an integration (OpenAI-compatible, 55 Bedrock). Absent for Squid-provided models.""" 56 displayName: str 57 """Human-readable display name for the model (e.g. 'GPT-4o').""" 58 description: str 59 """Short human-readable description of the model. Absent for custom integration models.""" 60 replacedBy: AiChatModelName 61 """Set only for deprecated models: the active model that calls to this model are 62 routed to. Absent for active models.""" 63 source: AiModelSource 64 """Where the model comes from: 'vendor' (Squid-provided), 'connector' (provided by an 65 integration configured on the app), or 'custom' (user-added model from the app's bundle)."""
An AI chat model available to the app.
Returned by AiClient.list_chat_models().
The integration ID if this model comes from an integration (OpenAI-compatible, Bedrock). Absent for Squid-provided models.
Short human-readable description of the model. Absent for custom integration models.
1144class Session(TypedDict): 1145 """A session: an app-scoped record of JSON data. Dates are ISO strings.""" 1146 1147 id: str 1148 data: dict[str, Any] 1149 createdAt: str 1150 updatedAt: str 1151 # None when the session never expires. 1152 expiresAt: str | None
A session: an app-scoped record of JSON data. Dates are ISO strings.
1135class SessionTtl(TypedDict): 1136 """An expiration a fixed time after the session's last write.""" 1137 1138 ttlMs: int
An expiration a fixed time after the session's last write.
21class SessionsClient: 22 """Sessions: app-scoped JSON records under ids the app chooses, which expire. 23 24 Every call needs the app API key. 25 """ 26 27 def __init__(self, http: HttpTransport) -> None: 28 self._http = http 29 30 async def upsert( 31 self, 32 session_id: str, 33 data: dict[str, Any] | None = None, 34 *, 35 delete_keys: list[str] | None = None, 36 expiration: SessionExpiration | None = None, 37 ) -> Session: 38 """Create the session, or update the one with the same id, and return it as stored. 39 40 Args: 41 session_id: The id of the session: 1-256 characters, without control characters. 42 data: Top-level keys to set; other keys keep their values. The session's data is at most 64 KB. 43 delete_keys: Top-level keys to remove. 44 expiration: ``"never"`` or ``{"ttlMs": ...}``. A new session expires one day after its last write. 45 46 Every upsert moves the expiration to its TTL from now. 47 """ 48 body: dict[str, Any] = {"id": session_id} 49 if data is not None: 50 body["data"] = data 51 if delete_keys is not None: 52 body["deleteKeys"] = delete_keys 53 if expiration is not None: 54 body["expiration"] = expiration 55 return await self._http.post("squid-api/v1/sessions/upsert", body) 56 57 async def get(self, session_id: str) -> Session | None: 58 """Return the session, or None when it is missing or expired.""" 59 result = await self._http.post("squid-api/v1/sessions/get", {"id": session_id}) 60 return result.get("session") if isinstance(result, dict) else None 61 62 async def delete(self, session_id: str) -> None: 63 """Delete the session. Deleting a missing session does nothing.""" 64 await self._http.post("squid-api/v1/sessions/delete", {"id": session_id}) 65 66 async def list( 67 self, 68 *, 69 limit: int | None = None, 70 cursor: str | None = None, 71 where: ListSessionsFilter | None = None, 72 ) -> ListSessionsResponse: 73 """Return a page of sessions, newest first. 74 75 Args: 76 limit: The page size: 100 by default, at most 1000. 77 cursor: The ``nextCursor`` of the previous page. 78 where: Filters: ``data`` (top-level keys that must equal the given values), 79 ``createdAfter`` and ``createdBefore`` (ISO timestamps). 80 """ 81 body: dict[str, Any] = {} 82 if limit is not None: 83 body["limit"] = limit 84 if cursor is not None: 85 body["cursor"] = cursor 86 if where is not None: 87 body["where"] = where 88 return await self._http.post("squid-api/v1/sessions/list", body)
Sessions: app-scoped JSON records under ids the app chooses, which expire.
Every call needs the app API key.
30 async def upsert( 31 self, 32 session_id: str, 33 data: dict[str, Any] | None = None, 34 *, 35 delete_keys: list[str] | None = None, 36 expiration: SessionExpiration | None = None, 37 ) -> Session: 38 """Create the session, or update the one with the same id, and return it as stored. 39 40 Args: 41 session_id: The id of the session: 1-256 characters, without control characters. 42 data: Top-level keys to set; other keys keep their values. The session's data is at most 64 KB. 43 delete_keys: Top-level keys to remove. 44 expiration: ``"never"`` or ``{"ttlMs": ...}``. A new session expires one day after its last write. 45 46 Every upsert moves the expiration to its TTL from now. 47 """ 48 body: dict[str, Any] = {"id": session_id} 49 if data is not None: 50 body["data"] = data 51 if delete_keys is not None: 52 body["deleteKeys"] = delete_keys 53 if expiration is not None: 54 body["expiration"] = expiration 55 return await self._http.post("squid-api/v1/sessions/upsert", body)
Create the session, or update the one with the same id, and return it as stored.
Arguments:
- session_id: The id of the session: 1-256 characters, without control characters.
- data: Top-level keys to set; other keys keep their values. The session's data is at most 64 KB.
- delete_keys: Top-level keys to remove.
- expiration:
"never"or{"ttlMs": ...}. A new session expires one day after its last write.
Every upsert moves the expiration to its TTL from now.
57 async def get(self, session_id: str) -> Session | None: 58 """Return the session, or None when it is missing or expired.""" 59 result = await self._http.post("squid-api/v1/sessions/get", {"id": session_id}) 60 return result.get("session") if isinstance(result, dict) else None
Return the session, or None when it is missing or expired.
62 async def delete(self, session_id: str) -> None: 63 """Delete the session. Deleting a missing session does nothing.""" 64 await self._http.post("squid-api/v1/sessions/delete", {"id": session_id})
Delete the session. Deleting a missing session does nothing.
66 async def list( 67 self, 68 *, 69 limit: int | None = None, 70 cursor: str | None = None, 71 where: ListSessionsFilter | None = None, 72 ) -> ListSessionsResponse: 73 """Return a page of sessions, newest first. 74 75 Args: 76 limit: The page size: 100 by default, at most 1000. 77 cursor: The ``nextCursor`` of the previous page. 78 where: Filters: ``data`` (top-level keys that must equal the given values), 79 ``createdAfter`` and ``createdBefore`` (ISO timestamps). 80 """ 81 body: dict[str, Any] = {} 82 if limit is not None: 83 body["limit"] = limit 84 if cursor is not None: 85 body["cursor"] = cursor 86 if where is not None: 87 body["where"] = where 88 return await self._http.post("squid-api/v1/sessions/list", body)
Return a page of sessions, newest first.
Arguments:
- limit: The page size: 100 by default, at most 1000.
- cursor: The
nextCursorof the previous page. - where: Filters:
data(top-level keys that must equal the given values),createdAfterandcreatedBefore(ISO timestamps).
25class Squid: 26 """Squid Cloud Python client. 27 28 The main entry point for interacting with the Squid Cloud platform. 29 Provides access to AI agents, knowledge bases, web utilities, 30 matchmaking, document extraction, backend functions, and webhooks. 31 32 Usage:: 33 34 squid = Squid( 35 app_id="my-app", 36 api_key="sk-...", 37 region="us-east-1.aws", 38 environment_id="dev", 39 ) 40 41 # AI agent 42 response = await squid.ai().agent("my-agent").ask("Hello!") 43 44 # Execute backend function 45 result = await squid.execute_function("MyService:greet", "World") 46 47 # Web search 48 results = await squid.web().ai_search("latest news") 49 50 # Cleanup 51 await squid.close() 52 53 Can also be used as an async context manager:: 54 55 async with Squid(app_id="my-app", api_key="sk-...", region="us-east-1.aws") as squid: 56 result = await squid.ai().agent("my-agent").ask("Hello!") 57 """ 58 59 def __init__( 60 self, 61 app_id: str, 62 region: str, 63 api_key: str | None = None, 64 environment_id: str | None = None, 65 squid_developer_id: str | None = None, 66 base_url: str | None = None, 67 backend_domain: str | None = None, 68 ) -> None: 69 """Initialize the Squid client. 70 71 Args: 72 app_id: The Squid application ID. 73 region: The deployment region (e.g., 'us-east-1.aws', 'local'). 74 api_key: API key for authentication. Required for most operations. 75 environment_id: Environment identifier (e.g., 'dev', 'prod'). 76 Appended to app_id as '{app_id}-{environment_id}'. 77 squid_developer_id: Developer identifier for local development. 78 Appended to app_id as '{app_id}-{environment_id}-{developer_id}'. 79 base_url: Overrides the region-derived API URL, e.g. an in-cluster core 80 address. Requests then send the app ID in the ``x-squid-appid`` header. 81 Public URLs such as ``get_webhook_url`` keep using the region. 82 backend_domain: Backend domain template of a self-hosted deployment, e.g. 83 'squid.acme.com' or '{cloudRegion}.squid.acme.com'. Placeholders: 84 {squidRegion}, {shard} / {customerId}, {cloudRegion}, {cloudId}, {stage}. 85 Falls back to SQUID_BACKEND_DOMAIN, then to Squid Cloud. 86 """ 87 self._app_id = app_id 88 self._region = region 89 self._environment_id = environment_id 90 self._squid_developer_id = squid_developer_id 91 self._backend_domain = backend_domain 92 93 full_app_id = app_id 94 if environment_id: 95 full_app_id = f"{app_id}-{environment_id}" 96 if squid_developer_id: 97 full_app_id = f"{full_app_id}-{squid_developer_id}" 98 99 self._full_app_id = full_app_id 100 self._http = HttpTransport( 101 app_id=full_app_id, 102 region=region, 103 api_key=api_key, 104 base_url=base_url, 105 backend_domain=backend_domain, 106 ) 107 108 @property 109 def app_id(self) -> str: 110 """The application ID (without environment/developer suffix).""" 111 return self._app_id 112 113 @property 114 def region(self) -> str: 115 """The deployment region.""" 116 return self._region 117 118 @property 119 def client_id(self) -> str: 120 """The unique client instance ID (UUID generated per Squid instance).""" 121 return self._http.client_id 122 123 # --- Sub-clients --- 124 125 def ai(self) -> AiClient: 126 """Access AI operations. 127 128 Provides access to AI agents, knowledge bases, image generation, 129 and audio transcription/synthesis. 130 131 Returns: 132 An :class:`AiClient` instance. 133 134 Example:: 135 136 agent = squid.ai().agent("my-agent") 137 response = await agent.ask("What is the weather?") 138 139 kb = squid.ai().knowledge_base("my-kb") 140 results = await kb.search("query") 141 """ 142 return AiClient(self._http) 143 144 def web(self) -> WebClient: 145 """Access web utilities. 146 147 Provides AI-powered web search, URL content extraction, 148 and short URL management. 149 150 Returns: 151 A :class:`WebClient` instance. 152 153 Example:: 154 155 content = await squid.web().get_url_content("https://example.com") 156 results = await squid.web().ai_search("latest AI news") 157 """ 158 return WebClient(self._http) 159 160 def matchmaking(self) -> MatchmakingClient: 161 """Access AI-powered matchmaking. 162 163 Provides match maker management, entity CRUD, 164 and AI-powered entity matching. 165 166 Returns: 167 A :class:`MatchmakingClient` instance. 168 169 Example:: 170 171 mm = squid.matchmaking() 172 await mm.create_match_maker("jobs", "Job matching", categories=[...]) 173 matches = await mm.find_matches("jobs", "entity-1") 174 """ 175 return MatchmakingClient(self._http) 176 177 def extraction(self) -> ExtractionClient: 178 """Access document extraction and PDF creation. 179 180 Provides PDF generation from HTML or URLs, and structured data 181 extraction from documents (PDF, DOCX, images, etc.). 182 183 Returns: 184 An :class:`ExtractionClient` instance. 185 186 Example:: 187 188 pdf = await squid.extraction().create_pdf_from_html("<h1>Hello</h1>") 189 data = await squid.extraction().extract_data_from_document_url( 190 "https://example.com/doc.pdf" 191 ) 192 """ 193 return ExtractionClient(self._http) 194 195 def sessions(self) -> SessionsClient: 196 """Access sessions: app-scoped JSON records that expire. Needs the app API key. 197 198 Returns: 199 A :class:`SessionsClient` instance. 200 201 Example:: 202 203 await squid.sessions().upsert("call-123", {"authenticated": True}) 204 session = await squid.sessions().get("call-123") 205 """ 206 return SessionsClient(self._http) 207 208 # --- Execute backend function --- 209 210 async def execute_function( 211 self, 212 function_name: str, 213 *params: Any, 214 ) -> Any: 215 """Execute a backend function by name. 216 217 Calls a function defined in a Squid backend service using the 218 ``@executable()`` decorator. 219 220 Args: 221 function_name: The service function name in the format 222 ``"ClassName:methodName"`` (e.g., ``"MyService:greet"``). 223 *params: Positional arguments to pass to the function. 224 Must be JSON-serializable. 225 226 Returns: 227 The function's return value, deserialized from JSON. 228 229 Raises: 230 SquidHttpError: If the function is not found or throws an error. 231 232 Example:: 233 234 result = await squid.execute_function("MyService:greet", "World") 235 # result == "Hello, World!" 236 237 data = await squid.execute_function("MyService:getData", 42, True) 238 """ 239 result = await self._http.post( 240 f"backend-function/execute?{function_name}", 241 { 242 "functionName": function_name, 243 "paramsArrayStr": json.dumps(list(params)), 244 }, 245 ) 246 if isinstance(result, dict): 247 payload = result.get("payload") 248 if isinstance(payload, str): 249 return json.loads(payload) 250 return payload 251 return result 252 253 # --- Execute webhook --- 254 255 async def execute_webhook( 256 self, 257 webhook_id: str, 258 *, 259 body: Any = None, 260 headers: dict[str, str] | None = None, 261 method: str = "POST", 262 ) -> Any: 263 """Execute a webhook. 264 265 Calls a webhook endpoint defined in a Squid backend service 266 using the ``@webhook()`` decorator. 267 268 Args: 269 webhook_id: The webhook ID as defined in the ``@webhook("id")`` decorator. 270 body: The request body to send. Must be JSON-serializable. 271 headers: Extra HTTP headers to include in the request. 272 method: The HTTP method to use (default ``"POST"``). 273 274 Returns: 275 The webhook's response body, deserialized from JSON. 276 277 Raises: 278 SquidHttpError: If the webhook is not found or returns an error. 279 280 Example:: 281 282 result = await squid.execute_webhook("my-hook", body={"key": "value"}) 283 """ 284 return await self._http.post( 285 f"webhooks/{webhook_id}", 286 body, 287 extra_headers=headers, 288 ) 289 290 def get_webhook_url(self, webhook_id: str) -> str: 291 """Get the full URL for a webhook endpoint. 292 293 Useful for providing the webhook URL to external services that 294 need to send HTTP requests to your Squid backend. 295 296 Args: 297 webhook_id: The webhook ID. 298 299 Returns: 300 The full URL string (e.g., 301 ``"https://myapp.us-east-1.aws.squid.cloud/webhooks/my-hook"``). 302 303 Example:: 304 305 url = squid.get_webhook_url("stripe-events") 306 # url == "https://myapp-dev.us-east-1.aws.squid.cloud/webhooks/stripe-events" 307 """ 308 return build_url( 309 self._region, self._full_app_id, f"webhooks/{webhook_id}", self._backend_domain 310 ) 311 312 # --- AI Query --- 313 314 async def execute_ai_query( 315 self, 316 integration_id: str, 317 prompt: str, 318 *, 319 options: AiQueryOptions | None = None, 320 response_format: dict[str, Any] | None = None, 321 ) -> dict: 322 """Execute an AI-powered database query. 323 324 Uses AI to generate and execute database queries based on a 325 natural language prompt. 326 327 Args: 328 integration_id: The database integration ID to query against. 329 prompt: A natural language description of the data you want. 330 options: Optional :class:`AiQueryOptions` controlling collection 331 selection, query generation (including ``allowClarification``), 332 result analysis (including ``enableCodeInterpreter``), memory, 333 AI validation, per-stage model overrides via ``aiOptions``, 334 and custom instructions. 335 response_format: Optional structured output format, e.g., 336 ``{"type": "json_schema", "schema": {...}}``. 337 338 Returns: 339 An ``AiQueryResponse`` dict containing: 340 - ``answer`` (str): The AI-generated answer. 341 - ``explanation`` (str): How the answer was derived. 342 - ``executedQueries`` (list): The actual queries that were run. 343 - ``success`` (bool): Whether the query succeeded. 344 - ``usedCodeInterpreter`` (bool): Whether the code 345 interpreter was used to analyze results. 346 - ``clarificationQuestion`` (str): If the AI needs more info. 347 348 Example:: 349 350 result = await squid.execute_ai_query( 351 "my-database", 352 "How many users signed up last week?", 353 options={ 354 "selectCollectionsOptions": {"collectionsToUse": ["users"]}, 355 "analyzeResultsOptions": {"enableCodeInterpreter": True}, 356 }, 357 ) 358 print(result["answer"]) 359 """ 360 return await execute_ai_query( 361 self._http, 362 integration_id, 363 prompt, 364 options=options, 365 response_format=response_format, 366 ) 367 368 # --- Lifecycle --- 369 370 async def close(self) -> None: 371 """Close the HTTP client and release resources. 372 373 Should be called when the Squid client is no longer needed. 374 Alternatively, use the client as an async context manager. 375 """ 376 await self._http.close() 377 378 async def __aenter__(self) -> Squid: 379 """Enter async context manager.""" 380 return self 381 382 async def __aexit__(self, *args: Any) -> None: 383 """Exit async context manager and close resources.""" 384 await self.close()
Squid Cloud Python client.
The main entry point for interacting with the Squid Cloud platform. Provides access to AI agents, knowledge bases, web utilities, matchmaking, document extraction, backend functions, and webhooks.
Usage::
squid = Squid(
app_id="my-app",
api_key="sk-...",
region="us-east-1.aws",
environment_id="dev",
)
# AI agent
response = await squid.ai().agent("my-agent").ask("Hello!")
# Execute backend function
result = await squid.execute_function("MyService:greet", "World")
# Web search
results = await squid.web().ai_search("latest news")
# Cleanup
await squid.close()
Can also be used as an async context manager::
async with Squid(app_id="my-app", api_key="sk-...", region="us-east-1.aws") as squid:
result = await squid.ai().agent("my-agent").ask("Hello!")
59 def __init__( 60 self, 61 app_id: str, 62 region: str, 63 api_key: str | None = None, 64 environment_id: str | None = None, 65 squid_developer_id: str | None = None, 66 base_url: str | None = None, 67 backend_domain: str | None = None, 68 ) -> None: 69 """Initialize the Squid client. 70 71 Args: 72 app_id: The Squid application ID. 73 region: The deployment region (e.g., 'us-east-1.aws', 'local'). 74 api_key: API key for authentication. Required for most operations. 75 environment_id: Environment identifier (e.g., 'dev', 'prod'). 76 Appended to app_id as '{app_id}-{environment_id}'. 77 squid_developer_id: Developer identifier for local development. 78 Appended to app_id as '{app_id}-{environment_id}-{developer_id}'. 79 base_url: Overrides the region-derived API URL, e.g. an in-cluster core 80 address. Requests then send the app ID in the ``x-squid-appid`` header. 81 Public URLs such as ``get_webhook_url`` keep using the region. 82 backend_domain: Backend domain template of a self-hosted deployment, e.g. 83 'squid.acme.com' or '{cloudRegion}.squid.acme.com'. Placeholders: 84 {squidRegion}, {shard} / {customerId}, {cloudRegion}, {cloudId}, {stage}. 85 Falls back to SQUID_BACKEND_DOMAIN, then to Squid Cloud. 86 """ 87 self._app_id = app_id 88 self._region = region 89 self._environment_id = environment_id 90 self._squid_developer_id = squid_developer_id 91 self._backend_domain = backend_domain 92 93 full_app_id = app_id 94 if environment_id: 95 full_app_id = f"{app_id}-{environment_id}" 96 if squid_developer_id: 97 full_app_id = f"{full_app_id}-{squid_developer_id}" 98 99 self._full_app_id = full_app_id 100 self._http = HttpTransport( 101 app_id=full_app_id, 102 region=region, 103 api_key=api_key, 104 base_url=base_url, 105 backend_domain=backend_domain, 106 )
Initialize the Squid client.
Arguments:
- app_id: The Squid application ID.
- region: The deployment region (e.g., 'us-east-1.aws', 'local').
- api_key: API key for authentication. Required for most operations.
- environment_id: Environment identifier (e.g., 'dev', 'prod'). Appended to app_id as '{app_id}-{environment_id}'.
- squid_developer_id: Developer identifier for local development. Appended to app_id as '{app_id}-{environment_id}-{developer_id}'.
- base_url: Overrides the region-derived API URL, e.g. an in-cluster core
address. Requests then send the app ID in the
x-squid-appidheader. Public URLs such asget_webhook_urlkeep using the region. - backend_domain: Backend domain template of a self-hosted deployment, e.g. 'squid.acme.com' or '{cloudRegion}.squid.acme.com'. Placeholders: {squidRegion}, {shard} / {customerId}, {cloudRegion}, {cloudId}, {stage}. Falls back to SQUID_BACKEND_DOMAIN, then to Squid Cloud.
108 @property 109 def app_id(self) -> str: 110 """The application ID (without environment/developer suffix).""" 111 return self._app_id
The application ID (without environment/developer suffix).
118 @property 119 def client_id(self) -> str: 120 """The unique client instance ID (UUID generated per Squid instance).""" 121 return self._http.client_id
The unique client instance ID (UUID generated per Squid instance).
125 def ai(self) -> AiClient: 126 """Access AI operations. 127 128 Provides access to AI agents, knowledge bases, image generation, 129 and audio transcription/synthesis. 130 131 Returns: 132 An :class:`AiClient` instance. 133 134 Example:: 135 136 agent = squid.ai().agent("my-agent") 137 response = await agent.ask("What is the weather?") 138 139 kb = squid.ai().knowledge_base("my-kb") 140 results = await kb.search("query") 141 """ 142 return AiClient(self._http)
Access AI operations.
Provides access to AI agents, knowledge bases, image generation, and audio transcription/synthesis.
Returns:
An
AiClientinstance.
Example::
agent = squid.ai().agent("my-agent")
response = await agent.ask("What is the weather?")
kb = squid.ai().knowledge_base("my-kb")
results = await kb.search("query")
144 def web(self) -> WebClient: 145 """Access web utilities. 146 147 Provides AI-powered web search, URL content extraction, 148 and short URL management. 149 150 Returns: 151 A :class:`WebClient` instance. 152 153 Example:: 154 155 content = await squid.web().get_url_content("https://example.com") 156 results = await squid.web().ai_search("latest AI news") 157 """ 158 return WebClient(self._http)
Access web utilities.
Provides AI-powered web search, URL content extraction, and short URL management.
Returns:
A
WebClientinstance.
Example::
content = await squid.web().get_url_content("https://example.com")
results = await squid.web().ai_search("latest AI news")
160 def matchmaking(self) -> MatchmakingClient: 161 """Access AI-powered matchmaking. 162 163 Provides match maker management, entity CRUD, 164 and AI-powered entity matching. 165 166 Returns: 167 A :class:`MatchmakingClient` instance. 168 169 Example:: 170 171 mm = squid.matchmaking() 172 await mm.create_match_maker("jobs", "Job matching", categories=[...]) 173 matches = await mm.find_matches("jobs", "entity-1") 174 """ 175 return MatchmakingClient(self._http)
Access AI-powered matchmaking.
Provides match maker management, entity CRUD, and AI-powered entity matching.
Returns:
A
MatchmakingClientinstance.
Example::
mm = squid.matchmaking()
await mm.create_match_maker("jobs", "Job matching", categories=[...])
matches = await mm.find_matches("jobs", "entity-1")
177 def extraction(self) -> ExtractionClient: 178 """Access document extraction and PDF creation. 179 180 Provides PDF generation from HTML or URLs, and structured data 181 extraction from documents (PDF, DOCX, images, etc.). 182 183 Returns: 184 An :class:`ExtractionClient` instance. 185 186 Example:: 187 188 pdf = await squid.extraction().create_pdf_from_html("<h1>Hello</h1>") 189 data = await squid.extraction().extract_data_from_document_url( 190 "https://example.com/doc.pdf" 191 ) 192 """ 193 return ExtractionClient(self._http)
Access document extraction and PDF creation.
Provides PDF generation from HTML or URLs, and structured data extraction from documents (PDF, DOCX, images, etc.).
Returns:
An
ExtractionClientinstance.
Example::
pdf = await squid.extraction().create_pdf_from_html("<h1>Hello</h1>")
data = await squid.extraction().extract_data_from_document_url(
"https://example.com/doc.pdf"
)
195 def sessions(self) -> SessionsClient: 196 """Access sessions: app-scoped JSON records that expire. Needs the app API key. 197 198 Returns: 199 A :class:`SessionsClient` instance. 200 201 Example:: 202 203 await squid.sessions().upsert("call-123", {"authenticated": True}) 204 session = await squid.sessions().get("call-123") 205 """ 206 return SessionsClient(self._http)
Access sessions: app-scoped JSON records that expire. Needs the app API key.
Returns:
A
SessionsClientinstance.
Example::
await squid.sessions().upsert("call-123", {"authenticated": True})
session = await squid.sessions().get("call-123")
210 async def execute_function( 211 self, 212 function_name: str, 213 *params: Any, 214 ) -> Any: 215 """Execute a backend function by name. 216 217 Calls a function defined in a Squid backend service using the 218 ``@executable()`` decorator. 219 220 Args: 221 function_name: The service function name in the format 222 ``"ClassName:methodName"`` (e.g., ``"MyService:greet"``). 223 *params: Positional arguments to pass to the function. 224 Must be JSON-serializable. 225 226 Returns: 227 The function's return value, deserialized from JSON. 228 229 Raises: 230 SquidHttpError: If the function is not found or throws an error. 231 232 Example:: 233 234 result = await squid.execute_function("MyService:greet", "World") 235 # result == "Hello, World!" 236 237 data = await squid.execute_function("MyService:getData", 42, True) 238 """ 239 result = await self._http.post( 240 f"backend-function/execute?{function_name}", 241 { 242 "functionName": function_name, 243 "paramsArrayStr": json.dumps(list(params)), 244 }, 245 ) 246 if isinstance(result, dict): 247 payload = result.get("payload") 248 if isinstance(payload, str): 249 return json.loads(payload) 250 return payload 251 return result
Execute a backend function by name.
Calls a function defined in a Squid backend service using the
@executable() decorator.
Arguments:
- function_name: The service function name in the format
"ClassName:methodName"(e.g.,"MyService:greet"). - *params: Positional arguments to pass to the function. Must be JSON-serializable.
Returns:
The function's return value, deserialized from JSON.
Raises:
- SquidHttpError: If the function is not found or throws an error.
Example::
result = await squid.execute_function("MyService:greet", "World")
# result == "Hello, World!"
data = await squid.execute_function("MyService:getData", 42, True)
255 async def execute_webhook( 256 self, 257 webhook_id: str, 258 *, 259 body: Any = None, 260 headers: dict[str, str] | None = None, 261 method: str = "POST", 262 ) -> Any: 263 """Execute a webhook. 264 265 Calls a webhook endpoint defined in a Squid backend service 266 using the ``@webhook()`` decorator. 267 268 Args: 269 webhook_id: The webhook ID as defined in the ``@webhook("id")`` decorator. 270 body: The request body to send. Must be JSON-serializable. 271 headers: Extra HTTP headers to include in the request. 272 method: The HTTP method to use (default ``"POST"``). 273 274 Returns: 275 The webhook's response body, deserialized from JSON. 276 277 Raises: 278 SquidHttpError: If the webhook is not found or returns an error. 279 280 Example:: 281 282 result = await squid.execute_webhook("my-hook", body={"key": "value"}) 283 """ 284 return await self._http.post( 285 f"webhooks/{webhook_id}", 286 body, 287 extra_headers=headers, 288 )
Execute a webhook.
Calls a webhook endpoint defined in a Squid backend service
using the @webhook() decorator.
Arguments:
- webhook_id: The webhook ID as defined in the
@webhook("id")decorator. - body: The request body to send. Must be JSON-serializable.
- headers: Extra HTTP headers to include in the request.
- method: The HTTP method to use (default
"POST").
Returns:
The webhook's response body, deserialized from JSON.
Raises:
- SquidHttpError: If the webhook is not found or returns an error.
Example::
result = await squid.execute_webhook("my-hook", body={"key": "value"})
290 def get_webhook_url(self, webhook_id: str) -> str: 291 """Get the full URL for a webhook endpoint. 292 293 Useful for providing the webhook URL to external services that 294 need to send HTTP requests to your Squid backend. 295 296 Args: 297 webhook_id: The webhook ID. 298 299 Returns: 300 The full URL string (e.g., 301 ``"https://myapp.us-east-1.aws.squid.cloud/webhooks/my-hook"``). 302 303 Example:: 304 305 url = squid.get_webhook_url("stripe-events") 306 # url == "https://myapp-dev.us-east-1.aws.squid.cloud/webhooks/stripe-events" 307 """ 308 return build_url( 309 self._region, self._full_app_id, f"webhooks/{webhook_id}", self._backend_domain 310 )
Get the full URL for a webhook endpoint.
Useful for providing the webhook URL to external services that need to send HTTP requests to your Squid backend.
Arguments:
- webhook_id: The webhook ID.
Returns:
The full URL string (e.g.,
"https://myapp.us-east-1.aws.squid.cloud/webhooks/my-hook").
Example::
url = squid.get_webhook_url("stripe-events")
# url == "https://myapp-dev.us-east-1.aws.squid.cloud/webhooks/stripe-events"
314 async def execute_ai_query( 315 self, 316 integration_id: str, 317 prompt: str, 318 *, 319 options: AiQueryOptions | None = None, 320 response_format: dict[str, Any] | None = None, 321 ) -> dict: 322 """Execute an AI-powered database query. 323 324 Uses AI to generate and execute database queries based on a 325 natural language prompt. 326 327 Args: 328 integration_id: The database integration ID to query against. 329 prompt: A natural language description of the data you want. 330 options: Optional :class:`AiQueryOptions` controlling collection 331 selection, query generation (including ``allowClarification``), 332 result analysis (including ``enableCodeInterpreter``), memory, 333 AI validation, per-stage model overrides via ``aiOptions``, 334 and custom instructions. 335 response_format: Optional structured output format, e.g., 336 ``{"type": "json_schema", "schema": {...}}``. 337 338 Returns: 339 An ``AiQueryResponse`` dict containing: 340 - ``answer`` (str): The AI-generated answer. 341 - ``explanation`` (str): How the answer was derived. 342 - ``executedQueries`` (list): The actual queries that were run. 343 - ``success`` (bool): Whether the query succeeded. 344 - ``usedCodeInterpreter`` (bool): Whether the code 345 interpreter was used to analyze results. 346 - ``clarificationQuestion`` (str): If the AI needs more info. 347 348 Example:: 349 350 result = await squid.execute_ai_query( 351 "my-database", 352 "How many users signed up last week?", 353 options={ 354 "selectCollectionsOptions": {"collectionsToUse": ["users"]}, 355 "analyzeResultsOptions": {"enableCodeInterpreter": True}, 356 }, 357 ) 358 print(result["answer"]) 359 """ 360 return await execute_ai_query( 361 self._http, 362 integration_id, 363 prompt, 364 options=options, 365 response_format=response_format, 366 )
Execute an AI-powered database query.
Uses AI to generate and execute database queries based on a natural language prompt.
Arguments:
- integration_id: The database integration ID to query against.
- prompt: A natural language description of the data you want.
- options: Optional
AiQueryOptionscontrolling collection selection, query generation (includingallowClarification), result analysis (includingenableCodeInterpreter), memory, AI validation, per-stage model overrides viaaiOptions, and custom instructions. - response_format: Optional structured output format, e.g.,
{"type": "json_schema", "schema": {...}}.
Returns:
An
AiQueryResponsedict containing: -answer(str): The AI-generated answer. -explanation(str): How the answer was derived. -executedQueries(list): The actual queries that were run. -success(bool): Whether the query succeeded. -usedCodeInterpreter(bool): Whether the code interpreter was used to analyze results. -clarificationQuestion(str): If the AI needs more info.
Example::
result = await squid.execute_ai_query(
"my-database",
"How many users signed up last week?",
options={
"selectCollectionsOptions": {"collectionsToUse": ["users"]},
"analyzeResultsOptions": {"enableCodeInterpreter": True},
},
)
print(result["answer"])
370 async def close(self) -> None: 371 """Close the HTTP client and release resources. 372 373 Should be called when the Squid client is no longer needed. 374 Alternatively, use the client as an async context manager. 375 """ 376 await self._http.close()
Close the HTTP client and release resources.
Should be called when the Squid client is no longer needed. Alternatively, use the client as an async context manager.
82class SquidHttpError(Exception): 83 """Raised when the Squid API returns an HTTP error response (status >= 400). 84 85 Attributes: 86 status_code: The HTTP status code. 87 url: The URL that was requested. 88 body: The parsed response body, if available. 89 """ 90 91 def __init__(self, status_code: int, message: str, url: str, body: Any = None): 92 self.status_code = status_code 93 self.url = url 94 self.body = body 95 super().__init__(f"HTTP {status_code}: {message} (url={url})")
Raised when the Squid API returns an HTTP error response (status >= 400).
Attributes:
- status_code: The HTTP status code.
- url: The URL that was requested.
- body: The parsed response body, if available.
1033class StableDiffusionOptions(TypedDict, total=False): 1034 """Options for Stable Diffusion Core image generation.""" 1035 1036 modelName: Literal["stable-diffusion-core"] 1037 aspectRatio: Literal["16:9", "1:1", "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21"] 1038 negativePrompt: str 1039 seed: int 1040 stylePreset: str 1041 outputFormat: str
Options for Stable Diffusion Core image generation.
807class TextContextRequest(TypedDict, total=False): 808 """Request to upsert a text context.""" 809 810 contextId: str 811 type: Literal["text"] 812 title: str 813 text: str 814 format: Literal["auto", "markdown", "html", "plain"] 815 """Hint about the format of the text. Defaults to 'auto' (sniffed from content).""" 816 extractImages: bool 817 """Whether to extract images embedded in markdown/HTML text. Defaults to False. 818 819 This is the opposite of the file context default, which is True: a pasted blob's inline 820 images are usually layout chrome, while an uploaded document's images are part of its 821 content. 822 """ 823 imageMinSizePixels: int 824 imageExtractionModel: AiChatModelSelection 825 metadata: dict[str, Any] 826 options: AiContextTextOptions 827 scopes: list[str] 828 """Access scopes granting read access to this context. Only meaningful on a knowledge base 829 with ``accessControl.mode: 'enforced'``. Omitted on a re-ingest keeps existing scopes; an 830 empty list makes the context visible to every caller. 831 """
Request to upsert a text context.
Hint about the format of the text. Defaults to 'auto' (sniffed from content).
Whether to extract images embedded in markdown/HTML text. Defaults to False.
This is the opposite of the file context default, which is True: a pasted blob's inline images are usually layout chrome, while an uploaded document's images are part of its content.
549class UpsertAgentOptions(TypedDict, total=False): 550 """Options for creating/updating an agent.""" 551 552 description: str 553 """Description of the agent's purpose.""" 554 isPublic: bool 555 """Whether the agent is publicly accessible.""" 556 auditLog: bool 557 """Enable audit logging.""" 558 auditLogFullContext: bool 559 """Record the full agent context (system instructions and retrieved knowledge-base content) in the audit log.""" 560 apiKey: str 561 """API key for this agent.""" 562 mcpServer: AiAgentMcpServerConfig 563 """Optional configuration for exposing the agent as an MCP server.""" 564 options: AiChatOptions 565 """Default chat options."""
Options for creating/updating an agent.
1286class WebAiSearchResponse(TypedDict): 1287 """Response from AI web search.""" 1288 1289 markdownText: str 1290 citedUrls: list[dict[str, str]] 1291 """Pages the answer cites. A terse answer cites nothing even when the search ran.""" 1292 1293 consultedUrls: list[str] 1294 """Pages the search opened, whether or not the answer cites them."""
Response from AI web search.
16class WebClient: 17 """Web utilities: AI search, URL content, short URLs.""" 18 19 def __init__(self, http: HttpTransport) -> None: 20 self._http = http 21 22 async def ai_search( 23 self, query: str, allowed_domains: list[str] | None = None 24 ) -> WebAiSearchResponse: 25 """Perform an AI-powered web search. 26 27 When allowed_domains is provided, the search is restricted to those domains 28 (subdomains included) and every URL in the response -- cited or consulted -- 29 belongs to one of them. Squid enforces this over the consulted pages; 30 citations arrive already restricted. 31 32 Returns WebAiSearchResponse with 'markdownText', 'citedUrls' and 'consultedUrls'. 33 """ 34 body: dict[str, object] = {"query": query} 35 if allowed_domains is not None: 36 body["allowedDomains"] = allowed_domains 37 return await self._http.post("squid-api/v1/web/aiSearch", body) 38 39 async def get_url_content(self, url: str) -> str: 40 """Fetch and extract content from a URL as markdown.""" 41 result = await self._http.post("squid-api/v1/web/getUrlContent", {"url": url}) 42 if isinstance(result, dict): 43 return result.get("markdownText", "") 44 return str(result) if result else "" 45 46 async def create_short_url( 47 self, 48 url: str, 49 *, 50 seconds_to_live: int | None = None, 51 file_extension: str | None = None, 52 ) -> WebShortUrlResponse: 53 """Create a short URL. 54 55 Returns WebShortUrlResponse with 'id', 'shortUrl', 'expiry'. 56 """ 57 body: dict = {"url": url} 58 if seconds_to_live is not None: 59 body["secondsToLive"] = seconds_to_live 60 if file_extension is not None: 61 body["fileExtension"] = file_extension 62 return await self._http.post("squid-api/v1/web/createShortUrl", body) 63 64 async def create_short_urls( 65 self, 66 urls: list[str], 67 *, 68 seconds_to_live: int | None = None, 69 file_extension: str | None = None, 70 ) -> WebShortUrlBulkResponse: 71 """Create multiple short URLs in bulk. 72 73 Returns WebShortUrlBulkResponse with 'ids', 'shortUrls', 'expiry'. 74 """ 75 body: dict = {"urls": urls} 76 if seconds_to_live is not None: 77 body["secondsToLive"] = seconds_to_live 78 if file_extension is not None: 79 body["fileExtension"] = file_extension 80 return await self._http.post("squid-api/v1/web/createShortUrls", body) 81 82 async def delete_short_url(self, url_id: str) -> None: 83 """Delete a short URL.""" 84 await self._http.post("squid-api/v1/web/deleteShortUrl", {"id": url_id}) 85 86 async def delete_short_urls(self, url_ids: list[str]) -> None: 87 """Delete multiple short URLs.""" 88 await self._http.post("squid-api/v1/web/deleteShortUrls", {"ids": url_ids})
Web utilities: AI search, URL content, short URLs.
22 async def ai_search( 23 self, query: str, allowed_domains: list[str] | None = None 24 ) -> WebAiSearchResponse: 25 """Perform an AI-powered web search. 26 27 When allowed_domains is provided, the search is restricted to those domains 28 (subdomains included) and every URL in the response -- cited or consulted -- 29 belongs to one of them. Squid enforces this over the consulted pages; 30 citations arrive already restricted. 31 32 Returns WebAiSearchResponse with 'markdownText', 'citedUrls' and 'consultedUrls'. 33 """ 34 body: dict[str, object] = {"query": query} 35 if allowed_domains is not None: 36 body["allowedDomains"] = allowed_domains 37 return await self._http.post("squid-api/v1/web/aiSearch", body)
Perform an AI-powered web search.
When allowed_domains is provided, the search is restricted to those domains (subdomains included) and every URL in the response -- cited or consulted -- belongs to one of them. Squid enforces this over the consulted pages; citations arrive already restricted.
Returns WebAiSearchResponse with 'markdownText', 'citedUrls' and 'consultedUrls'.
39 async def get_url_content(self, url: str) -> str: 40 """Fetch and extract content from a URL as markdown.""" 41 result = await self._http.post("squid-api/v1/web/getUrlContent", {"url": url}) 42 if isinstance(result, dict): 43 return result.get("markdownText", "") 44 return str(result) if result else ""
Fetch and extract content from a URL as markdown.
46 async def create_short_url( 47 self, 48 url: str, 49 *, 50 seconds_to_live: int | None = None, 51 file_extension: str | None = None, 52 ) -> WebShortUrlResponse: 53 """Create a short URL. 54 55 Returns WebShortUrlResponse with 'id', 'shortUrl', 'expiry'. 56 """ 57 body: dict = {"url": url} 58 if seconds_to_live is not None: 59 body["secondsToLive"] = seconds_to_live 60 if file_extension is not None: 61 body["fileExtension"] = file_extension 62 return await self._http.post("squid-api/v1/web/createShortUrl", body)
Create a short URL.
Returns WebShortUrlResponse with 'id', 'shortUrl', 'expiry'.
64 async def create_short_urls( 65 self, 66 urls: list[str], 67 *, 68 seconds_to_live: int | None = None, 69 file_extension: str | None = None, 70 ) -> WebShortUrlBulkResponse: 71 """Create multiple short URLs in bulk. 72 73 Returns WebShortUrlBulkResponse with 'ids', 'shortUrls', 'expiry'. 74 """ 75 body: dict = {"urls": urls} 76 if seconds_to_live is not None: 77 body["secondsToLive"] = seconds_to_live 78 if file_extension is not None: 79 body["fileExtension"] = file_extension 80 return await self._http.post("squid-api/v1/web/createShortUrls", body)
Create multiple short URLs in bulk.
Returns WebShortUrlBulkResponse with 'ids', 'shortUrls', 'expiry'.
1278class WebShortUrlBulkResponse(TypedDict): 1279 """Response from creating bulk short URLs.""" 1280 1281 ids: list[str] 1282 shortUrls: list[str] 1283 expiry: str
Response from creating bulk short URLs.
1270class WebShortUrlResponse(TypedDict): 1271 """Response from creating a short URL.""" 1272 1273 id: str 1274 shortUrl: str 1275 expiry: str
Response from creating a short URL.