Sys.Ai
Sys.Ai connects server-side code to a large language model (LLM). The SimpleAi class wraps one conversation with a model: you add messages, documents and tools, then query the model for text or for a structured object. The functions manage the chat sessions that SimpleAi stores in the database so that a conversation can be resumed later.
A SimpleAi instance is usually created from an AI Connection configuration item (This.$Config.<name>), which provides the connection fields described under the constructor.
Availability: Server
Functions
Section titled “Functions”getChatSessionsForUser()
Section titled “getChatSessionsForUser()”getChatSessionsForUser(userId: string, includeAnonymousSessions: boolean): Promise<AiChatSession[]>Returns the chat sessions owned by a user that have not expired.
| Parameter | Type | Description |
|---|---|---|
userId | string | ID of the user who owns the sessions. |
includeAnonymousSessions | boolean | If true, sessions without an owner (created with isAnonymousSession: true) are added to the result. |
The sessions are returned without their messages. Use getChatSessionDetailsById() to load the messages of one session.
Returns: Promise<AiChatSession[]> · Availability: Server
getChatSessionDetailsById()
Section titled “getChatSessionDetailsById()”getChatSessionDetailsById(chatSessionId: string, asUserId: string | 'system'): Promise<AiChatSession>Loads one chat session, including its messages.
| Parameter | Type | Description |
|---|---|---|
chatSessionId | string | ID of the chat session, as returned by SimpleAi.chatSessionId. |
asUserId | string | 'system' | ID of the user on whose behalf the session is read. Lowgile throws Access to chat session forbidden if this user does not own the session. Pass 'system' to skip the check. |
AiChatSession fields
| Field | Type | Description |
|---|---|---|
id | string | ID of the chat session. |
firstHumanMessage | string | The first message the user sent, shortened, for use as a title. |
ownerUserId | string | null | ID of the owning user, or null for an anonymous session. |
createDate | Date | When the session was created. |
updateDate | Date | When the session was last saved. |
expirationDate | Date | null | When the session expires, or null if it never expires. Lowgile deletes expired sessions automatically. |
details | AiChatSessionDetails | Holds messages, the conversation as an array of LangChain StoredMessage objects. |
Returns: Promise<AiChatSession> · Availability: Server
Note
If no session with this ID exists, or it has expired, the promise resolves to null, although the declared type does not include null.
saveChatSession()
Section titled “saveChatSession()”saveChatSession(chatSession: AiChatSession): Promise<void>Saves a chat session to the database, creating or updating it.
| Parameter | Type | Description |
|---|---|---|
chatSession | AiChatSession | The session to save. It must be an AiChatSession instance, for example one returned by getChatSessionDetailsById(). Lowgile throws if a session with the same ID exists and belongs to another user. |
Returns: Promise<void> · Availability: Server
deleteChatSession()
Section titled “deleteChatSession()”deleteChatSession(chatSessionId: string, asUserId: string | 'system'): Promise<void>Deletes a chat session and its messages.
| Parameter | Type | Description |
|---|---|---|
chatSessionId | string | ID of the chat session to delete. |
asUserId | string | 'system' | ID of the user on whose behalf the session is deleted. Lowgile throws Access to chat session forbidden if this user does not own the session. Pass 'system' to skip the check. |
Returns: Promise<void> · Availability: Server
Classes
Section titled “Classes”SimpleAi
Section titled “SimpleAi”SimpleAi holds one conversation with an LLM. Messages added with the add… methods become part of the conversation history. Documents added with addTextDocuments(), addImageDocuments() or addPdfDocuments() are queued and sent together with the next query. Each query adds the query and the model’s answer to the history, so later queries can refer to earlier ones.
Lowgile supports the AI types AzureOpenAi, Gemini, Anthropic, DeepSeek and Ollama.
const ai = new Sys.Ai.SimpleAi(This.$Config.AiConnection)await ai.addSystemMessage('You extract data from supplier invoices.')
const file = await Sys.Fs.readFile('working', 'invoices/invoice-0042.pdf', { format: 'binary' })await ai.addPdfDocuments({ data: file.content, fileName: 'invoice-0042.pdf' })
const invoice = await ai.queryAndReturnStructuredObject( 'Extract the invoice number, the invoice date and the total amount.', (zod) => zod.object({ invoiceNumber: zod.string(), invoiceDate: zod.string().describe('Date in ISO format, e.g. 2026-10-28'), totalAmount: zod.number(), }),)// invoice is typed as { invoiceNumber: string; invoiceDate: string; totalAmount: number }constructor()
Section titled “constructor()”constructor(connectionOptions: ConnectionOptions, modelOptions?: ModelOptions)Creates a conversation with the model described by connectionOptions.
| Parameter | Type | Description |
|---|---|---|
connectionOptions | ConnectionOptions | How to reach the model. An AI Connection configuration item (This.$Config.<name>) has this shape. |
modelOptions | ModelOptions | Optional. Model settings and chat session handling. |
ConnectionOptions fields
ConnectionOptions is one of AzureOpenAiOptions, DeepSeekOptions, GeminiOptions, AnthropicOptions or OllamaOptions, selected by aiType.
| Field | Type | Required | Description |
|---|---|---|---|
aiType | 'AzureOpenAi' | 'DeepSeek' | 'Gemini' | 'Anthropic' | 'Ollama' | Yes | The AI provider. |
apiKey | string | Yes | API key for the provider. |
usdPer1000InputTokens | number | No | Price per 1000 input tokens, used by getTokenUsage(). |
usdPer1000OutputTokens | number | No | Price per 1000 output tokens, used by getTokenUsage(). |
tracingEnabled | boolean | No | Enables LangChain tracing (for example to LangSmith). |
tracingEndpoint | string | No | Tracing endpoint, used if tracingEnabled is true. |
tracingApiKey | string | No | API key for the tracing endpoint. |
instanceName | string | AzureOpenAi only, required | Name of the Azure OpenAI instance. |
deploymentName | string | AzureOpenAi only, required | Name of the chat model deployment. |
embeddingsDeploymentName | string | AzureOpenAi only | Name of the embeddings deployment, used by embedDocuments() and embedQuery(). |
apiVersion | string | AzureOpenAi only | Azure OpenAI API version. |
model | string | DeepSeek, Gemini, Ollama | Model name. Defaults to deepseek-chat for DeepSeek and gemini-1.5-flash for Gemini. For DeepSeek the only accepted value is 'deepseek-chat'. |
apiBase | string | DeepSeek, Ollama | Base URL of the API. Defaults to https://api.deepseek.com/v1 for DeepSeek. |
numCtx | number | Ollama only | Size of the context window. |
ModelOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
temperature | number | No | Sampling temperature. Defaults to 0. |
chatSessionLifetime | { minutes: number } | 'forever' | 'none' | No | How long the conversation is kept. { minutes: 0 } (the default) keeps it only for the lifetime of this instance. A positive number of minutes or 'forever' also stores it in the database as a chat session, which can be resumed with chatSessionId. The expiration is extended after every query. 'none' stores nothing. |
chatSessionId | string | No | ID of a stored chat session to resume. If omitted, Lowgile generates a new ID. |
chatSessionStartNewIfExpired | boolean | No | If true and the session given in chatSessionId no longer exists, a new session is started under that ID. Otherwise the first query throws Chat session not found; maybe it has expired?. |
isAnonymousSession | boolean | No | If true, a new stored session has no owner. Otherwise it is owned by the current user. |
cache | boolean | No | Enables LangChain’s response cache for the model. |
maxConcurrency | number | No | Maximum number of concurrent requests to the model. |
maxRetries | number | No | Maximum number of retries for a failed request. |
A resumed session must belong to the current user: Lowgile throws Access to chat session forbidden otherwise. Errors while loading the session are thrown by the first query.
Availability: Server
Note
With chatSessionLifetime: 'none', the conversation is still remembered between queries on the same instance. It is only not stored in the database, the same as with the default { minutes: 0 }. A session stored with isAnonymousSession: true cannot be resumed through chatSessionId, because the ownership check fails.
chatSessionId
Section titled “chatSessionId”get chatSessionId(): stringReturns the ID of the stored chat session, or undefined if the conversation is not stored (see chatSessionLifetime). Pass this ID as chatSessionId to resume the conversation later. The session is set up asynchronously, so read this property after the first query.
Type: string · Availability: Server
chatSessionUpdateSemaphore
Section titled “chatSessionUpdateSemaphore”chatSessionUpdateSemaphore: SemaphoreThe lock SimpleAi uses to save the chat session one query at a time. App code does not normally need it.
Type: Semaphore · Availability: Server
clear()
Section titled “clear()”clear(): Promise<void>Removes all messages from the conversation history and resets the token counters of getTokenUsage().
Returns: Promise<void> · Availability: Server
addSystemMessage()
Section titled “addSystemMessage()”addSystemMessage(text: string): Promise<void>Adds a system message, typically instructions for the model, to the conversation history.
| Parameter | Type | Description |
|---|---|---|
text | string | Text of the message. |
Returns: Promise<void> · Availability: Server
addHumanMessage()
Section titled “addHumanMessage()”addHumanMessage(text: string): Promise<void>Adds a message from the user to the conversation history without querying the model.
| Parameter | Type | Description |
|---|---|---|
text | string | Text of the message. |
Returns: Promise<void> · Availability: Server
addAiMessage()
Section titled “addAiMessage()”addAiMessage(text: string): Promise<void>Adds a message as if the model had written it, for example to give the model an example answer.
| Parameter | Type | Description |
|---|---|---|
text | string | Text of the message. |
Returns: Promise<void> · Availability: Server
addMessages()
Section titled “addMessages()”addMessages(messages: (['system' | 'human' | 'ai', string] | BaseMessage)[]): Promise<void>Adds several messages to the conversation history at once.
| Parameter | Type | Description |
|---|---|---|
messages | (['system' | 'human' | 'ai', string] | BaseMessage)[] | Messages as [type, text] pairs or as LangChain BaseMessage objects. |
Returns: Promise<void> · Availability: Server
addTextDocuments()
Section titled “addTextDocuments()”addTextDocuments(textOrFile: string | BinaryFile<BinaryData | string>): voidQueues a text document to be sent with the next query.
| Parameter | Type | Description |
|---|---|---|
textOrFile | string | BinaryFile<BinaryData | string> | The text, or a file object with data (text or binary data read as UTF-8) and an optional fileName, which is passed to the model. |
Returns: void · Availability: Server
addPdfDocuments()
Section titled “addPdfDocuments()”addPdfDocuments(binaryDatas: BinaryDataOrFile<BinaryData | BinaryData[]>): Promise<void>Queues one or more PDF documents to be sent with the next query. Works like addImageDocuments() without options.
| Parameter | Type | Description |
|---|---|---|
binaryDatas | BinaryDataOrFile<BinaryData | BinaryData[]> | The binary data of one or more files, or a file object with data, fileName and mimeType. |
Returns: Promise<void> · Availability: Server
addImageDocuments()
Section titled “addImageDocuments()”addImageDocuments(datas: BinaryDataOrFile<BinaryData | BinaryData[]>, options?: AddImageDocumentsOptions): Promise<void>Queues one or more images to be sent with the next query. PDF and DOCX files are converted to one PNG image per page first.
| Parameter | Type | Description |
|---|---|---|
datas | BinaryDataOrFile<BinaryData | BinaryData[]> | The binary data of one or more files, or a file object with data, fileName and mimeType. If mimeType is missing, Lowgile detects the image format and throws if it does not recognize it. |
options | AddImageDocumentsOptions | Optional. Conversion settings. |
AddImageDocumentsOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
pdfToPngConversionScale | number | No | Scale factor used when converting PDF or DOCX pages to PNG images. Higher values give sharper images and use more tokens. |
Returns: Promise<void> · Availability: Server
addTool()
Section titled “addTool()”addTool<Z extends Sys.Data.Zod.ZodObject<any>>(name: string, description: string, inputSchema: Z, toolFunction: (input: Sys.Data.Zod.infer<Z>) => any, responseHasArtifact?: boolean): voidaddTool<Z extends Sys.Data.Zod.ZodObject<any>>(name: string, description: string, inputSchemaFn: (zod: typeof Sys.Data.Zod) => Z, toolFunction: (input: Sys.Data.Zod.infer<Z>) => any, responseHasArtifact?: boolean): voidRegisters a function that the model can call while answering a query. Lowgile runs the function when the model asks for it and passes the result back to the model. Adding a tool with an existing name replaces it.
| Parameter | Type | Description |
|---|---|---|
name | string | Name of the tool, as the model sees it. |
description | string | What the tool does. The model uses this to decide when to call it. |
inputSchema / inputSchemaFn | Z | ((zod: typeof Sys.Data.Zod) => Z) | A Zod object schema for the tool’s input, or a function that receives Sys.Data.Zod and returns one. |
toolFunction | (input: Sys.Data.Zod.infer<Z>) => any | The function to run. It receives the parsed input; its return value is sent to the model. |
responseHasArtifact | boolean | Optional. If true, toolFunction must return a [content, artifact] pair: only content is sent to the model. |
Returns: void · Availability: Server
removeTool()
Section titled “removeTool()”removeTool(name: string): voidRemoves a tool registered with addTool().
| Parameter | Type | Description |
|---|---|---|
name | string | Name of the tool. |
Returns: void · Availability: Server
queryAndReturnText()
Section titled “queryAndReturnText()”queryAndReturnText(query: string, _options?: QueryOptions): Promise<string | (ContentBlock | ContentBlock.Text)[]>Sends the query and any queued documents to the model and returns its answer. If tools are registered, the model may call them before answering.
| Parameter | Type | Description |
|---|---|---|
query | string | The question or instruction. |
_options | QueryOptions | Optional. Has one field, timeoutMs (number). |
If the query fails, the queued documents stay queued for the next query.
Returns: Promise<string | (ContentBlock | ContentBlock.Text)[]>: usually a string; some models return an array of content blocks. · Availability: Server
Note
timeoutMs is currently ignored.
queryAndReturnStructuredObject()
Section titled “queryAndReturnStructuredObject()”queryAndReturnStructuredObject<Z extends Sys.Data.Zod.ZodObject<any>>(query: string, outputSchema: Z, _options?: QueryOptions): Promise<Sys.Data.Zod.infer<Z>>queryAndReturnStructuredObject<Z extends Sys.Data.Zod.ZodObject<any>>(query: string, outputSchemaFn: (zod: typeof Sys.Data.Zod) => Z, _options?: QueryOptions): Promise<Sys.Data.Zod.infer<Z>>Sends the query and any queued documents to the model and returns its answer as an object that matches a Zod schema. See the example at the top of this class.
| Parameter | Type | Description |
|---|---|---|
query | string | The question or instruction. |
outputSchema / outputSchemaFn | Z | ((zod: typeof Sys.Data.Zod) => Z) | A Zod object schema for the answer, or a function that receives Sys.Data.Zod and returns one. Field descriptions (.describe()) are passed to the model. |
_options | QueryOptions | Optional. Has one field, timeoutMs (number), which is currently ignored. |
If tools are registered, the model may call them first. The answer is added to the conversation history as JSON text. If the query fails, the queued documents stay queued for the next query.
Returns: Promise<Sys.Data.Zod.infer<Z>> · Availability: Server
getTokenUsage()
Section titled “getTokenUsage()”getTokenUsage(): { inputTokens: number; outputTokens: number; totalTokens: number; priceInUsd: number }Returns the number of tokens used by this instance since it was created or last cleared.
priceInUsd is calculated from usdPer1000InputTokens and usdPer1000OutputTokens of the connection options, and is null unless both are set. The counts come from the usage the provider reports; they stay at 0 if the provider does not report usage in the format LangChain expects.
Returns: { inputTokens: number; outputTokens: number; totalTokens: number; priceInUsd: number } · Availability: Server
split()
Section titled “split()”split(textsOrDocuments: (string | DocumentInterface)[], options?: RecursiveCharacterTextSplitterParams, formatLanguage?: SupportedTextSplitterLanguage): Promise<Document<Record<string, any>>[]>Splits texts into smaller chunks with LangChain’s RecursiveCharacterTextSplitter, for example before embedding them.
| Parameter | Type | Description |
|---|---|---|
textsOrDocuments | (string | DocumentInterface)[] | Texts or LangChain documents to split. |
options | RecursiveCharacterTextSplitterParams | Optional. Splitter settings such as chunkSize, chunkOverlap and separators. See the LangChain text splitter documentation. |
formatLanguage | SupportedTextSplitterLanguage | Optional. Splits along the syntax of a language such as 'markdown' or 'html' instead of plain characters. |
Returns: Promise<Document<Record<string, any>>[]> · Availability: Server
Note
If formatLanguage is set, the text is always split as HTML, whichever language is given.
embedDocuments()
Section titled “embedDocuments()”embedDocuments(textsOrDocuments: (string | DocumentInterface)[], options?: RecursiveCharacterTextSplitterParams, formatLanguage?: SupportedTextSplitterLanguage): Promise<(readonly [DocumentInterface<Record<string, any>>, number[]])[]>Calculates an embedding vector for each text, for example to store it for a similarity search. If options or formatLanguage is given, the texts are split first, as with split().
| Parameter | Type | Description |
|---|---|---|
textsOrDocuments | (string | DocumentInterface)[] | Texts or LangChain documents to embed. |
options | RecursiveCharacterTextSplitterParams | Optional. Splitter settings, as for split(). |
formatLanguage | SupportedTextSplitterLanguage | Optional. Language for splitting, as for split(). |
Returns: Promise<(readonly [DocumentInterface<Record<string, any>>, number[]])[]>: pairs of document and embedding vector. · Availability: Server
Note
Embeddings use the OpenAI embeddings API with the connection’s settings. They work with AzureOpenAi connections that set embeddingsDeploymentName; with the other AI types the request fails.
embedQuery()
Section titled “embedQuery()”embedQuery(queryText: string): Promise<number[]>Calculates the embedding vector for a search text, to compare with vectors from embedDocuments(). The same restriction on AI types applies.
| Parameter | Type | Description |
|---|---|---|
queryText | string | The text to embed. |
Returns: Promise<number[]> · Availability: Server
Related
Section titled “Related”- AI Connection configuration item
- AI services
- Return structured AI objects
- Extract structured data from a PDF
- Sys.Data (provides
Sys.Data.Zod) - Sys API overview