graphlit-client
Version:
Graphlit API Client for TypeScript
1,330 lines • 389 kB
JavaScript
import jwt from "jsonwebtoken";
// Apollo core (React-free) - ESM import
import { ApolloClient, InMemoryCache, createHttpLink, ApolloLink, ApolloError, } from "@apollo/client/core/index.js";
// Apollo retry link for resilient error handling
import { RetryLink } from "@apollo/client/link/retry/index.js";
import gql from "graphql-tag";
import { attachPartialErrors } from "./partial-errors.js";
import * as Types from "./generated/graphql-types.js";
import * as Documents from "./generated/graphql-documents.js";
import { getServiceType, getModelName, getModelEnum, isOpenAIResponsesEligibleModel, } from "./model-mapping.js";
import { StuckDetector } from "./helpers/stuck-detector.js";
import { TurnEvaluator } from "./helpers/turn-evaluator.js";
import { TokenBudgetTracker, truncateToolResult, windowToolRounds, estimateTokens, DEFAULT_CONTEXT_STRATEGY, } from "./helpers/context-management.js";
import { ProviderError } from "./types/internal.js";
import { UIEventAdapter } from "./streaming/ui-event-adapter.js";
import { formatMessagesForOpenAI, formatMessagesForOpenAIResponsesInitialRound, extractInstructionsForOpenAIResponses, extractSystemInstructionParts, buildResponsesFunctionCallOutputItems, formatToolsForOpenAIResponses, formatMessagesForAnthropic, formatMessagesForGoogle, formatMessagesForMistral, formatMessagesForBedrock, } from "./streaming/llm-formatters.js";
import { streamWithOpenAIResponses, } from "./streaming/openai-responses.js";
import { streamWithOpenAI, streamWithAnthropic, streamWithGoogle, streamWithGroq, streamWithCerebras, streamWithCohere, streamWithMistral, streamWithBedrock, streamWithDeepseek, streamWithXai, } from "./streaming/providers.js";
// Optional imports for streaming LLM clients
// These are peer dependencies and may not be installed
// We need to use createRequire for optional dependencies to avoid build errors
import { createRequire } from "node:module";
const optionalRequire = createRequire(import.meta.url);
let OpenAI;
let Anthropic;
let GoogleGenAI;
let Groq;
let CohereClient;
let CohereClientV2;
let Mistral;
let BedrockRuntimeClient;
let Cerebras;
// Special-purpose lightweight conversation query for agent-flow visualization.
// This is hand-written instead of generated so UI clients can avoid fetching
// heavy citation/content/artifact fields without changing codegen templates.
const GetConversationFlow = gql `
query GetConversationFlow($id: ID!, $correlationId: String) {
conversation(id: $id, correlationId: $correlationId) {
id
name
creationDate
modifiedDate
state
correlationId
type
transcriptUri
turns {
index
messages {
role
author
message
toolCalls {
id
name
arguments
startedAt
completedAt
durationMs
status
failedAt
firstStatusAt
}
tokens
throughput
ttft
completionTime
timestamp
modelService
model
data
mimeType
toolCallId
toolCallResponse
thinkingContent
thinkingSignature
}
tokens
timestamp
text
relevance
summary
}
messageCount
turnCount
agent {
id
}
persona {
id
name
}
specification {
id
name
}
parent {
id
name
}
children {
id
name
}
}
}
`;
function nowIsoString() {
return new Date().toISOString();
}
function toTerminalToolStatus(error) {
return error
? Types.ToolExecutionStatus.Failed
: Types.ToolExecutionStatus.Completed;
}
function normalizeToolCallForExecution(toolCall) {
return {
__typename: "ConversationToolCall",
id: toolCall.id,
name: toolCall.name,
arguments: toolCall.arguments,
startedAt: toolCall.startedAt ?? undefined,
completedAt: toolCall.completedAt ?? undefined,
durationMs: toolCall.durationMs ?? undefined,
status: toolCall.status ?? undefined,
failedAt: toolCall.failedAt ?? undefined,
firstStatusAt: toolCall.firstStatusAt ?? undefined,
};
}
// Default eligible OpenAI GPT-5.4+ models to Responses. Explicit
// `useResponsesApi: false` still forces legacy Chat Completions.
const OPENAI_RESPONSES_AUTO_ROUTING_ENABLED = true;
function buildConversationToolCallFromResult(toolResult) {
return {
__typename: "ConversationToolCall",
id: toolResult.id,
name: toolResult.name,
arguments: typeof toolResult.arguments === "string"
? toolResult.arguments
: JSON.stringify(toolResult.arguments ?? {}),
startedAt: toolResult.startedAt,
completedAt: toolResult.completedAt,
durationMs: toolResult.durationMs ?? toolResult.duration,
status: toolResult.status,
failedAt: toolResult.failedAt,
firstStatusAt: toolResult.startedAt,
};
}
function appendSystemMessages(messages, systemPrompt, additionalSystemInstructions) {
if (systemPrompt?.trim()) {
messages.push({
__typename: "ConversationMessage",
role: Types.ConversationRoleTypes.System,
message: systemPrompt,
timestamp: new Date().toISOString(),
});
}
if (additionalSystemInstructions?.trim()) {
messages.push({
__typename: "ConversationMessage",
role: Types.ConversationRoleTypes.System,
message: additionalSystemInstructions,
timestamp: new Date().toISOString(),
});
}
}
function toEntityReferenceInput(reference) {
return reference?.id ? { id: reference.id } : undefined;
}
function uniqueEntityReferences(references) {
const seen = new Set();
const unique = [];
for (const reference of references) {
if (!reference?.id || seen.has(reference.id)) {
continue;
}
seen.add(reference.id);
unique.push({ id: reference.id });
}
return unique;
}
function uniqueSpecifications(specifications) {
const seen = new Set();
const unique = [];
for (const specification of specifications) {
if (!specification?.id || seen.has(specification.id)) {
continue;
}
seen.add(specification.id);
unique.push(specification);
}
return unique;
}
function rebuildMessagesForSpecification(messages, specification, additionalSystemInstructions) {
const rebuilt = [];
let firstNonSystemIndex = 0;
while (firstNonSystemIndex < messages.length &&
messages[firstNonSystemIndex].role === Types.ConversationRoleTypes.System) {
firstNonSystemIndex++;
}
appendSystemMessages(rebuilt, specification.systemPrompt, additionalSystemInstructions);
rebuilt.push(...messages.slice(firstNonSystemIndex));
return rebuilt;
}
function computePersistedToolRoundDurationMs(toolCalls) {
if (!toolCalls || toolCalls.length === 0) {
return undefined;
}
const startedTimes = [];
const completedTimes = [];
const durations = [];
for (const toolCall of toolCalls) {
if (!toolCall)
continue;
if (toolCall.startedAt && toolCall.completedAt) {
const started = new Date(toolCall.startedAt).getTime();
const completed = new Date(toolCall.completedAt).getTime();
if (Number.isFinite(started) && Number.isFinite(completed)) {
startedTimes.push(started);
completedTimes.push(completed);
}
}
if (toolCall.durationMs !== null &&
toolCall.durationMs !== undefined &&
Number.isFinite(toolCall.durationMs)) {
durations.push(toolCall.durationMs);
}
}
if (startedTimes.length > 0 && completedTimes.length > 0) {
return Math.max(0, Math.max(...completedTimes) - Math.min(...startedTimes));
}
if (durations.length > 0) {
return Math.max(...durations);
}
return undefined;
}
try {
OpenAI = optionalRequire("openai").default || optionalRequire("openai");
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] OpenAI SDK loaded successfully");
}
}
catch (e) {
// OpenAI not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] OpenAI SDK not found:", e.message);
}
}
try {
Anthropic =
optionalRequire("@anthropic-ai/sdk").default ||
optionalRequire("@anthropic-ai/sdk");
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Anthropic SDK loaded successfully");
}
}
catch (e) {
// Anthropic SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Anthropic SDK not found:", e.message);
}
}
try {
GoogleGenAI = optionalRequire("@google/genai").GoogleGenAI;
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Google Gen AI SDK loaded successfully");
}
}
catch (e) {
// Google Gen AI not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Google Gen AI SDK not found:", e.message);
}
}
try {
Groq = optionalRequire("groq-sdk").default || optionalRequire("groq-sdk");
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Groq SDK loaded successfully");
}
}
catch (e) {
// Groq SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Groq SDK not found:", e.message);
}
}
try {
CohereClient = optionalRequire("cohere-ai").CohereClient;
CohereClientV2 = optionalRequire("cohere-ai").CohereClientV2;
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Cohere SDK loaded successfully");
}
}
catch (e) {
// Cohere SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Cohere SDK not found:", e.message);
}
}
try {
Mistral = optionalRequire("@mistralai/mistralai").Mistral;
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Mistral SDK loaded successfully");
}
}
catch (e) {
// Mistral SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Mistral SDK not found:", e.message);
}
}
try {
BedrockRuntimeClient = optionalRequire("@aws-sdk/client-bedrock-runtime").BedrockRuntimeClient;
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Bedrock SDK loaded successfully");
}
}
catch (e) {
// Bedrock SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Bedrock SDK not found:", e.message);
}
}
try {
Cerebras =
optionalRequire("@cerebras/cerebras_cloud_sdk").default ||
optionalRequire("@cerebras/cerebras_cloud_sdk");
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Cerebras SDK loaded successfully");
}
}
catch (e) {
// Cerebras SDK not installed
if (process.env.DEBUG_GRAPHLIT_SDK_INITIALIZATION) {
console.log("[SDK Loading] Cerebras SDK not found:", e.message);
}
}
const DEFAULT_MAX_TOOL_ROUNDS = 100;
/** Maximum number of tool calls to execute concurrently within a single streaming round. */
const DEFAULT_MAX_PARALLEL_TOOL_CALLS = 4;
/** Maximum number of retries for transient provider errors (5xx, network, overloaded). */
const DEFAULT_PROVIDER_RETRIES = 3;
/** Base delay in ms for exponential backoff between provider retries. */
const PROVIDER_RETRY_BASE_DELAY_MS = 1000;
/** Cap on the backoff delay in ms. */
const PROVIDER_RETRY_MAX_DELAY_MS = 30_000;
// Re-export context management utilities
export { TokenBudgetTracker, truncateToolResult, estimateTokens, isAccurateTokenCounting, } from "./helpers/context-management.js";
// Helper function to validate GUID format
function isValidGuid(guid) {
if (!guid)
return false;
// GUID regex pattern: 8-4-4-4-12 hexadecimal characters
const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
return guidRegex.test(guid);
}
/**
* Map Graphlit AnthropicEffortLevels to the string values accepted by the
* Anthropic Messages API `output_config.effort` parameter (adaptive thinking).
* Used for Claude 4.7 Opus, which replaces `thinking.budget_tokens` with
* `thinking.type = "adaptive"` + `output_config.effort`.
*/
function mapAnthropicEffort(effort) {
if (!effort)
return undefined;
switch (effort) {
case Types.AnthropicEffortLevels.Low:
return "low";
case Types.AnthropicEffortLevels.Medium:
return "medium";
case Types.AnthropicEffortLevels.High:
return "high";
case Types.AnthropicEffortLevels.XHigh:
case Types.AnthropicEffortLevels.Max:
return "xhigh";
default:
return undefined;
}
}
// Define the Graphlit class
class Graphlit {
client;
token;
apiUri;
organizationId;
environmentId;
ownerId;
userId;
jwtSecret;
retryConfig;
// Streaming client instances (optional - can be provided by user)
openaiClient;
anthropicClient;
googleClient;
groqClient;
cerebrasClient;
cohereClient;
mistralClient;
bedrockClient;
deepseekClient;
xaiClient;
// Serializes streamAgent calls per conversation to prevent race conditions
// when a user sends a second message before the first response completes.
conversationQueues = new Map();
googlePromptCache = {
entries: new Map(),
maxEntries: 100,
};
constructor(organizationIdOrOptions, environmentId, jwtSecret, ownerId, userId, apiUri) {
// Handle both old constructor signature and new options object
let options;
if (typeof organizationIdOrOptions === "object" &&
organizationIdOrOptions !== null) {
// New constructor with options object
options = organizationIdOrOptions;
}
else {
// Legacy constructor with individual parameters
options = {
organizationId: organizationIdOrOptions,
environmentId,
jwtSecret,
ownerId,
userId,
apiUri,
};
}
this.apiUri =
options.apiUri ||
(typeof process !== "undefined"
? process.env.GRAPHLIT_API_URL
: undefined) ||
"https://data-scus.graphlit.io/api/v1/graphql";
if (typeof process !== "undefined") {
// Attempt to load dotenv if available (optional dependency)
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require("dotenv").config();
}
catch {
// dotenv not installed, user must set env vars manually
}
this.organizationId =
options.organizationId || process.env.GRAPHLIT_ORGANIZATION_ID;
this.environmentId =
options.environmentId || process.env.GRAPHLIT_ENVIRONMENT_ID;
this.jwtSecret = options.jwtSecret || process.env.GRAPHLIT_JWT_SECRET;
// optional: for multi-tenant support
this.ownerId = options.ownerId || process.env.GRAPHLIT_OWNER_ID;
this.userId = options.userId || process.env.GRAPHLIT_USER_ID;
}
else {
this.organizationId = options.organizationId;
this.environmentId = options.environmentId;
this.jwtSecret = options.jwtSecret;
// optional: for multi-tenant support
this.ownerId = options.ownerId;
this.userId = options.userId;
}
// Set default retry configuration
this.retryConfig = {
maxAttempts: 5,
initialDelay: 300,
maxDelay: 30000,
retryableStatusCodes: [429, 500, 502, 503, 504],
jitter: true,
...options.retryConfig,
};
// Skip all validation if pre-signed token is provided
if (!options.token) {
if (!this.organizationId) {
throw new Error("Graphlit organization identifier is required.");
}
if (!isValidGuid(this.organizationId)) {
throw new Error(`Invalid organization ID format. Expected a valid GUID, but received: '${this.organizationId}'. ` +
"A valid GUID should be in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
}
if (!this.environmentId) {
throw new Error("Graphlit environment identifier is required.");
}
if (!isValidGuid(this.environmentId)) {
throw new Error(`Invalid environment ID format. Expected a valid GUID, but received: '${this.environmentId}'. ` +
"A valid GUID should be in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
}
if (!this.jwtSecret) {
throw new Error("Graphlit environment JWT secret is required.");
}
}
// Validate optional userId if provided (ownerId can be any format)
if (this.userId && !isValidGuid(this.userId)) {
throw new Error(`Invalid user ID format. Expected a valid GUID, but received: '${this.userId}'. ` +
"A valid GUID should be in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
}
// If a pre-signed token is provided, use it directly instead of generating one
if (options.token) {
this.token = options.token;
this.initializeClient();
}
else {
this.refreshClient();
}
}
/**
* Initialize the Apollo client without regenerating the token.
* Used when a pre-signed token is provided.
*/
initializeClient() {
this.client = undefined;
this.setupApolloClient();
}
refreshClient() {
this.client = undefined;
this.generateToken();
this.setupApolloClient();
}
setupApolloClient() {
const httpLink = createHttpLink({
uri: this.apiUri,
});
// Create retry link with configuration
const retryLink = new RetryLink({
delay: {
initial: this.retryConfig.initialDelay || 300,
max: this.retryConfig.maxDelay || 30000,
jitter: this.retryConfig.jitter !== false,
},
attempts: {
max: this.retryConfig.maxAttempts || 5,
retryIf: (error, _operation) => {
// Check if we should retry this error
if (!error)
return false;
// Check for network errors
const hasNetworkError = !!error.networkError;
if (!hasNetworkError)
return false;
// Get status code from different possible locations
const statusCode = error.networkError?.statusCode ||
error.networkError?.response?.status ||
error.statusCode;
// Check if status code is retryable
if (statusCode && this.retryConfig.retryableStatusCodes) {
const shouldRetry = this.retryConfig.retryableStatusCodes.includes(statusCode);
// Call onRetry callback if provided
if (shouldRetry &&
this.retryConfig.onRetry &&
_operation.getContext().retryCount !== undefined) {
const attempt = _operation.getContext().retryCount + 1;
this.retryConfig.onRetry(attempt, error, _operation);
}
return shouldRetry;
}
// Default: retry on network errors without specific status codes
return true;
},
},
});
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: this.token ? `Bearer ${this.token}` : "",
},
});
return forward(operation);
});
// Chain links: retry -> auth -> http
this.client = new ApolloClient({
link: ApolloLink.from([retryLink, authLink, httpLink]),
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
errorPolicy: "all",
fetchPolicy: "no-cache",
},
query: {
errorPolicy: "all",
fetchPolicy: "no-cache",
},
mutate: {
errorPolicy: "all",
fetchPolicy: "no-cache",
},
},
});
}
/**
* Set a custom OpenAI client instance for streaming
* @param client - OpenAI client instance (e.g., new OpenAI({ apiKey: "..." }))
*/
setOpenAIClient(client) {
this.openaiClient = client;
}
/**
* Set a custom Anthropic client instance for streaming
* @param client - Anthropic client instance (e.g., new Anthropic({ apiKey: "..." }))
*/
setAnthropicClient(client) {
this.anthropicClient = client;
}
/**
* Set a custom Google Generative AI client instance for streaming
* @param client - Google GenAI client instance (e.g., new GoogleGenAI({apiKey}))
*/
setGoogleClient(client) {
this.googleClient = client;
}
/**
* Set a custom Groq client instance for streaming
* @param client - Groq client instance (e.g., new Groq({ apiKey: "..." }))
*/
setGroqClient(client) {
this.groqClient = client;
}
/**
* Set a custom Cerebras client instance for streaming
* @param client - Cerebras client instance (e.g., new Cerebras({ apiKey: "..." }))
*/
setCerebrasClient(client) {
this.cerebrasClient = client;
}
/**
* Set a custom Cohere client instance for streaming
* @param client - Cohere client instance (e.g., new CohereClient({ token: "..." }))
*/
setCohereClient(client) {
this.cohereClient = client;
}
/**
* Set a custom Mistral client instance for streaming
* @param client - Mistral client instance (e.g., new Mistral({ apiKey: "..." }))
*/
setMistralClient(client) {
this.mistralClient = client;
}
/**
* Set a custom Bedrock client instance for streaming
* @param client - BedrockRuntimeClient instance (e.g., new BedrockRuntimeClient({ region: "us-east-2" }))
*/
setBedrockClient(client) {
this.bedrockClient = client;
}
/**
* Set a custom Deepseek client instance for streaming
* @param client - OpenAI client instance configured for Deepseek (e.g., new OpenAI({ baseURL: "https://api.deepseek.com", apiKey: "..." }))
*/
setDeepseekClient(client) {
this.deepseekClient = client;
}
/**
* Set a custom xAI client instance for streaming
* @param client - OpenAI client instance configured for xAI (e.g., new OpenAI({ baseURL: "https://api.x.ai/v1", apiKey: "..." }))
*/
setXaiClient(client) {
this.xaiClient = client;
}
/**
* Update retry configuration and refresh the Apollo client
* @param retryConfig - New retry configuration
*/
setRetryConfig(retryConfig) {
this.retryConfig = {
...this.retryConfig,
...retryConfig,
};
// Refresh client to apply new retry configuration
this.refreshClient();
}
generateToken() {
if (!this.jwtSecret) {
throw new Error("Graphlit environment JWT secret is required.");
}
const expiration = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // one day from now
const payload = {
"https://graphlit.io/jwt/claims": {
"x-graphlit-organization-id": this.organizationId,
"x-graphlit-environment-id": this.environmentId,
...(this.ownerId && { "x-graphlit-owner-id": this.ownerId }),
...(this.userId && { "x-graphlit-user-id": this.userId }),
"x-graphlit-role": "Owner",
},
exp: expiration,
iss: "graphlit",
aud: "https://portal.graphlit.io",
};
this.token = jwt.sign(payload, this.jwtSecret, { algorithm: "HS256" });
}
/**
* Fetch current project.
* @returns The project.
*/
async getProject() {
return this.queryAndCheckError(Documents.GetProject, {});
}
/**
* Updates a project.
* @param project - The project to update.
* @returns The updated project.
*/
async updateProject(project) {
return this.mutateAndCheckError(Documents.UpdateProject, { project: project });
}
/**
* Lookup usage records given tenant correlation identifier.
* @param correlationId - The tenant correlation identifier.
* @param startDate - The start date of records to be returned, optional. Defaults to last 30 days.
* @param duration - The duration of records to be returned, optional. Defaults to last 30 days.
* @returns The project usage records.
*/
async lookupProjectUsage(correlationId, startDate, duration) {
return this.queryAndCheckError(Documents.LookupUsage, {
correlationId: correlationId,
startDate: startDate,
duration: duration,
});
}
/**
* Lookup credit usage given tenant correlation identifier.
* @param correlationId - The tenant correlation identifier.
* @param startDate - The start date of records to be returned, optional. Defaults to last 30 days.
* @param duration - The duration of records to be returned, optional. Defaults to last 30 days.
* @returns The project credits.
*/
async lookupProjectCredits(correlationId, startDate, duration) {
return this.queryAndCheckError(Documents.LookupCredits, {
correlationId: correlationId,
startDate: startDate,
duration: duration,
});
}
/**
* Retrieves project tokens.
* @param startDate - The start date of tokens to be returned.
* @param duration - The duration of tokens to be returned.
* @returns The project tokens.
*/
async queryProjectTokens(startDate, duration) {
return this.queryAndCheckError(Documents.QueryTokens, { startDate: startDate, duration: duration });
}
/**
* Retrieves project usage.
* @param startDate - The start date of records to be returned.
* @param duration - The duration of records to be returned.
* @param names - Filter by allowed usage record names, defaults to 'GraphQL'.
* @param excludedNames - Filter by excluded usage record names.
* @param offset - The offset to the records to be returned, defaults to 0.
* @param limit - The number of records to be returned, defaults to 1000.
* @returns The project usage records.
*/
async queryProjectUsage(startDate, duration, names, excludedNames, offset, limit) {
return this.queryAndCheckError(Documents.QueryUsage, {
startDate: startDate,
duration: duration,
names: names,
excludedNames: excludedNames,
offset: offset,
limit: limit,
});
}
/**
* Retrieves project credits.
* @param startDate - The start date of credits to be returned.
* @param duration - The duration of credits to be returned.
* @returns The project credits.
*/
async queryProjectCredits(startDate, duration) {
return this.queryAndCheckError(Documents.QueryCredits, { startDate: startDate, duration: duration });
}
/**
* Sends a notification.
* @param connector - The integration connector used to send the notification.
* @param text - The notification text.
* @param textType - The text type, optional.
* @returns The result of the notification.
*/
async sendNotification(connector, text, textType) {
return this.mutateAndCheckError(Documents.SendNotification, {
connector: connector,
text: text,
textType: textType,
});
}
/**
* Enumerates the web pages at or beneath the provided URL using web sitemap.
* @param uri - The URI of the web page to be mapped.
* @param allowedPaths - The list of regular expressions for URL paths to be crawled, i.e. "^\/public\/blogs\/.*".
* @param excludedPaths - The list of regular expressions for URL paths to not be crawled, i.e. "^\/internal\/private\/.*".
* @param correlationId - The tenant correlation identifier, optional.
* @returns The mapped URIs.
*/
async mapWeb(uri, allowedPaths, excludedPaths, correlationId) {
return this.queryAndCheckError(Documents.MapWeb, {
uri: uri,
allowedPaths: allowedPaths,
excludedPaths: excludedPaths,
correlationId: correlationId,
});
}
/**
* Searches the web based on the provided properties.
* @param text - The web search text.
* @param service - The web search service type, defaults to Tavily.
* @param limit - The number of web search results to be returned, defaults to 10.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The web search results.
*/
async searchWeb(text, service, limit, correlationId) {
return this.queryAndCheckError(Documents.SearchWeb, {
text: text,
service: service,
limit: limit,
correlationId: correlationId,
});
}
/**
* Creates an alert.
* @param alert - The alert to create.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The created alert.
*/
async createAlert(alert, correlationId) {
return this.mutateAndCheckError(Documents.CreateAlert, { alert: alert, correlationId: correlationId });
}
/**
* Updates an alert.
* @param alert - The alert to update.
* @returns The updated alert.
*/
async updateAlert(alert) {
return this.mutateAndCheckError(Documents.UpdateAlert, { alert: alert });
}
/**
* Creates or updates an alert.
* @param alert - The alert to create or update.
* @returns The created or updated alert.
*/
async upsertAlert(alert) {
return this.mutateAndCheckError(Documents.UpsertAlert, { alert: alert });
}
/**
* Deletes an alert.
* @param id - The ID of the alert to delete.
* @returns The deleted alert.
*/
async deleteAlert(id) {
return this.mutateAndCheckError(Documents.DeleteAlert, { id: id });
}
/**
* Deletes multiple alerts.
* @param ids - The IDs of the alerts to delete.
* @param isSynchronous - Whether this mutation is synchronous.
* @returns The deleted alerts.
*/
async deleteAlerts(ids, isSynchronous) {
return this.mutateAndCheckError(Documents.DeleteAlerts, { ids: ids, isSynchronous: isSynchronous });
}
/**
* Deletes all alerts based on the provided filter criteria.
* @param filter - The filter criteria to apply when deleting alerts.
* @param isSynchronous - Whether this mutation is synchronous.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The result of the deletion.
*/
async deleteAllAlerts(filter, isSynchronous, correlationId) {
return this.mutateAndCheckError(Documents.DeleteAllAlerts, {
filter: filter,
isSynchronous: isSynchronous,
correlationId: correlationId,
});
}
/**
* Enables an alert.
* @param id - The ID of the alert to enable.
* @returns The enabled alert.
*/
async enableAlert(id) {
return this.mutateAndCheckError(Documents.EnableAlert, { id: id });
}
/**
* Disables an alert.
* @param id - The ID of the alert to disable.
* @returns The disabled alert.
*/
async disableAlert(id) {
return this.mutateAndCheckError(Documents.DisableAlert, { id: id });
}
/**
* Lookup an alert given its ID.
* @param id - ID of the alert.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The alert.
*/
async getAlert(id, correlationId) {
return this.queryAndCheckError(Documents.GetAlert, { id: id, correlationId: correlationId });
}
/**
* Retrieves alerts based on the provided filter criteria.
* @param filter - The filter criteria to apply when retrieving alerts.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The alerts.
*/
async queryAlerts(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryAlerts, { filter: filter, correlationId: correlationId });
}
/**
* Counts alerts based on the provided filter criteria.
* @param filter - The filter criteria to apply when counting alerts.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The count of alerts.
*/
async countAlerts(filter, correlationId) {
return this.queryAndCheckError(Documents.CountAlerts, { filter: filter, correlationId: correlationId });
}
/**
* Creates an agent.
* @param agent - The agent to create.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The created agent.
*/
async createAgent(agent, correlationId) {
return this.mutateAndCheckError(Documents.CreateAgent, { agent: agent, correlationId: correlationId });
}
/**
* Updates an agent.
* @param agent - The agent to update.
* @returns The updated agent.
*/
async updateAgent(agent) {
return this.mutateAndCheckError(Documents.UpdateAgent, { agent: agent });
}
/**
* Creates or updates an agent.
* @param agent - The agent to create or update.
* @returns The created or updated agent.
*/
async upsertAgent(agent) {
return this.mutateAndCheckError(Documents.UpsertAgent, { agent: agent });
}
/**
* Deletes an agent.
* @param id - The ID of the agent to delete.
* @returns The deleted agent.
*/
async deleteAgent(id) {
return this.mutateAndCheckError(Documents.DeleteAgent, { id: id });
}
/**
* Deletes multiple agents.
* @param ids - The IDs of the agents to delete.
* @param isSynchronous - Whether this mutation is synchronous.
* @returns The deleted agents.
*/
async deleteAgents(ids, isSynchronous) {
return this.mutateAndCheckError(Documents.DeleteAgents, { ids: ids, isSynchronous: isSynchronous });
}
/**
* Deletes all agents based on the provided filter criteria.
* @param filter - The filter criteria to apply when deleting agents.
* @param isSynchronous - Whether this mutation is synchronous.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The result of the deletion.
*/
async deleteAllAgents(filter, isSynchronous, correlationId) {
return this.mutateAndCheckError(Documents.DeleteAllAgents, {
filter: filter,
isSynchronous: isSynchronous,
correlationId: correlationId,
});
}
/**
* Enables an agent.
* @param id - The ID of the agent to enable.
* @returns The enabled agent.
*/
async enableAgent(id) {
return this.mutateAndCheckError(Documents.EnableAgent, { id: id });
}
/**
* Disables an agent.
* @param id - The ID of the agent to disable.
* @returns The disabled agent.
*/
async disableAgent(id) {
return this.mutateAndCheckError(Documents.DisableAgent, { id: id });
}
/**
* Updates the focus of an agent.
* @param id - The ID of the agent.
* @param focus - The focus text to set, or undefined to clear.
* @returns The updated agent.
*/
async updateAgentFocus(id, focus) {
return this.mutateAndCheckError(Documents.UpdateAgentFocus, { id: id, focus: focus });
}
/**
* Updates the scratchpad of an agent.
* @param id - The ID of the agent.
* @param scratchpad - The scratchpad text to set.
* @returns The updated agent.
*/
async updateAgentScratchpad(id, scratchpad) {
return this.mutateAndCheckError(Documents.UpdateAgentScratchpad, { id: id, scratchpad: scratchpad });
}
/**
* Lookup an agent given its ID.
* @param id - ID of the agent.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The agent.
*/
async getAgent(id, correlationId) {
return this.queryAndCheckError(Documents.GetAgent, { id: id, correlationId: correlationId });
}
/**
* Retrieves agents based on the provided filter criteria.
* @param filter - The filter criteria to apply when retrieving agents.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The agents.
*/
async queryAgents(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryAgents, { filter: filter, correlationId: correlationId });
}
/**
* Counts agents based on the provided filter criteria.
* @param filter - The filter criteria to apply when counting agents.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The count of agents.
*/
async countAgents(filter, correlationId) {
return this.queryAndCheckError(Documents.CountAgents, { filter: filter, correlationId: correlationId });
}
/**
* Creates a bureau.
* @param bureau - The bureau to create.
* @returns The created bureau.
*/
async createBureau(bureau) {
return this.mutateAndCheckError(Documents.CreateBureau, { bureau: bureau });
}
/**
* Updates a bureau.
* @param bureau - The bureau to update.
* @returns The updated bureau.
*/
async updateBureau(bureau) {
return this.mutateAndCheckError(Documents.UpdateBureau, { bureau: bureau });
}
/**
* Deletes a bureau.
* @param id - The ID of the bureau to delete.
* @returns The deleted bureau.
*/
async deleteBureau(id) {
return this.mutateAndCheckError(Documents.DeleteBureau, { id: id });
}
/**
* Deletes multiple bureaus.
* @param ids - The IDs of the bureaus to delete.
* @param isSynchronous - Whether this mutation is synchronous.
* @returns The deleted bureaus.
*/
async deleteBureaus(ids, isSynchronous) {
return this.mutateAndCheckError(Documents.DeleteBureaus, { ids: ids, isSynchronous: isSynchronous });
}
/**
* Deletes all bureaus based on the provided filter criteria.
* @param filter - The filter criteria to apply when deleting bureaus.
* @param isSynchronous - Whether this mutation is synchronous.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The result of the deletion.
*/
async deleteAllBureaus(filter, isSynchronous, correlationId) {
return this.mutateAndCheckError(Documents.DeleteAllBureaus, {
filter: filter,
isSynchronous: isSynchronous,
correlationId: correlationId,
});
}
/**
* Adds desks to a bureau.
* @param desks - The desks to add.
* @param bureau - The bureau to add the desks to.
* @returns The updated bureau.
*/
async addDesksToBureau(desks, bureau) {
return this.mutateAndCheckError(Documents.AddDesksToBureau, {
desks: desks,
bureau: bureau,
});
}
/**
* Removes desks from a bureau.
* @param desks - The desks to remove.
* @param bureau - The bureau to remove the desks from.
* @returns The updated bureau.
*/
async removeDesksFromBureau(desks, bureau) {
return this.mutateAndCheckError(Documents.RemoveDesksFromBureau, {
desks: desks,
bureau: bureau,
});
}
/**
* Lookup a bureau given its ID.
* @param id - ID of the bureau.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The bureau.
*/
async getBureau(id, correlationId) {
return this.queryAndCheckError(Documents.GetBureau, { id: id, correlationId: correlationId });
}
/**
* Retrieves bureaus based on the provided filter criteria.
* @param filter - The filter criteria to apply when retrieving bureaus.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The bureaus.
*/
async queryBureaus(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryBureaus, { filter: filter, correlationId: correlationId });
}
/**
* Counts bureaus based on the provided filter criteria.
* @param filter - The filter criteria to apply when counting bureaus.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The count of bureaus.
*/
async countBureaus(filter, correlationId) {
return this.queryAndCheckError(Documents.CountBureaus, { filter: filter, correlationId: correlationId });
}
/**
* Creates a desk.
* @param desk - The desk to create.
* @returns The created desk.
*/
async createDesk(desk) {
return this.mutateAndCheckError(Documents.CreateDesk, { desk: desk });
}
/**
* Updates a desk.
* @param desk - The desk to update.
* @returns The updated desk.
*/
async updateDesk(desk) {
return this.mutateAndCheckError(Documents.UpdateDesk, { desk: desk });
}
/**
* Deletes a desk.
* @param id - The ID of the desk to delete.
* @returns The deleted desk.
*/
async deleteDesk(id) {
return this.mutateAndCheckError(Documents.DeleteDesk, { id: id });
}
/**
* Deletes multiple desks.
* @param ids - The IDs of the desks to delete.
* @param isSynchronous - Whether this mutation is synchronous.
* @returns The deleted desks.
*/
async deleteDesks(ids, isSynchronous) {
return this.mutateAndCheckError(Documents.DeleteDesks, { ids: ids, isSynchronous: isSynchronous });
}
/**
* Deletes all desks based on the provided filter criteria.
* @param filter - The filter criteria to apply when deleting desks.
* @param isSynchronous - Whether this mutation is synchronous.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The result of the deletion.
*/
async deleteAllDesks(filter, isSynchronous, correlationId) {
return this.mutateAndCheckError(Documents.DeleteAllDesks, {
filter: filter,
isSynchronous: isSynchronous,
correlationId: correlationId,
});
}
/**
* Adds agents to a desk.
* @param agents - The agents to add.
* @param desk - The desk to add the agents to.
* @returns The updated desk.
*/
async addAgentsToDesk(agents, desk) {
return this.mutateAndCheckError(Documents.AddAgentsToDesk, {
agents: agents,
desk: desk,
});
}
/**
* Removes agents from a desk.
* @param agents - The agents to remove.
* @param desk - The desk to remove the agents from.
* @returns The updated desk.
*/
async removeAgentsFromDesk(agents, desk) {
return this.mutateAndCheckError(Documents.RemoveAgentsFromDesk, {
agents: agents,
desk: desk,
});
}
/**
* Lookup a desk given its ID.
* @param id - ID of the desk.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The desk.
*/
async getDesk(id, correlationId) {
return this.queryAndCheckError(Documents.GetDesk, { id: id, correlationId: correlationId });
}
/**
* Retrieves desks based on the provided filter criteria.
* @param filter - The filter criteria to apply when retrieving desks.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The desks.
*/
async queryDesks(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryDesks, { filter: filter, correlationId: correlationId });
}
/**
* Counts desks based on the provided filter criteria.
* @param filter - The filter criteria to apply when counting desks.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The count of desks.
*/
async countDesks(filter, correlationId) {
return this.queryAndCheckError(Documents.CountDesks, { filter: filter, correlationId: correlationId });
}
/**
* Creates a fact.
* @param fact - The fact to create.
* @returns The created fact.
*/
async createFact(fact) {
return this.mutateAndCheckError(Documents.CreateFact, { fact: fact });
}
/**
* Updates a fact.
* @param fact - The fact to update.
* @returns The updated fact.
*/
async updateFact(fact) {
return this.mutateAndCheckError(Documents.UpdateFact, { fact: fact });
}
/**
* Deletes a fact.
* @param id - The ID of the fact to delete.
* @returns The deleted fact.
*/
async deleteFact(id) {
return this.mutateAndCheckError(Documents.DeleteFact, { id: id });
}
/**
* Deletes multiple facts.
* @param ids - The IDs of the facts to delete.
* @param isSynchronous - Whether this mutation is synchronous.
* @returns The deleted facts.
*/
async deleteFacts(ids, isSynchronous) {
return this.mutateAndCheckError(Documents.DeleteFacts, { ids: ids, isSynchronous: isSynchronous });
}
/**
* Deletes all facts based on the provided filter criteria.
* @param filter - The filter criteria to apply when deleting facts.
* @param isSynchronous - Whether this mutation is synchronous.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The result of the deletion.
*/
async deleteAllFacts(filter, isSynchronous, correlationId) {
return this.mutateAndCheckError(Documents.DeleteAllFacts, {
filter: filter,
isSynchronous: isSynchronous,
correlationId: correlationId,
});
}
/**
* Lookup a fact given its ID.
* @param id - ID of the fact.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The fact.
*/
async getFact(id, correlationId) {
return this.queryAndCheckError(Documents.GetFact, { id: id, correlationId: correlationId });
}
/**
* Retrieves facts based on the provided filter criteria.
* @param filter - The filter criteria to apply when retrieving facts.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The facts.
*/
async queryFacts(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryFacts, { filter: filter, correlationId: correlationId });
}
/**
* Retrieves facts as a knowledge graph.
* @param filter - The filter criteria to apply when retrieving facts, optional.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The facts graph with nodes and edges.
*/
async queryFactsGraph(filter, correlationId) {
return this.queryAndCheckError(Documents.QueryFactsGraph, {
filter: filter,
graph: {
/* return everything */
},
correlationId: correlationId,
});
}
/**
* Retrieves facts with clustering.
* @param filter - The filter criteria to apply when retrieving facts, optional.
* @param clusters - The clustering input parameters, optional.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The facts with clusters.
*/
async queryFactsClusters(filter, clusters, correlationId) {
return this.queryAndCheckError(Documents.QueryFactsClusters, {
filter: filter,
clusters: clusters,
correlationId: correlationId,
});
}
/**
* Counts facts based on the provided filter criteria.
* @param filter - The filter criteria to apply when counting facts.
* @param correlationId - The tenant correlation identifier, optional.
* @returns The count of facts.
*/
async countFacts(filter, correlationId) {
return this.queryAndCheckError(Documents.CountFacts, { filter: filter, correlationId: correlationId });
}
/**
* Creates a