> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Use AI SDK with CometAPI

> Use this guide to configure AI SDK with CometAPI by setting the base URL, API key, and model or provider options.

The [CometAPI provider for the AI SDK](https://github.com/cometapi-dev/ai-sdk-provider) gives you access to 500+ AI models through a unified TypeScript interface. Use it to add text generation, streaming, embeddings, and image generation to any Node.js or Edge runtime application.

## Supported features

| Feature          | Method                 | Status    |
| ---------------- | ---------------------- | --------- |
| Text generation  | `generateText()`       | Supported |
| Text streaming   | `streamText()`         | Supported |
| Text embeddings  | `textEmbeddingModel()` | Supported |
| Image generation | `imageModel()`         | Supported |

## Prerequisites

* Node.js 18+
* A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token)

<Steps>
  <Step title="Install the provider">
    Install `@cometapi/ai-sdk-provider` alongside the AI SDK core package:

    <CodeGroup>
      ```bash npm theme={null}
      npm install @cometapi/ai-sdk-provider ai
      ```

      ```bash pnpm theme={null}
      pnpm add @cometapi/ai-sdk-provider ai
      ```

      ```bash yarn theme={null}
      yarn add @cometapi/ai-sdk-provider ai
      ```
    </CodeGroup>
  </Step>

  <Step title="Set your API key">
    The provider reads the `COMETAPI_KEY` environment variable by default:

    ```bash theme={null}
    read -rsp "CometAPI API key: " COMETAPI_KEY
    printf '\n'
    export COMETAPI_KEY
    ```

    <Note>
      Use environment variables to avoid hardcoding credentials in your source code.
    </Note>
  </Step>

  <Step title="Import the provider">
    Import the default provider instance:

    ```typescript theme={null}
    import { cometapi } from '@cometapi/ai-sdk-provider';
    ```

    To override the API key, base URL, or other settings, use `createCometAPI`:

    ```typescript theme={null}
    import { createCometAPI } from '@cometapi/ai-sdk-provider';

    const cometapi = createCometAPI({
      apiKey: process.env.COMETAPI_KEY,       // override env variable
      baseURL: 'https://api.cometapi.com/v1',  // default
    });
    ```
  </Step>
</Steps>

## Usage

### Generate text

Use `generateText()` for a single-shot response:

```typescript theme={null}
import { cometapi } from '@cometapi/ai-sdk-provider';
import { generateText } from 'ai';

const { text } = await generateText({
  model: cometapi('your-model-id'),
  prompt: 'What is CometAPI?',
});

console.log(text);
```

### Stream text

Use `streamText()` for real-time chunked output:

```typescript theme={null}
import { cometapi } from '@cometapi/ai-sdk-provider';
import { streamText } from 'ai';

const result = streamText({
  model: cometapi('your-model-id'),
  prompt: 'Write a short story about AI.',
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}
```

### Generate embeddings

Use `textEmbeddingModel()` to create vector embeddings:

```typescript theme={null}
import { cometapi } from '@cometapi/ai-sdk-provider';

const model = cometapi.textEmbeddingModel('text-embedding-3-small');

// Single embedding
const single = await model.doEmbed({ values: ['Hello, world!'] });
console.log('Dimensions:', single.embeddings[0].length);

// Batch embeddings
const batch = await model.doEmbed({
  values: ['sunny day', 'rainy afternoon', 'cold winter night'],
});
console.log('Count:', batch.embeddings.length);
```

### Generate images

Use `imageModel()` to generate images from text prompts:

```typescript theme={null}
import { cometapi } from '@cometapi/ai-sdk-provider';
import { experimental_generateImage as generateImage } from 'ai';

const { image } = await generateImage({
  model: cometapi.imageModel('your-model-id'),
  prompt: 'A beautiful sunset over mountains',
});
```

## Provider configuration

`createCometAPI` accepts the following options:

| Option    | Type                     | Default                       | Description                 |
| --------- | ------------------------ | ----------------------------- | --------------------------- |
| `apiKey`  | `string`                 | `process.env.COMETAPI_KEY`    | CometAPI API key            |
| `baseURL` | `string`                 | `https://api.cometapi.com/v1` | API base URL                |
| `headers` | `Record<string, string>` | —                             | Custom request headers      |
| `fetch`   | `FetchFunction`          | —                             | Custom fetch implementation |

## Model methods

The provider exposes several model constructors:

| Method                                 | Returns            | Use case                                  |
| -------------------------------------- | ------------------ | ----------------------------------------- |
| `cometapi(modelId)`                    | `LanguageModelV2`  | Text generation and streaming (shorthand) |
| `cometapi.chatModel(modelId)`          | `LanguageModelV2`  | Chat completions                          |
| `cometapi.completionModel(modelId)`    | `LanguageModelV2`  | Text completions                          |
| `cometapi.languageModel(modelId)`      | `LanguageModelV2`  | Alias for `chatModel`                     |
| `cometapi.textEmbeddingModel(modelId)` | `EmbeddingModelV2` | Text embeddings                           |
| `cometapi.imageModel(modelId)`         | `ImageModelV2`     | Image generation                          |

Browse the full list of available model IDs on the [Models page](/overview/models).

<AccordionGroup>
  <Accordion title="Tips and troubleshooting">
    * **Model selection**: Any model from the [CometAPI model catalog](/overview/models) works with the corresponding model method — chat models via `cometapi()`, embedding models via `textEmbeddingModel()`, image models via `imageModel()`.
    * **Fine-tuning responses**: Pass `temperature`, `maxTokens`, and `topP` directly to `generateText()` or `streamText()`, e.g. `generateText(\{..., temperature: 0.7\})`.
    * **Error handling**: Wrap calls in `try/catch` to handle authentication errors, rate limits, or network issues.
    * **Security**: Never commit API keys to version control. Use environment variables or a secrets manager.
    * **Rate limits**: Monitor usage in the [CometAPI console](https://www.cometapi.com/console).
  </Accordion>
</AccordionGroup>

## Related resources

* [CometAPI AI SDK Provider on GitHub](https://github.com/cometapi-dev/ai-sdk-provider)
* [@cometapi/ai-sdk-provider on npm](https://www.npmjs.com/package/@cometapi/ai-sdk-provider)
* [AI SDK documentation](https://ai-sdk.dev/docs)
* [CometAPI quick start](/overview/quick-start)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "HowTo",
        "@id": "https://apidoc.cometapi.com/integrations/ai-sdk#howto",
        "name": "Use AI SDK with CometAPI",
        "description": "Use this guide to configure AI SDK with CometAPI by setting the base URL, API key, and model or provider options.",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/ai-sdk#step-1",
            "position": 1,
            "name": "Install the provider",
            "text": "Complete the Install the provider step in the Use AI SDK with CometAPI guide."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/ai-sdk#step-2",
            "position": 2,
            "name": "Set your API key",
            "text": "Store your CometAPI API key in the environment variable or settings field used by the integration."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/ai-sdk#step-3",
            "position": 3,
            "name": "Import the provider",
            "text": "Complete the Import the provider step in the Use AI SDK with CometAPI guide."
          }
        ]
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "CometAPI Docs",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Integrations",
            "item": "https://apidoc.cometapi.com/integrations"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Use AI SDK with CometAPI",
            "item": "https://apidoc.cometapi.com/integrations/ai-sdk"
          }
        ]
      }
    ]
    }
    `}
</script>
