Skip to content

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

getChatSessionsForUser(userId: string, includeAnonymousSessions: boolean): Promise<AiChatSession[]>

Returns the chat sessions owned by a user that have not expired.

ParameterTypeDescription
userIdstringID of the user who owns the sessions.
includeAnonymousSessionsbooleanIf 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(chatSessionId: string, asUserId: string | 'system'): Promise<AiChatSession>

Loads one chat session, including its messages.

ParameterTypeDescription
chatSessionIdstringID of the chat session, as returned by SimpleAi.chatSessionId.
asUserIdstring | '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

FieldTypeDescription
idstringID of the chat session.
firstHumanMessagestringThe first message the user sent, shortened, for use as a title.
ownerUserIdstring | nullID of the owning user, or null for an anonymous session.
createDateDateWhen the session was created.
updateDateDateWhen the session was last saved.
expirationDateDate | nullWhen the session expires, or null if it never expires. Lowgile deletes expired sessions automatically.
detailsAiChatSessionDetailsHolds 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(chatSession: AiChatSession): Promise<void>

Saves a chat session to the database, creating or updating it.

ParameterTypeDescription
chatSessionAiChatSessionThe 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(chatSessionId: string, asUserId: string | 'system'): Promise<void>

Deletes a chat session and its messages.

ParameterTypeDescription
chatSessionIdstringID of the chat session to delete.
asUserIdstring | '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

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(connectionOptions: ConnectionOptions, modelOptions?: ModelOptions)

Creates a conversation with the model described by connectionOptions.

ParameterTypeDescription
connectionOptionsConnectionOptionsHow to reach the model. An AI Connection configuration item (This.$Config.<name>) has this shape.
modelOptionsModelOptionsOptional. Model settings and chat session handling.

ConnectionOptions fields

ConnectionOptions is one of AzureOpenAiOptions, DeepSeekOptions, GeminiOptions, AnthropicOptions or OllamaOptions, selected by aiType.

FieldTypeRequiredDescription
aiType'AzureOpenAi' | 'DeepSeek' | 'Gemini' | 'Anthropic' | 'Ollama'YesThe AI provider.
apiKeystringYesAPI key for the provider.
usdPer1000InputTokensnumberNoPrice per 1000 input tokens, used by getTokenUsage().
usdPer1000OutputTokensnumberNoPrice per 1000 output tokens, used by getTokenUsage().
tracingEnabledbooleanNoEnables LangChain tracing (for example to LangSmith).
tracingEndpointstringNoTracing endpoint, used if tracingEnabled is true.
tracingApiKeystringNoAPI key for the tracing endpoint.
instanceNamestringAzureOpenAi only, requiredName of the Azure OpenAI instance.
deploymentNamestringAzureOpenAi only, requiredName of the chat model deployment.
embeddingsDeploymentNamestringAzureOpenAi onlyName of the embeddings deployment, used by embedDocuments() and embedQuery().
apiVersionstringAzureOpenAi onlyAzure OpenAI API version.
modelstringDeepSeek, Gemini, OllamaModel name. Defaults to deepseek-chat for DeepSeek and gemini-1.5-flash for Gemini. For DeepSeek the only accepted value is 'deepseek-chat'.
apiBasestringDeepSeek, OllamaBase URL of the API. Defaults to https://api.deepseek.com/v1 for DeepSeek.
numCtxnumberOllama onlySize of the context window.

ModelOptions fields

FieldTypeRequiredDescription
temperaturenumberNoSampling temperature. Defaults to 0.
chatSessionLifetime{ minutes: number } | 'forever' | 'none'NoHow 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.
chatSessionIdstringNoID of a stored chat session to resume. If omitted, Lowgile generates a new ID.
chatSessionStartNewIfExpiredbooleanNoIf 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?.
isAnonymousSessionbooleanNoIf true, a new stored session has no owner. Otherwise it is owned by the current user.
cachebooleanNoEnables LangChain’s response cache for the model.
maxConcurrencynumberNoMaximum number of concurrent requests to the model.
maxRetriesnumberNoMaximum 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.

