npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@devoxa/openai-structured-chat

v1.1.0

Published

OpenAI chat completion with schema validation and error correction

Downloads

3

Readme

Installation

yarn add @devoxa/openai-structured-chat openai zod

Usage

Basic usage

import OpenAI from 'openai'
import { StructuredChat } from '@devoxa/openai-structured-chat'

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })

const chat = new StructuredChat({
  openai: openai,
  params: { model: 'gpt-4o' },
})

const result = await chat.send({
  messages: [
    { role: 'system', content: 'Your task is to convert any statements to standard English.' },
    { role: 'user', content: 'She no went to the market.' },
  ],
})

Schema-validated functions

import { z } from 'zod'

const chat = new StructuredChat({
  openai: openai,
  params: {
    model: 'gpt-4o',
    tools: [
      {
        type: 'function',
        function: {
          name: 'return_sentiment' as const,
          parameters: z.object({
            /** The sentiment of the tweet */
            sentiment: z
              .enum(['positive', 'neutral', 'negative'])
              .describe('The sentiment of the tweet'),
          }),
        },
      },
    ],
  },
  options: {
    // The maximum number of times that the client will attempt to correct errors in case of a
    // hallucinated model response, like an incorrect function name or an argument schema mismatch.
    // Defaults to `2`.
    maxErrorCorrectionTries: 2,
  },
})

const result = await chat.send({
  // Messages to add to the existing conversation
  messages: [
    {
      role: 'system',
      content:
        'You will be provided with a tweet, and your task is to classify its sentiment as positive, neutral, or negative.',
    },
    { role: 'user', content: 'I loved the new Batman movie!' },
  ],

  // - `none` means the model will not call a function and instead generate a message.
  // - `auto` means the model can pick between generating a message or calling a function.
  // - `function` means the model will always call a function and never generate a message.
  // - `{ type: 'function', function: { name: 'my_function' } }` forces the model to call a specific function.
  // Defaults to `none` when no functions are present or `auto` when functions are present.
  tool_choice: 'function',
})

const func = result.choices[0].message.tool_calls?.[0].function
if (func?.name === 'return_sentiment') {
  console.log(func.arguments) // -> { sentiment: 'positive' }
}

Message history

You can retrieve and manipulate the message history of the chat with the provided functions:

const messages = chat.getMessages()

chat.setMessages([
  { role: 'system', content: 'Your task is to convert any statements to correct English.' },
  { role: 'user', content: 'She no went to the market.' },
])

chat.addMessage({ role: 'assistant', content: "She didn't go to the market." })

Caching

You can provide an optional cacheAdapter, which causes all requests to the OpenAI API to be cached based on the parameters and options of the requests.

This package includes a FileSystemCacheAdapter that is meant to be used for consistent integration tests. For your own use-cases you can bring your own cache adapter by implementing the CacheAdapter interface.

import { FileSystemCacheAdapter } from '@devoxa/openai-structured-chat'
import path from 'path'

const cacheAdapter = new FileSystemCacheAdapter({
  baseDirectory: path.join(__dirname, '.cache'),
})

const chat = new StructuredChat({
  openai: openai,
  cacheAdapter,
  // ...
})

Default request params and options

You can provide defaults for all requests in the top level params and options parameters of the constructor. Keep in mind that the default timeout of the openai library is 60s (options.timeout) with 2 additional retries (options.maxRetries), which may be too long for your application.

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT