Lamatic SDK
The Lamatic SDK (opens in a new tab) provides a simple way to interact with the Lamatic AI platform, allowing you to execute flow 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 workflowexecuteAgent(agentId: string, payload: Object): Promise<LamaticResponse>- Execute an agentcheckStatus(requestId: string, pollInterval?: number, pollTimeout?: number): Promise<LamaticResponse>- Check the status of a request with pollingupdateAccessToken(accessToken: string): void- Update the access token for the SDK instance
Executing Flow
One of the main functionality of the SDK is to execute flow (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 both flow and agent executions. 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);Response Structure
The executeFlow and executeAgent methods return a promise that resolves to a LamaticResponse object with the following structure:
{
status: "success" | "error" | "failed", // Status of the workflow/agent execution
result: object | null, // The result data from the workflow/agent (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;
}
}Here we have an example of handling with agent execution:
async function runAgent() {
const agentId = "your-agent-id";
const payload = {
input: "Generate a linkedin post about AI",
parameters: {
temperature: 0.7,
maxTokens: 500,
},
};
try {
const response = await lamatic.executeAgent(agentId, payload);
if (response.status === "success") {
console.log("Agent executed successfully!");
console.log("Result:", response.result);
return response.result;
} else if (response.status === "error" || response.status === "failed") {
console.error("Agent execution failed:", response.message);
return null;
}
} catch (error) {
console.error("Exception occurred:", error);
return null;
}
}Checking Request Status
The SDK provides a checkStatus method to check the status of a request with polling capability. This is useful for long-running workflows or agents that execute asynchronously.
Unlike executeFlow and executeAgent, the checkStatus method returns error responses instead of throwing exceptions. This allows you to handle errors without try-catch blocks, though you should still check the response status.
Basic Usage
const requestId = "your-request-id";
const response = await lamatic.checkStatus(requestId);
if (response.status === "success") {
console.log("Request completed:", response.result);
} else if (response.status === "error" || response.status === "failed") {
console.error("Request failed:", response.message);
}With Custom Polling Configuration
The checkStatus method supports custom polling intervals and timeouts:
// Check status with custom polling interval (15 seconds) and timeout (900 seconds = 15 minutes)
const response = await lamatic.checkStatus(
requestId,
15, // pollInterval in seconds (default: 15)
900 // pollTimeout in seconds (default: 900)
);Complete Example
import { Lamatic } from "lamatic";
const lamatic = new Lamatic({
apiKey: "your-api-key",
projectId: "your-project-id",
endpoint: "your-endpoint",
});
async function executeAndCheckStatus() {
const flowId = "your-flow-id";
const payload = {
prompt: "Generate a long report",
};
try {
// Execute the flow
const executeResponse = await lamatic.executeFlow(flowId, payload);
// If the response includes a requestId, you can check its status
if (executeResponse.result?.requestId) {
const requestId = executeResponse.result.requestId;
// Poll for status with custom configuration
// Note: checkStatus returns error responses instead of throwing
const statusResponse = await lamatic.checkStatus(
requestId,
10, // Check every 10 seconds
600 // Timeout after 10 minutes
);
if (statusResponse.status === "success") {
console.log("Request completed:", statusResponse.result);
} else if (statusResponse.status === "error" || statusResponse.status === "failed") {
console.error("Request failed:", statusResponse.message);
console.error("Status code:", statusResponse.statusCode);
}
} else {
// Request completed immediately
console.log("Immediate result:", executeResponse.result);
}
} catch (error) {
// This catch block handles errors from executeFlow, not checkStatus
console.error("Error executing flow:", error);
}
}
executeAndCheckStatus();Status Response
The checkStatus method returns a LamaticResponse object:
{
status: "success" | "error" | "failed", // Current status (never returns "in_progress" as it polls until completion)
result: object | null, // Result data (if completed)
message?: string, // Error message (if failed or timeout)
statusCode: number // HTTP status code (408 for timeout)
}The method will automatically poll until:
- The status becomes
"success","error", or"failed"(returns immediately) - The timeout is reached (returns with
status: "error",statusCode: 408, and a timeout message)
If a timeout occurs, your request may still be executing in the background. You can check the status again after a few minutes using the same requestId. The timeout message will indicate this.
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/agent you're executing. Make sure to check the documentation for your workflow/agent 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 flow/agents may return different result structures. Here's how you might handle responses from different types of flow/agents:
// 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);
}
// Tweet Generation agent response
const tweetResponse = await lamatic.executeAgent("tweet-gen-agent-id", tweetPayload);
if (tweetResponse.status === "success" && tweetResponse.result) {
const tweet = tweetResponse.result.tweet;
console.log("Generated tweet:", tweet);
}
// 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})`);
}
// Image analysis agent response
const imageAnalysisResponse = await lamatic.executeAgent("image-analysis-agent-id", imageAnalysisPayload);
if (imageAnalysisResponse.status === "success" && imageAnalysisResponse.result) {
const objects = imageAnalysisResponse.result.objects;
const faces = imageAnalysisResponse.result.faces;
const text = imageAnalysisResponse.result.text;
console.log("Analysis results:", { objects, faces, text });
}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;
}Agent Execution Example
import { Lamatic, LamaticResponse, LamaticConfig } from "lamatic";
// Custom payload type
interface ImageAnalysisPayload {
imageUrl: string;
analysisTypes: string[];
}
// Custom response type
interface ImageAnalysisResult {
objects: string[];
faces: string[];
text: string;
}
async function analyzeImage(imageUrl: string): Promise<ImageAnalysisResult | null> {
const payload: ImageAnalysisPayload = {
imageUrl,
analysisTypes: ["objects", "faces", "text"]
};
const response = await lamatic.executeAgent("image-analysis-agent", payload);
if (response.status === "success" && response.result) {
return response.result as ImageAnalysisResult;
}
return null;
}Error Handling
The SDK has different error handling behaviors:
-
executeFlowandexecuteAgent: These methods throw exceptions for network errors, configuration issues, or parsing errors. They also return error responses in theLamaticResponseobject for GraphQL errors. Always wrap these calls in try-catch blocks. -
checkStatus: This method returns 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
}
}
}Agent Execution Example
try {
const response = await lamatic.executeAgent(agentId, 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,
});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 and agents, status checking with polling, 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 (opens in a new tab) or contact [email protected].