get chatSessionId(): string

Returns 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: Semaphore

The 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(): Promise<void>

Removes all messages from the conversation history and resets the token counters of getTokenUsage().

Returns: Promise<void> · Availability: Server

addSystemMessage(text: string): Promise<void>

Adds a system message, typically instructions for the model, to the conversation history.

ParameterTypeDescription
textstringText of the message.

Returns: Promise<void> · Availability: Server

addHumanMessage(text: string): Promise<void>

Adds a message from the user to the conversation history without querying the model.

ParameterTypeDescription
textstringText of the message.

Returns: Promise<void> · Availability: Server

addAiMessage(text: string): Promise<void>

Adds a message as if the model had written it, for example to give the model an example answer.

ParameterTypeDescription
textstringText of the message.

Returns: Promise<void> · Availability: Server

addMessages(messages: (['system' | 'human' | 'ai', string] | BaseMessage)[]): Promise<void>

Adds several messages to the conversation history at once.

ParameterTypeDescription
messages(['system' | 'human' | 'ai', string] | BaseMessage)[]Messages as [type, text] pairs or as LangChain BaseMessage objects.

Returns: Promise<void> · Availability: Server

addTextDocuments(textOrFile: string | BinaryFile<BinaryData | string>): void

Queues a text document to be sent with the next query.

ParameterTypeDescription
textOrFilestring | 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(binaryDatas: BinaryDataOrFile<BinaryData | BinaryData[]>): Promise<void>

Queues one or more PDF documents to be sent with the next query. Works like addImageDocuments() without options.

ParameterTypeDescription
binaryDatasBinaryDataOrFile<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(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.

ParameterTypeDescription
datasBinaryDataOrFile<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.
optionsAddImageDocumentsOptionsOptional. Conversion settings.

AddImageDocumentsOptions fields

FieldTypeRequiredDescription
pdfToPngConversionScalenumberNoScale 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<Z extends Sys.Data.Zod.ZodObject<any>>(name: string, description: string, inputSchema: Z, toolFunction: (input: Sys.Data.Zod.infer<Z>) => any, responseHasArtifact?: boolean): void
addTool<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): void

Registers 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.

ParameterTypeDescription
namestringName of the tool, as the model sees it.
descriptionstringWhat the tool does. The model uses this to decide when to call it.
inputSchema / inputSchemaFnZ | ((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>) => anyThe function to run. It receives the parsed input; its return value is sent to the model.
responseHasArtifactbooleanOptional. If true, toolFunction must return a [content, artifact] pair: only content is sent to the model.

Returns: void · Availability: Server

removeTool(name: string): void

Removes a tool registered with addTool().

ParameterTypeDescription
namestringName of the tool.

Returns: void · Availability: Server

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.

ParameterTypeDescription
querystringThe question or instruction.
_optionsQueryOptionsOptional. 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<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.

ParameterTypeDescription
querystringThe question or instruction.
outputSchema / outputSchemaFnZ | ((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.
_optionsQueryOptionsOptional. 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(): { 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(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.

ParameterTypeDescription
textsOrDocuments(string | DocumentInterface)[]Texts or LangChain documents to split.
optionsRecursiveCharacterTextSplitterParamsOptional. Splitter settings such as chunkSize, chunkOverlap and separators. See the LangChain text splitter documentation.
formatLanguageSupportedTextSplitterLanguageOptional. 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(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().

ParameterTypeDescription
textsOrDocuments(string | DocumentInterface)[]Texts or LangChain documents to embed.
optionsRecursiveCharacterTextSplitterParamsOptional. Splitter settings, as for split().
formatLanguageSupportedTextSplitterLanguageOptional. 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(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.

ParameterTypeDescription
queryTextstringThe text to embed.

Returns: Promise<number[]> · Availability: Server