> ## Documentation Index
> Fetch the complete documentation index at: https://www.adaline.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Adaline

# Adaline Class

The `Adaline` class is the main entry point for the TypeScript SDK. It provides methods for fetching deployments and initializing monitors for observability.

## Constructor

```typescript theme={null}
new Adaline(options?: AdalineOptions)
```

### Parameters

<ParamField path="options" type="object" optional>
  Configuration options for the Adaline client

  <Expandable title="properties">
    <ParamField path="apiKey" type="string" optional>
      API key for authentication. If omitted, reads from `ADALINE_API_KEY` environment variable.
    </ParamField>

    <ParamField path="baseURL" type="string" optional default="https://api.adaline.ai/v2">
      Base URL of the Adaline API. Defaults to production API.
    </ParamField>

    <ParamField path="logger" type="Logger" optional>
      Custom [Logger](/docs/reference/sdk/v2/typescript/types/Logger) object with `debug`, `info`, `warn`, `error` methods. Any console-compatible logger works (e.g., `console`, Winston, Pino). Defaults to silent no-op logger.
    </ParamField>

    <ParamField path="debug" type="boolean" optional default={false}>
      If `true` and no `logger` is provided, uses `console` as the logger.
    </ParamField>
  </Expandable>
</ParamField>

### Example

<CodeGroup>
  ```typescript Default theme={null}
  import { Adaline } from '@adaline/client';

  // Uses ADALINE_API_KEY environment variable
  const adaline = new Adaline();
  ```

  ```typescript With Options theme={null}
  import { Adaline } from '@adaline/client';

  const adaline = new Adaline({
    apiKey: 'adl_1234567890',
    baseURL: 'https://api.staging.adaline.ai/v2',
    debug: true
  });
  ```
</CodeGroup>

## Methods

### getDeployment()

Fetch a specific deployment by its ID.

```typescript theme={null}
async getDeployment(options: GetDeploymentOptions): Promise<Deployment>
```

#### Parameters

<ParamField path="options" type="object" required>
  <Expandable title="properties">
    <ParamField path="promptId" type="string" required>
      The unique identifier of the prompt.
    </ParamField>

    <ParamField path="deploymentId" type="string" required>
      The unique identifier of the deployment.
    </ParamField>
  </Expandable>
</ParamField>

#### Returns

<ResponseField name="deployment" type="Deployment">
  The [Deployment](/docs/reference/sdk/v2/typescript/types/deployment) object.

  See [Deployment Type](/docs/reference/sdk/v2/typescript/types/deployment) for complete documentation.
</ResponseField>

#### Example

```typescript theme={null}
const deployment = await adaline.getDeployment({
  promptId: 'prompt_abc123',
  deploymentId: 'deploy_xyz789'
});

console.log(deployment.prompt.config.model); // 'gpt-4o'
console.log(deployment.prompt.messages);     // Array of messages
console.log(deployment.prompt.tools);        // Array of tools
```

### getLatestDeployment()

Fetch the latest deployment for a prompt in a specific environment.

```typescript theme={null}
async getLatestDeployment(options: GetLatestDeploymentOptions): Promise<Deployment>
```

#### Parameters

<ParamField path="options" type="object" required>
  <Expandable title="properties">
    <ParamField path="promptId" type="string" required>
      The unique identifier of the prompt.
    </ParamField>

    <ParamField path="deploymentEnvironmentId" type="string" required>
      The unique identifier of the deployment environment.
    </ParamField>
  </Expandable>
</ParamField>

#### Returns

<ResponseField name="deployment" type="Deployment">
  The latest [Deployment](/docs/reference/sdk/v2/typescript/types/deployment) object for the specified environment.

  See [Deployment Type](/docs/reference/sdk/v2/typescript/types/deployment) for complete documentation.
</ResponseField>

#### Example

```typescript theme={null}
const deployment = await adaline.getLatestDeployment({
  promptId: 'prompt_abc123',
  deploymentEnvironmentId: 'environment_abc123'
});

// Use the deployment config with Adaline Gateway
import { Gateway } from '@adaline/gateway';
import { OpenAI } from '@adaline/openai';

const gateway = new Gateway();
const openaiProvider = new OpenAI();

const model = openaiProvider.chatModel({
  modelName: deployment.prompt.config.model,
  apiKey: process.env.OPENAI_API_KEY!
});

const gatewayResponse = await gateway.completeChat({
  model,
  config: deployment.prompt.config.settings,
  messages: deployment.prompt.messages,
  tools: deployment.prompt.tools
});
```

