Docs
AI Responses - JavaScript SDK
AI Responses - JavaScript SDK
Creating and managing AI responses with the JavaScript SDK
Creating AI Responses
Basic Usage
import { LumnisClient } from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
// Simple string prompt
const response = await client.invoke("What is the meaning of life?")
console.log(response.outputText)
// With message format
const response = await client.responses.create({
messages: [{ role: 'user', content: 'Hello!' }]
})With Conversation History
// Continue existing thread
const response = await client.responses.create({
threadId: 'existing-thread-id',
messages: [
{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'What can you help me with?' }
]
})With Agent Configuration
import { LumnisClient, type AgentConfig } from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
const agentConfig: AgentConfig = {
plannerModelName: 'openai:gpt-4.1',
coordinatorModelName: 'openai:gpt-4.1',
orchestratorModelName: 'openai:gpt-4.1',
useCognitiveTools: true,
enableTaskValidation: true,
generateComprehensiveOutput: true
}
const response = await client.invoke(
"Analyze complex data patterns",
{
userId: "user@example.com",
agentConfig
}
)Streaming Progress Updates
Basic Streaming
import { LumnisClient, displayProgress } from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
// Stream progress updates
for await (const update of await client.invoke(
"Analyze this dataset",
{ stream: true }
)) {
displayProgress(update)
if (update.state === 'completed') {
console.log(`\nFinal output: ${update.outputText}`)
break
}
}Collecting Updates
import { LumnisClient, displayProgress } from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
// Collect all updates
const updates: any[] = []
let finalOutput = ''
for await (const update of await client.invoke(
"Research topic",
{
stream: true,
userId: "user@example.com"
}
)) {
displayProgress(update)
updates.push(update)
if (update.outputText) {
finalOutput = update.outputText
}
}
console.log(`\n\nFinal Analysis:\n${finalOutput}`)
console.log(`\nTotal updates: ${updates.length}`)Custom Progress Tracking
import { LumnisClient, ProgressTracker } from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
const tracker = new ProgressTracker()
for await (const update of await client.invoke(
"Complex task",
{ stream: true }
)) {
const newContent = tracker.formatNewEntries(
update.state,
update.message,
update.toolCalls
)
if (newContent) {
console.log(newContent) // Only new content
}
}Managing Responses
List Responses
// List responses with filters
const responses = await client.responses.list({
userId: "user@example.com",
status: "succeeded",
startDate: "2025-01-01",
endDate: "2025-01-31",
limit: 50,
offset: 0
})
for (const resp of responses.responses) {
console.log(`${resp.responseId}: ${resp.status}`)
}Get Response Details
// Get specific response
const response = await client.responses.get(responseId)
// With long polling (wait for updates)
const response = await client.responses.get(responseId, { wait: 30 })
// Access response details
console.log(`Status: ${response.status}`)
console.log(`Output: ${response.outputText}`)
console.log(`Thread: ${response.threadId}`)
// Access progress entries
if (response.progress) {
for (const entry of response.progress) {
console.log(`${entry.state}: ${entry.message}`)
if (entry.toolCalls) {
for (const tool of entry.toolCalls) {
console.log(` → ${tool.name}`)
}
}
}
}Cancel Response
// Cancel a running response
const cancelled = await client.responses.cancel(responseId)
console.log(`Cancelled: ${cancelled.status}`)Managing Threads
Create and List Threads
// Create a new thread
const thread = await client.createThread({
userId: "user@example.com",
title: "Customer Support Conversation"
})
// List user's threads
const threads = await client.listThreads({
userId: "user@example.com",
limit: 20
})
for (const thread of threads.threads) {
console.log(`${thread.threadId}: ${thread.title}`)
}Get Thread Details
// Get thread details
const thread = await client.getThread(threadId)
console.log(`Thread: ${thread.title}`)
console.log(`Responses: ${thread.responseCount}`)Delete Thread
// Delete a thread
await client.deleteThread(threadId)Complete Example Workflow
import { LumnisClient, displayProgress, type AgentConfig } from 'lumnisai'
// Initialize client
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
// Create user
const user = await client.createUser({
email: "analyst@example.com",
firstName: "Data",
lastName: "Analyst"
})
// Configure agent
const agentConfig: AgentConfig = {
coordinatorModelName: "openai:gpt-4.1",
plannerModelName: "openai:gpt-4.1",
useCognitiveTools: true,
enableTaskValidation: true,
generateComprehensiveOutput: true
}
// Create streaming response
for await (const update of await client.invoke(
"What are the latest trends in AI agents?",
{
stream: true,
userId: user.email,
agentConfig
}
)) {
displayProgress(update)
if (update.state === 'completed') {
console.log(`\n\nFinal Analysis:\n${update.outputText}`)
}
}
// List user's responses
const userResponses = await client.users.getResponses(user.email)
console.log(`\nUser has ${userResponses.responses.length} total responses`)Error Handling
import {
LumnisClient,
AuthenticationError,
NotFoundError,
RateLimitError,
ValidationError,
LumnisAPIError
} from 'lumnisai'
const client = new LumnisClient({ apiKey: process.env.LUMNISAI_API_KEY! })
try {
const response = await client.invoke("Hello!")
}
catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key:', error.message)
}
else if (error instanceof ValidationError) {
console.error('Invalid request:', error.details)
}
else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds`)
}
else if (error instanceof NotFoundError) {
console.error('Resource not found:', error.message)
}
else if (error instanceof LumnisAPIError) {
console.error(`API error [${error.statusCode}]: ${error.message}`)
}
}