TypeScript

A typed helper for calling OptimAI Search from server-side TypeScript.

type SearchRequest = {
  query: string
  limit?: number
}

type SearchResponse = {
  answer?: string
  sources?: Array<{ title?: string; url: string }>
  metadata?: Record<string, unknown>
}

export async function searchOptimAI(input: SearchRequest): Promise<SearchResponse> {
  const apiKey = process.env.OPTIMAI_API_KEY

  if (!apiKey) {
    throw new Error("OPTIMAI_API_KEY is required")
  }

  const response = await fetch("https://api-onchain.optimai.network/v1/search", {
    method: "POST",
    headers: {
      "X-API-Key": apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(input),
  })

  if (!response.ok) {
    const message = await response.text()
    throw new Error(`OptimAI Search failed with status ${response.status}: ${message}`)
  }

  return response.json() as Promise<SearchResponse>
}