### initLatestDeployment()

Initialize a cached latest deployment with automatic background refresh. This is the recommended approach for production applications.

```typescript theme={null}
async initLatestDeployment(options: InitLatestDeploymentOptions): Promise<DeploymentController>
```

#### Parameters

<ParamField path="options" type="object" required>
  <Expandable title="properties">
    <ParamField path="promptId" type="string" required>
      The unique identifier of the prompt.
    </ParamField>

    <ParamField path="deploymentEnvironmentId" type="string" required>
      The unique identifier of the deployment environment.
    </ParamField>

    <ParamField path="refreshInterval" type="number" optional default={60}>
      How often to refresh the cached deployment, in seconds. Valid range: 1-600 seconds.
    </ParamField>

    <ParamField path="maxContinuousFailures" type="number" optional default={3}>
      Maximum consecutive failures before stopping background refresh.
    </ParamField>
  </Expandable>
</ParamField>

#### Returns

<ResponseField name="controller" type="DeploymentController">
  A controller object with the following methods:

  <Expandable title="methods">
    <ResponseField name="get()" type="(forceRefresh?: boolean) => Promise<Deployment | undefined>">
      Get the cached deployment. Pass `true` to force a fresh fetch.
    </ResponseField>

    <ResponseField name="backgroundStatus()" type="() => BackgroundStatus">
      Get the current [BackgroundStatus](/docs/reference/sdk/v2/typescript/types/BackgroundStatus) of the background refresh process.
    </ResponseField>

    <ResponseField name="stop()" type="() => void">
      Stop the background refresh and clear the cache.
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example

<CodeGroup>
  ```typescript Basic Usage theme={null}
  const controller = await adaline.initLatestDeployment({
    promptId: 'prompt_abc123',
    deploymentEnvironmentId: 'environment_abc123',
    refreshInterval: 60 // refresh every 60 seconds
  });

  // Get cached deployment (instant, no API call)
  const deployment = await controller.get();

  // Use the deployment
  console.log(deployment.prompt.config.model);

  // Stop background refresh when done
  controller.stop();
  ```

  ```typescript Production Setup theme={null}
  import { Gateway } from '@adaline/gateway';
  import { OpenAI } from '@adaline/openai';

  // Initialize at app startup
  let deploymentController: DeploymentController;
  const gateway = new Gateway();
  const openaiProvider = new OpenAI();

  async function initializeApp() {
    deploymentController = await adaline.initLatestDeployment({
      promptId: process.env.PROMPT_ID!,
      deploymentEnvironmentId: 'environment_abc123',
      refreshInterval: 60,
      maxContinuousFailures: 5
    });

    console.log('Deployment controller initialized');
  }

  // Use in request handlers
  async function handleRequest(req, res) {
    const deployment = await deploymentController.get();

    const model = openaiProvider.chatModel({
      modelName: deployment.prompt.config.model,
      apiKey: process.env.OPENAI_API_KEY!
    });

    const gatewayResponse = await gateway.completeChat({
      model,
      config: deployment.prompt.config.settings,
      messages: deployment.prompt.messages,
      tools: deployment.prompt.tools
    });

    res.json(gatewayResponse.response);
  }

  // Graceful shutdown
  process.on('SIGTERM', () => {
    deploymentController.stop();
    console.log('Deployment controller stopped');
  });
  ```

  ```typescript Health Monitoring theme={null}
  const controller = await adaline.initLatestDeployment({
    promptId: 'prompt_abc123',
    deploymentEnvironmentId: 'environment_abc123'
  });

  // Check background refresh health
  setInterval(() => {
    const status = controller.backgroundStatus();
    
    if (status.stopped) {
      console.error('Background refresh has stopped!');
      // Alert or restart
    }
    
    if (status.consecutiveFailures > 0) {
      console.warn(`${status.consecutiveFailures} consecutive failures`, status.lastError);
    }
    
    console.log(`Last refreshed: ${status.lastRefreshed}`);
  }, 30000); // Check every 30 seconds
  ```

  ```typescript Force Refresh theme={null}
  const controller = await adaline.initLatestDeployment({
    promptId: 'prompt_abc123',
    deploymentEnvironmentId: 'environment_abc123'
  });

  // Get cached (instant)
  const cached = await controller.get();

  // Force fresh fetch (ignores cache, makes API call)
  const fresh = await controller.get(true);
  ```
