Groq TypeScript SDK

repository·main·Indexed 42 days ago

https://github.com/groq/groq-typescript

The official TypeScript/JavaScript library (groq-sdk v1.6.0) for the Groq REST API. It provides type-safe access to chat completions, embeddings, audio transcriptions, translations, and batch processing. Supports Node.js 20 LTS+, Deno, Bun, Cloudflare Workers, and Vercel Edge Runtime.

Tokens
13.7K
Snippets
51
Records
66
Agent score
54%

What's inside Groq

  1. Handle Web-standard Response and Error types

    main

    The SDK now uses the builtin Web fetch API. This changes how withResponse, asResponse, and APIError.headers behave:

    • Response Bodies: The body property is now a Web ReadableStream instead of a Node.js Readable. To use Node.js stream methods (like .pipe()), you must convert it using Readable.fromWeb() from the node:stream module.
    • Error Headers: The headers property on APIError objects is now an instance of the Web Headers class, rather than a plain Record<string, string | null | undefined> object.
    // Converting a Web ReadableStream body to a Node.js stream
    import { Readable } from 'node:stream';
    
    const res = await client.example.retrieve('string/with/slash').asResponse();
    Readable.fromWeb(res.body).pipe(process.stdout);
  2. Configure retries and timeouts

    main

    The library provides mechanisms to manage request resilience:

    Retries

    Certain errors (Connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors) are automatically retried 2 times by default using exponential backoff. Use maxRetries to change this behavior.

    Timeouts

    Requests time out after 1 minute by default. On timeout, an APIConnectionTimeoutError is thrown. Use timeout to adjust this. Note that timed-out requests are also subject to the default retry logic.

    You can configure these globally in the Groq constructor or override them on a per-request basis.

    // Global configuration
    const client = new Groq({
      maxRetries: 0, // default is 2
      timeout: 20 * 1000, // 20 seconds (default is 1 minute)
    });
    
    // Per-request override
    await client.chat.completions.create(
      { 
        messages: [{ role: 'user', content: '...' }], 
        model: 'openai/gpt-oss-20b' 
      }, 
      { 
        maxRetries: 5, 
        timeout: 5 * 1000 
      }
    );
  3. Supported runtimes and requirements

    main

    Requirements

    • TypeScript: >= 4.9

    Supported Runtimes

    • Node.js: 20 LTS or later
    • Deno: v1.28.0 or higher
    • Bun: 1.0 or later
    • Cloudflare Workers
    • Vercel Edge Runtime
    • Jest: 28 or greater (with "node" environment; "jsdom" is not supported)
    • Nitro: v2.6 or greater
    • Web Browsers: Disabled by default to prevent API credential exposure. To enable, set dangerouslyAllowBrowser: true in the client configuration.

    Note: React Native is not supported.

  4. Use the Groq SDK migration CLI

    main

    To automate the migration to the latest version of the Groq TypeScript SDK, you can use the built-in migration tool. This tool helps update your code to accommodate changes like the switch to the Web fetch API and new export structures.

    1. Upgrade the groq-sdk package.
    2. Run the migration tool against your source folders: ./node_modules/.bin/groq-sdk migrate ./your/src/folders

    To preview changes without modifying your files, use the --dry flag.

    # Run migration on your source directory
    ./node_modules/.bin/groq-sdk migrate ./src
    
    # Preview changes without writing to disk
    ./node_modules/.bin/groq-sdk migrate ./src --dry
  5. Make custom or undocumented requests

    main

    If you need to access endpoints, parameters, or response properties not yet included in the typed SDK, you can bypass the type safety:

    1. Undocumented Endpoints: Use HTTP verb methods directly on the client (e.g., client.post('/path', { ... })). Client options like retries are still respected.
    2. Undocumented Parameters: Pass extra properties to existing methods and use // @ts-expect-error to suppress TypeScript errors. For GET requests, extra params are sent as query strings; for other verbs, they are sent in the body.
    3. Undocumented Response Properties: Access properties on the returned object using // @ts-expect-error or by casting to a custom type.
    // Undocumented endpoint
    await client.post('/some/path', {
      body: { some_prop: 'foo' },
      query: { some_query_arg: 'bar' },
    });
    
    // Undocumented parameter
    client.chat.completions.create({
      // ...
      // @ts-expect-error baz is not yet public
      baz: 'undocumented option',
    });
  6. Upload files for transcription or processing

    main

    When a request parameter requires a file upload, you can provide the file in several formats:

    • A web File object.
    • A fetch Response object.
    • A Node.js fs.ReadStream (recommended for Node environments).
    • The return value of the toFile helper (useful for Buffer or Uint8Array).
    import fs from 'fs';
    import Groq, { toFile } from 'groq-sdk';
    
    const client = new Groq();
    
    // Using Node.js fs.createReadStream()
    await client.audio.transcriptions.create({
      model: 'whisper-large-v3-turbo',
      file: fs.createReadStream('/path/to/file'),
    });
    
    // Using web File API
    await client.audio.transcriptions.create({
      model: 'whisper-large-v3-turbo',
      file: new File(['my bytes'], 'file'),
    });
    
    // Using fetch Response
    await client.audio.transcriptions.create({
      model: 'whisper-large-v3-turbo',
      file: await fetch('https://somesite/file'),
    });
    
    // Using toFile helper for Buffers or Uint8Arrays
    await client.audio.transcriptions.create({
      model: 'whisper-large-v3-turbo',
      file: await toFile(Buffer.from('my bytes'), 'file'),
    });
    
    await client.audio.transcriptions.create({
      model: 'whisper-large-v3-turbo',
      file: await toFile(new Uint8Array([0, 1, 2]), 'file'),
    });
  7. Use the Groq client for Chat Completions

    main

    Initialize the Groq client using an API key. By default, the client looks for the GROQ_API_KEY environment variable. You can then use client.chat.completions.create to generate text completions.

    import Groq from 'groq-sdk';
    
    const client = new Groq({
      apiKey: process.env['GROQ_API_KEY'], // This is the default and can be omitted,
    });
    
    const chatCompletion = await client.chat.completions.create({
      messages: [{ role: 'user', content: 'Explain the importance of low latency LLMs' }],
      model: 'openai/gpt-oss-20b',
    });
    
    console.log(chatCompletion.id);
  8. Customize the fetch client and fetch options

    main

    The SDK uses a global fetch by default. You can provide a custom fetch implementation or configure fetchOptions (which accept RequestInit options) during client instantiation or per request.

    Configuring Proxies via fetchOptions:

    • Node.js (using undici): Use the dispatcher key.
    • Bun: Use the proxy key.
    • Deno: Use the client key with a Deno.HttpClient.
    // Node.js Proxy Example
    import Groq from 'groq-sdk';
    import * as undici from 'undici';
    
    const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
    const client = new Groq({
      fetchOptions: {
        dispatcher: proxyAgent,
      },
    });
    
    // Bun Proxy Example
    const clientBun = new Groq({
      fetchOptions: {
        proxy: 'http://localhost:8888',
      },
    });
    
    // Deno Proxy Example
    import { Groq } from 'npm:groq-sdk';
    const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
    const clientDeno = new Groq({
      fetchOptions: {
        client: httpClient,
      },
    });
  9. Access Groq API resources

    main

    The Groq client provides access to several specialized resource namespaces for interacting with different parts of the Groq API:

    • groq.chat: Chat completions and conversational AI.
    • groq.completions: Standard text completions.
    • groq.embeddings: Generating vector embeddings.
    • groq.audio: Audio processing capabilities.
    • groq.models: Managing and listing available models.
    • groq.batches: Managing batch processing jobs.
    • groq.files: Managing uploaded files for use in other API calls.
  10. Configure logging and log levels

    main

    The Groq SDK supports configurable logging for debugging. You can set the log level via the GROQ_LOG environment variable or the logLevel client option (which takes precedence).

    Available log levels (most to least verbose):

    • 'debug': Shows debug messages, info, warnings, and errors. Includes full HTTP requests/responses (headers and bodies).
    • 'info': Shows info, warnings, and errors.
    • 'warn': Shows warnings and errors (Default).
    • 'error': Shows only errors.
    • 'off': Disables all logging.
    IMPORTANT

    Log formats may change between releases. At 'debug' level, sensitive data in request/response bodies may be visible.

    import Groq from 'groq-sdk';
    
    const client = new Groq({
      logLevel: 'debug', // Show all log messages
    });