Elizon Docs
Examples

TypeScript

Typed TypeScript client examples for the Elizon Public API.

Types and a small fetch wrapper covering all three execution modes. No SDK required — this is plain fetch.

Types

interface AgentRunMetrics {
  inputTokens: number | null
  outputTokens: number | null
  latencyMs: number | null
  model: string | null
  failoverUsed: boolean
}

interface AgentRunResult {
  runId: string
  agentId: string
  agentName: string
  content: string
  sessionId: string
  userId: string
  createdAt: number
  success: true
  metrics: AgentRunMetrics
  messages: unknown[] | null
}

type SseEvent =
  | {
      event: 'RunStarted' | 'ModelRequestStarted' | 'ModelRequestCompleted' | 'RunContentCompleted'
      runId: string
      agentId: string
      agentName: string
      sessionId: string
      userId: string
      createdAt: number
    }
  | {
      event: 'RunContent'
      runId: string
      agentId: string
      agentName: string
      sessionId: string
      userId: string
      createdAt: number
      content: string
    }
  | {
      event: 'RunCompleted'
      runId: string
      agentId: string
      agentName: string
      sessionId: string
      userId: string
      createdAt: number
      content: string
      metrics: AgentRunMetrics
    }
  | {
      event: 'error'
      runId: string
      agentId: string
      agentName: string
      sessionId: string
      userId: string
      createdAt: number
      reason: string
    }

type AsyncJobStatus = 'queued' | 'running' | 'completed' | 'failed' | 'timeout' | 'cancelled'

interface AsyncJobResult {
  jobId: string
  agentId: string
  status: AsyncJobStatus
  createdAt: number
  startedAt: number | null
  completedAt: number | null
  result: Omit<AgentRunResult, 'runId' | 'agentId' | 'agentName' | 'createdAt' | 'success'> | null
  error: string | null
}

Fetch wrapper

const BASE_URL = 'https://api.elizon.com/api/v1'

class ElizonClient {
  constructor(private apiKey: string) {}

  private headers(): Record<string, string> {
    return { 'X-API-Key': this.apiKey, 'Content-Type': 'application/json' }
  }

  async run(agentId: string, message: string, sessionId?: string): Promise<AgentRunResult> {
    const res = await fetch(`${BASE_URL}/agents/${agentId}/run`, {
      method: 'POST',
      headers: this.headers(),
      body: JSON.stringify({ message, session_id: sessionId }),
    })
    if (!res.ok) throw new Error(`Run failed: ${res.status} ${await res.text()}`)
    return res.json() as Promise<AgentRunResult>
  }

  async *runStream(agentId: string, message: string, sessionId?: string): AsyncGenerator<SseEvent> {
    const res = await fetch(`${BASE_URL}/agents/${agentId}/run-stream`, {
      method: 'POST',
      headers: this.headers(),
      body: JSON.stringify({ message, session_id: sessionId }),
    })
    if (!res.ok || !res.body) throw new Error(`Stream failed: ${res.status}`)

    const reader = res.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() ?? ''
      for (const line of lines) {
        if (!line.startsWith('data: ')) continue
        yield JSON.parse(line.slice(6)) as SseEvent
      }
    }
  }

  async runAsync(
    agentId: string,
    message: string,
  ): Promise<{ jobId: string; status: AsyncJobStatus }> {
    const res = await fetch(`${BASE_URL}/agents/${agentId}/run-async`, {
      method: 'POST',
      headers: this.headers(),
      body: JSON.stringify({ message }),
    })
    if (!res.ok) throw new Error(`Enqueue failed: ${res.status}`)
    return res.json()
  }

  async getJob(jobId: string): Promise<AsyncJobResult> {
    const res = await fetch(`${BASE_URL}/jobs/${jobId}`, { headers: this.headers() })
    if (!res.ok) throw new Error(`Job lookup failed: ${res.status}`)
    return res.json() as Promise<AsyncJobResult>
  }

  async pollJob(jobId: string): Promise<AsyncJobResult> {
    const terminal = new Set<AsyncJobStatus>(['completed', 'failed', 'timeout', 'cancelled'])
    let interval = 2000
    let elapsed = 0
    while (true) {
      await new Promise((resolve) => setTimeout(resolve, interval))
      elapsed += interval
      if (elapsed > 30_000) interval = 5000
      const job = await this.getJob(jobId)
      if (terminal.has(job.status)) return job
    }
  }
}

Usage

const client = new ElizonClient('elz_your_key_here')

// Synchronous
const result = await client.run(agentId, 'Hello!')
console.log(result.content)

// Streaming
for await (const event of client.runStream(agentId, 'Hello!')) {
  if (event.event === 'RunContent') process.stdout.write(event.content)
  if (event.event === 'RunCompleted') console.log('\nDone:', event.metrics)
}

// Async
const { jobId } = await client.runAsync(agentId, 'A longer task...')
const job = await client.pollJob(jobId)
console.log(job.status, job.result)