</CodeGroup>

### initEvaluationResults()

Initialize a cached, polling fetcher for evaluation results. Mirrors `initLatestDeployment()` but targets [`EvaluationResultsClient.list()`](/docs/reference/sdk/v2/typescript/classes/evaluation-results#list). Useful when an evaluation is still running server-side and you want to surface partial results without writing your own polling loop — the same `query` (pagination + filters) is replayed on every refresh.

```typescript theme={null}
async initEvaluationResults(options: InitEvaluationResultsOptions): Promise<EvaluationResultsController>
```

#### Parameters

<ParamField path="options" type="object" required>
  <Expandable title="properties">
    <ParamField path="query" type="EvaluationResultsQuery" required>
      Identifies the evaluation and the page/filter to keep fresh. See [EvaluationResultsQuery](/docs/reference/sdk/v2/typescript/types/EvaluationResultsQuery).
    </ParamField>

    <ParamField path="refreshInterval" type="number" optional default={60}>
      Seconds between background refreshes. Clamped to \[1, 600].
    </ParamField>

    <ParamField path="maxContinuousFailures" type="number" optional default={3}>
      Consecutive failures before the background loop self-stops.
    </ParamField>
  </Expandable>
</ParamField>

#### Returns

<ResponseField name="controller" type="EvaluationResultsController">
  A controller with the same shape as the deployment controller:

  <Expandable title="methods">
    <ResponseField name="get()" type="(forceRefresh?: boolean) => Promise<ListEvaluationResultsResponse | undefined>">
      Get the cached results. Pass `true` to force a fresh fetch.
    </ResponseField>

    <ResponseField name="backgroundStatus()" type="() => BackgroundStatus">
      Current [BackgroundStatus](/docs/reference/sdk/v2/typescript/types/BackgroundStatus).
    </ResponseField>

    <ResponseField name="stop()" type="() => void">
      Stop the background refresh and clear the cache entry.
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example

```typescript theme={null}
const results = await adaline.initEvaluationResults({
  query: {
    promptId: 'prompt_abc123',
    evaluationId: 'eval_abc123',
    grade: 'fail',
    expand: 'row',
    sort: 'score:desc',
    limit: 50,
  },
  refreshInterval: 30,
});

// Poll from your UI layer without additional HTTP
setInterval(async () => {
  const page = await results.get();
  renderEvaluationResults(page);
}, 5000);

// Stop when the user navigates away
onUnmount(() => {
  results.stop();
});
```

### initMonitor()

Initialize a monitoring session for logging traces and spans.

```typescript theme={null}
initMonitor(options: InitMonitorOptions): Monitor
```

#### Parameters

<ParamField path="options" type="object" required>
  <Expandable title="properties">
    <ParamField path="projectId" type="string" required>
      Unique identifier for your project. All traces and spans will be associated with this project.
    </ParamField>

    <ParamField path="flushInterval" type="number" optional default={1}>
      How often to flush buffered entries to the API, in seconds.
    </ParamField>

    <ParamField path="maxBufferSize" type="number" optional default={1000}>
      Maximum number of buffered entries before triggering an automatic flush.
    </ParamField>

    <ParamField path="defaultContent" type="LogSpanContent" optional>
      Default [LogSpanContent](/docs/reference/sdk/v2/typescript/types/LogSpanContent) used when no explicit content is provided. Defaults to `{ type: 'Other', input: '{}', output: '{}' }`.
    </ParamField>
  </Expandable>
</ParamField>

#### Returns

<ResponseField name="monitor" type="Monitor">
  A Monitor instance for creating traces and spans. See [Monitor Class](/docs/reference/sdk/v2/typescript/classes/monitor) for details.
</ResponseField>

#### Example

<CodeGroup>
  ```typescript Basic theme={null}
  const monitor = adaline.initMonitor({
    projectId: 'proj_abc123'
  });

  const trace = monitor.logTrace({ name: 'User Request' });
  // ... log spans ...
  trace.end();
  ```

  ```typescript Custom Configuration theme={null}
  const monitor = adaline.initMonitor({
    projectId: 'proj_abc123',
    flushInterval: 10,        // flush every 10 seconds
    maxBufferSize: 500,       // or when buffer reaches 500 items
  });
  ```

  ```typescript Production Setup theme={null}
  // Initialize once at app startup
  let monitor: Monitor;

  async function initializeApp() {
    const adaline = new Adaline({
      debug: true
    });

    monitor = adaline.initMonitor({
      projectId: process.env.ADALINE_PROJECT_ID!,
      flushInterval: 10,
      maxBufferSize: 500
    });

    setInterval(() => {
      console.log('Monitor health:', {
        bufferSize: monitor.buffer.length,
        sent: monitor.sentCount,
        dropped: monitor.droppedCount
      });
    }, 60000);
  }

  // Export for use throughout app
  export { monitor };

  // Graceful shutdown
  process.on('SIGTERM', async () => {
    await monitor.flush(); // Flush remaining entries
    monitor.stop();        // Stop background flush
  });
  ```
</CodeGroup>

## Namespace clients

Seven namespace clients are attached to every `Adaline` instance. Each wraps the corresponding autogen API with retry-on-5xx, abort-on-4xx, and named-argument ergonomics:

| Property            | Client                                                            | Covers                                                                          |
| ------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `adaline.datasets`  | [DatasetsClient](/docs/reference/sdk/v2/typescript/classes/datasets)   | Datasets (+ `.rows`, `.columns` sub-clients)                                    |
| `adaline.prompts`   | [PromptsClient](/docs/reference/sdk/v2/typescript/classes/prompts)     | Prompts (+ `.draft`, `.playgrounds`, `.evaluators`, `.evaluations` sub-clients) |
| `adaline.providers` | [ProvidersClient](/docs/reference/sdk/v2/typescript/classes/providers) | configured LLM providers                                                        |
| `adaline.models`    | [ModelsClient](/docs/reference/sdk/v2/typescript/classes/models)       | models available across providers                                               |
| `adaline.projects`  | [ProjectsClient](/docs/reference/sdk/v2/typescript/classes/projects)   | list / get / update workspace projects                                          |
| `adaline.logs`      | [LogsClient](/docs/reference/sdk/v2/typescript/classes/logs)           | read-side log access (+ `.traces`, `.spans` sub-clients)                        |

Raw escape hatches are also exposed for cases that don't have a first-class helper yet:

* `adaline.deploymentsApi` — raw `DeploymentsApi` from `@adaline/api`
* `adaline.logsApi` — raw `LogsApi` (used internally by [`Monitor`](/docs/reference/sdk/v2/typescript/classes/monitor))

If you need identical retry behavior on an arbitrary call, use the exported `withRetry` helper:

```typescript theme={null}
import { Adaline, withRetry } from '@adaline/client';

const adaline = new Adaline();

const projects = await withRetry(() => {
  return adaline.projects.list();
});
```

## Complete Example

Here's a complete example showing all methods working together:

```typescript theme={null}
import { Adaline } from '@adaline/client';
import { Gateway } from '@adaline/gateway';
import { OpenAI } from '@adaline/openai';

const adaline = new Adaline({
  debug: true
});

const gateway = new Gateway();
const openaiProvider = new OpenAI();

// Initialize deployment controller
const deploymentController = await adaline.initLatestDeployment({
  promptId: 'chatbot-prompt',
  deploymentEnvironmentId: 'environment_abc123',
  refreshInterval: 60
});

// Initialize monitor
const monitor = adaline.initMonitor({
  projectId: 'chatbot-project'
});

// Handle chat request
async function handleChat(userId: string, message: string) {
  // Get cached deployment (no API call)
  const deployment = await deploymentController.get();

  // Create trace for this conversation
  const trace = monitor.logTrace({
    name: 'Chat Turn',
    sessionId: userId,
    tags: ['chat', 'production'],
    attributes: { userId, messageLength: message.length }
  });

  // Log LLM call
  const span = trace.logSpan({
    name: 'LLM Completion',
    promptId: deployment.promptId,
    deploymentId: deployment.id,
    runEvaluation: true,
    tags: ['llm', deployment.prompt.config.providerName]
  });

  try {
    const model = openaiProvider.chatModel({
      modelName: deployment.prompt.config.model,
      apiKey: process.env.OPENAI_API_KEY!
    });

    const gatewayResponse = await gateway.completeChat({
      model,
      config: deployment.prompt.config.settings,
      messages: [
        ...deployment.prompt.messages,
        { role: 'user', content: [{ modality: 'text', value: message }] }
      ],
      tools: deployment.prompt.tools
    });

    const reply = gatewayResponse.response.messages[0].content[0].value;

    // Update span with success
    span.update({
      status: 'success',
      content: {
        type: 'Model',
        provider: deployment.prompt.config.providerName,
        model: deployment.prompt.config.model,
        input: JSON.stringify(gatewayResponse.provider.request),
        output: JSON.stringify(gatewayResponse.provider.response)
      }
    });

    trace.update({ status: 'success' });

    return reply;

  } catch (error) {
    span.update({
      status: 'failure',
      attributes: {
        error: error instanceof Error ? error.message : String(error)
      }
    });
    trace.update({ status: 'failure' });
    throw error;

  } finally {
    span.end();
    trace.end();
  }
}

// Graceful shutdown
process.on('SIGTERM', async () => {
  await monitor.flush();
  monitor.stop();
  deploymentController.stop();
  console.log('Shutdown complete');
});
```

## Type Definitions

```typescript theme={null}
interface AdalineOptions {
  apiKey?: string;
  baseURL?: string;
  logger?: Logger;
  debug?: boolean;
}

interface Logger {
  debug(message: string, ...args: unknown[]): void;
  info(message: string, ...args: unknown[]): void;
  warn(message: string, ...args: unknown[]): void;
  error(message: string, ...args: unknown[]): void;
}

interface GetDeploymentOptions {
  promptId: string;
  deploymentId: string;
}

interface GetLatestDeploymentOptions {
  promptId: string;
  deploymentEnvironmentId: string;
}

interface InitLatestDeploymentOptions {
  promptId: string;
  deploymentEnvironmentId: string;
  refreshInterval?: number;
  maxContinuousFailures?: number;
}

interface BackgroundStatus {
  stopped: boolean;
  consecutiveFailures: number;
  lastError: Error | null;
  lastRefreshed: Date;
}

// Return type of initLatestDeployment() (not an exported class)
interface DeploymentController {
  get: (forceRefresh?: boolean) => Promise<Deployment | undefined>;
  backgroundStatus: () => BackgroundStatus;
  stop: () => void;
}

interface InitMonitorOptions {
  projectId: string;
  flushInterval?: number;  // default: 1
  maxBufferSize?: number;  // default: 1000
  defaultContent?: LogSpanContent;
}
```

## Best Practices

### Use Environment Variables

```typescript theme={null}
const adaline = new Adaline({
  apiKey: process.env.ADALINE_API_KEY,
  baseURL: process.env.ADALINE_API_URL || 'https://api.adaline.ai/v2'
});
```

### Initialize Once, Use Everywhere

```typescript theme={null}
// Initialize at app startup
let deploymentController: DeploymentController;
let monitor: Monitor;

async function initialize() {
  const adaline = new Adaline();
  
  deploymentController = await adaline.initLatestDeployment({
    promptId: process.env.PROMPT_ID!,
    deploymentEnvironmentId: process.env.ENVIRONMENT!
  });
  
  monitor = adaline.initMonitor({
    projectId: process.env.PROJECT_ID!
  });
}

// Export for use throughout your app
export { deploymentController, monitor };
```

### Monitor Health in Production

```typescript theme={null}
const controller = await adaline.initLatestDeployment({ /* ... */ });

// Set up health check
setInterval(() => {
  const status = controller.backgroundStatus();
  
  if (status.stopped) {
    // Alert: Background refresh stopped!
    logger.error('Deployment refresh stopped', status.lastError);
  }
  
  if (status.consecutiveFailures >= 2) {
    // Warning: Having issues
    logger.warn('Deployment refresh failures', {
      failures: status.consecutiveFailures,
      lastError: status.lastError
    });
  }
}, 60000); // Check every minute
```

### Handle Graceful Shutdown

```typescript theme={null}
async function gracefulShutdown() {
  console.log('Shutting down...');
  
  // Flush remaining logs
  await monitor.flush();
  
  // Stop background processes
  monitor.stop();
  deploymentController.stop();
  
  console.log('Shutdown complete');
  process.exit(0);
}

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
```
