chat-completions

5.1.0 • Public • Published

ChatCompletions

A reactive state machine implementation for OpenAI Chat Completions API.

ChatCompletions is a state machine implementation designed to interact seamlessly with the OpenAI Chat Completions API. It wraps around the API calls and manages the communication state with a reactive approach. Utilizing StateGuard, it supports both browser and Node environments and simplifies the process of sending and receiving messages from the Chat Completions API.

Installation

npm install chat-completions state-guard zod

Usage Example

The following example demonstrates how to create and use a state machine to interact with the OpenAI Chat Completions API in a Node.js environment:

import {createChatCompletionsMachine} from 'chat-completions';
import {env, stderr, stdout} from 'node:process';

const machine = createChatCompletionsMachine();

machine.subscribe(() => {
  const snapshot = machine.get();

  switch (snapshot.state) {
    case `isReceivingContent`: {
      stdout.write(snapshot.value.contentDelta);
      break;
    }
    case `isContentFinished`: {
      stdout.write(`\n`);
      break;
    }
    case `isFailed`: {
      stderr.write(`${snapshot.value.error}\n`);
    }
  }
});

const apiKey = /** @type {string} */ (env.API_KEY);

machine.assert(`isInitialized`).actions.sendRequest({
  apiKey,
  body: {
    model: `gpt-4`,
    messages: [{role: `user`, content: `Hello, World!`}],
  },
});

Dependencies (0)

    Dev Dependencies (14)

    Package Sidebar

    Install

    npm i chat-completions

    Weekly Downloads

    7

    Version

    5.1.0

    License

    MIT

    Unpacked Size

    86.8 kB

    Total Files

    18

    Last publish

    Collaborators

    • clebert