Lamatic SDK
Once your Flows are built and deployed, the SDK is the easiest way to call them from TypeScript, Node.js, or browser-based apps.
The Lamatic SDK provides a simple way to interact with the Lamatic AI platform, allowing you to execute Flows and integrate AI capabilities into your applications.
Installation
Install the Lamatic SDK using npm:
npm install lamaticGetting Started
To use the Lamatic SDK, you’ll need:
- An API key or access token
- Your project ID
- The Lamatic API endpoint
Initialize the SDK like this:
import { Lamatic } from "lamatic";
const lamatic = new Lamatic({
endpoint: "your-endpoint", // Required: The Lamatic API endpoint
projectId: "your-project-id", // Required: Your project ID
apiKey: "your-api-key", // Required if not using accessToken
// OR
accessToken: "your-access-token" // Required if not using apiKey
});The constructor will throw an error if:
- Configuration object is not provided
endpointis missingprojectIdis missing- Neither
apiKeynoraccessTokenis provided
Authentication
The SDK supports two authentication methods:
const lamatic = new Lamatic({
apiKey: "your-api-key",
projectId: "your-project-id",
endpoint: "your-endpoint",
});You must provide either an API key or an access token, but not both.
How to obtain your API Key/Secret
- Navigate to Project Settings in your Lamatic dashboard
- Locate and copy your API Key/Secret from the credentials section
API Methods
The Lamatic SDK provides the following methods:
executeFlow(flowId: string, payload: Object): Promise<LamaticResponse>- Execute a workflowexecuteFlowTokenStream(flowId: string, payload: Object, options?: LamaticStreamOptions): AsyncGenerator<LamaticTokenEvent>- Execute a workflow and stream its LLM/RAG output token by tokenexecuteFlowPoll(flowId: string, payload: Object, pollOptions?: PollOptions): Promise<LamaticResponse>- Execute a workflow and, if it runs asynchronously, wait for its resultcheckStatus(requestId: string, pollInterval?: number, pollTimeout?: number): Promise<LamaticResponse>- Poll a request until it finishesupdateAccessToken(accessToken: string): void- Update the access token for the SDK instance
Executing Flows
One of the main functions of the SDK is to execute Flows that you’ve created on the Lamatic platform.
import { Lamatic } from "lamatic";
const lamatic = new Lamatic({
apiKey: "your-api-key",
projectId: "your-project-id",
endpoint: "your-endpoint",
});
async function main() {
const flowId = "your-flow-id";
// sample payload
const payload = {
prompt: "hey, how are you?"
}
try {
const response = await lamatic.executeFlow(flowId, payload);
console.log(response);
} catch (error) {
console.error(error);
}
}
main();Handling Expired Access Tokens
This example shows how to handle an expired access token by fetching a new one and updating the SDK.
import { Lamatic } from "lamatic";
const lamatic = new Lamatic({
accessToken: "your-access-token",
projectId: "your-project-id",
endpoint: "your-endpoint",
});
async function getAccessToken() {
const response = await fetch("your-server-endpoint/get-access-token", {
method: "GET",
});
const data = await response.json();
return data.accessToken;
}
async function main() {
const flowId = "your-flow-id";
// sample payload
const payload = {
prompt: "hey, how are you?",
};
const response = await lamatic.executeFlow(flowId, payload);
console.log(response);
if (response.statusCode === 403) {
// Get the new access token
const accessToken = await getAccessToken();
// Update the access token for the Lamatic SDK
lamatic.updateAccessToken(accessToken);
// Execute the flow again
const response = await lamatic.executeFlow(flowId, payload);
console.log(response);
}
}
main();Here, you are supposed to have a server endpoint that returns a new access token when called. This works for every SDK call. The server should handle the authentication and return the new access token from the same secret generated from Lamatic Studio.
Generating an Access Token Using JWT Sign
Here’s a method to create an access token using jsonwebtoken (JWT) with and without an expiration time:
import jwt from 'jsonwebtoken';
const secretKey = 'KEY'; // Secret key generated from Lamatic Studio
// Generate token without expiry
const accessToken = jwt.sign({ project_id: 'PROJECT_ID' }, secretKey, {
algorithm: 'HS256',
});
console.log('Access Token (without expiry):', accessToken);
// Generate token with expiry (e.g., 1 hour)
const accessTokenWithExpiry = jwt.sign({ project_id: 'PROJECT_ID' }, secretKey, {
algorithm: 'HS256',
expiresIn: '1h', // Change this to '1s' for testing or adjust as needed
});
console.log('Access Token (with expiry):', accessTokenWithExpiry);Streaming Responses
Use executeFlowTokenStream to show LLM output as it is generated, instead of waiting for the whole flow to finish. It runs the flow and yields one event at a time. Streaming requires lamatic v0.4.0 or later.
import { Lamatic } from "lamatic";
const lamatic = new Lamatic({
apiKey: "your-api-key",
projectId: "your-project-id",
endpoint: "your-endpoint",
});
for await (const event of lamatic.executeFlowTokenStream("your-flow-id", { prompt: "Write a short story" })) {
if (event.type === "token") process.stdout.write(event.token); // one piece of text
if (event.type === "final") console.log("\nFull text:", event.text);
if (event.type === "error") console.error("Stream failed:", event.message);
}Events
| Event | Fields | When |
|---|---|---|
token | token, nodeId, raw | An LLM or RAG node produced the next piece of text |
node | nodeId, output, raw | A node finished; output is its full output |
final | result, text, textByNode, raw | The flow finished. This is always the last event of a successful stream |
error | message, nodeId, raw | Something failed. The stream ends if the failure was fatal |
final.textis every token joined together. Use it instead of readinggeneratedResponsefrom a node’s output, because the flow’sresultonly holds what its response node returns.final.textByNodesplits the text by node, for flows with more than one LLM or RAG node.rawis the original server frame. On thenodeevent of an LLM node,raw.data._metaholds token counts and cost.
Only LLM and RAG nodes stream token by token. Every other node reports once, as a single node event when it finishes.
Stopping a stream
Pass an AbortSignal to stop generation, for example from a “Stop” button. The loop then ends quietly without an error or final event. Breaking out of the for await loop also stops the stream and closes the connection.
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
for await (const event of lamatic.executeFlowTokenStream(flowId, payload, { signal: controller.signal })) {
if (event.type === "token") output.textContent += event.token;
}Handling stream errors
Failures arrive as an error event, not as a thrown exception. That covers invalid credentials, network errors and a connection that drops before the flow finishes. Check for event.type === "error" in your loop.
Keep your API key on the server. In a browser app, stream from your own backend route and forward the tokens to the page, rather than calling Lamatic directly from the browser.
Response Structure
executeFlow, executeFlowPoll and checkStatus return a promise that resolves to a LamaticResponse object with the following structure:
{
status: "success" | "error" | "failed", // "failed": a node failed; "error": the request failed
result: object | null, // The result data from the workflow (if successful)
message?: string, // Error message (if status is "error" or "failed")
statusCode: number // HTTP status code
}Example with Error Handling
Here’s an example of how you might handle the response from a workflow execution:
async function runWorkflow() {
const flowId = "your-flow-id";
const payload = {
input: "Generate a creative story about robots",
parameters: {
temperature: 0.7,
maxTokens: 500,
},
};
try {
const response = await lamatic.executeFlow(flowId, payload);
if (response.status === "success") {
console.log("Workflow executed successfully!");
console.log("Result:", response.result);
return response.result;
} else if (response.status === "error" || response.status === "failed") {
console.error("Workflow execution failed:", response.message);
return null;
}
} catch (error) {
console.error("Exception occurred:", error);
return null;
}
}Async Flows
A flow whose API trigger is set to run asynchronously answers at once with only a request ID (result: { requestId }) and keeps running in the background. The SDK can wait for the result for you.
The fixes on this page need lamatic v0.4.1 or later. Earlier versions returned an empty result from checkStatus, and their executeFlowPoll never polled.
Run a flow and wait for the result
executeFlowPoll runs a flow and, if it was queued, polls until it finishes. A realtime flow’s response comes back unchanged, so it is safe to use for any flow.
const response = await lamatic.executeFlowPoll(flowId, payload, {
interval: 5, // seconds between checks (default 15)
timeout: 300, // give up after this many seconds (default 900)
});
if (response.status === "success") {
console.log("Result:", response.result);
} else {
console.error(response.status, response.message);
}Poll a request ID you already have
const response = await lamatic.checkStatus(
requestId,
15, // pollInterval in seconds (default: 15)
900 // pollTimeout in seconds (default: 900)
);Unlike executeFlow, checkStatus and executeFlowPoll return error responses instead of throwing, so check response.status rather than relying on try-catch.
What polling returns
status | statusCode | Meaning |
|---|---|---|
success | 200 | The flow finished. result is its output, the same shape a realtime run returns. |
failed | 200 | A node failed. message is the error, and result.failedNode names the node. |
error | 404 | The request ID was still unknown after 60 seconds of polling. |
error | 408 | The run had not finished when pollTimeout ran out. |
A 408 means only that polling gave up: the run may still finish in the background. Call checkStatus again later with the same requestId.
Updating Access Token
If you’re using access token authentication, you can update the token during runtime, if the need be:
// Initialize with an access token
const lamatic = new Lamatic({
accessToken: "initial-access-token",
projectId: "your-project-id",
endpoint: "your-endpoint",
});
// Later, update the access token
lamatic.updateAccessToken("new-access-token");Advanced Usage
Customizing Payloads
The payload structure depends on the specific workflow you’re executing. Make sure to check the documentation for your workflow to understand what parameters it expects.
// Example for a text generation workflow
const textGenPayload = {
prompt: "Write a poem about artificial intelligence",
options: {
temperature: 0.8,
topP: 0.95,
maxLength: 200
}
};Handling Responses
Different flows return different result structures. Here’s how you might handle responses from different types of flows:
// Text generation workflow response
const textResponse = await lamatic.executeFlow(
"text-gen-flow-id",
textGenPayload
);
if (textResponse.status === "success" && textResponse.result) {
const generatedText = textResponse.result.text;
console.log("Generated text:", generatedText);
}
// Classification workflow response
const classificationResponse = await lamatic.executeFlow(
"classify-flow-id",
classifyPayload
);
if (
classificationResponse.status === "success" &&
classificationResponse.result
) {
const category = classificationResponse.result.category;
const confidence = classificationResponse.result.confidence;
console.log(`Classification: ${category} (confidence: ${confidence})`);
}
TypeScript Support
The SDK is written in TypeScript and provides type definitions for all its functionality:
Workflow Execution Example
import { Lamatic, LamaticResponse, LamaticConfig } from "lamatic";
// Custom payload type
interface TextGenerationPayload {
prompt: string;
maxTokens?: number;
temperature?: number;
}
// Custom response type
interface TextGenerationResult {
text: string;
usedTokens: number;
}
async function generateText(
prompt: string
): Promise<TextGenerationResult | null> {
const payload: TextGenerationPayload = {
prompt,
maxTokens: 1000,
temperature: 0.7,
};
const response = await lamatic.executeFlow(
"text-gen-flow",
payload
);
if (response.status === "success" && response.result) {
return response.result as TextGenerationResult;
}
return null;
}Error Handling
The SDK has different error handling behaviors:
-
executeFlow: This method throws exceptions for network errors, configuration issues, or parsing errors. It also returns error responses in theLamaticResponseobject for GraphQL errors. Always wrap these calls in try-catch blocks. -
checkStatusandexecuteFlowPoll: These return error responses instead of throwing exceptions (except in rare cases). Check the response status rather than relying on try-catch.
Workflow Execution Example
try {
const response = await lamatic.executeFlow(flowId, payload);
// Check response status
if (response.status === "success") {
console.log("Success:", response.result);
} else if (response.status === "error" || response.status === "failed") {
console.error("Execution failed:", response.message);
console.error("Status code:", response.statusCode);
}
} catch (error) {
if (error instanceof Error) {
// Log the error
console.error("SDK Error:", error.message);
// Handle specific error scenarios
if (error.message.includes("timeout")) {
// Handle timeout
} else if (error.message.includes("network")) {
// Handle network error
} else if (error.message.includes("required")) {
// Handle configuration errors
}
}
}Status Check Example
// checkStatus returns error responses instead of throwing
const response = await lamatic.checkStatus(requestId, 15, 900);
if (response.status === "success") {
console.log("Request completed:", response.result);
} else if (response.status === "error" || response.status === "failed") {
console.error("Request failed:", response.message);
console.error("Status code:", response.statusCode);
// Handle timeout specifically
if (response.statusCode === 408) {
console.log("Request timed out. It may still be processing in the background.");
}
}Environment Variables
For better security, consider using environment variables for sensitive information:
// Using environment variables
const lamatic = new Lamatic({
apiKey: process.env.LAMATIC_API_KEY,
projectId: process.env.LAMATIC_PROJECT_ID,
endpoint: process.env.LAMATIC_ENDPOINT,
});Python SDK
Lamatic also provides a Python SDK (pip install lamatic) for executing flows from Python applications, with both sync and async methods, streaming, and waiting for async results.
For detailed information, installation instructions, and code examples, see the Python SDK documentation.
Go SDK
Lamatic also provides a Go SDK for integrating with Go applications. The Go SDK offers the same core functionality as the JavaScript/TypeScript SDK, with a Go-native API design that includes support for executing workflows, streaming, waiting for async results, and both API key and access token authentication.
For detailed information, installation instructions, code examples, and API reference, see the Go SDK documentation.
Support
For help and support, visit our documentation or contact [email protected].