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

@axflow/models

v0.0.25

Published

Zero-dependency, modular SDK for building robust natural language applications

Downloads

454

Readme

@axflow/models

Zero-dependency, modular SDK for building robust natural language applications.

npm i @axflow/models

Features

  • Support for all leading model providers, plus popular open source models like Llama2 or Mistral through Together.ai inference
  • First-class streaming support for both low-level byte streams and higher-level JavaScript object streams
  • First-class support for streaming arbitrary data in addition to the LLM response
  • Comes with a set of utilities and React hooks for easily creating robust client applications
  • Built exclusively on modern web standards such as fetch and the stream APIs
  • Supports Node 18+, Next.js serverless or edge runtime, Express.js, browsers, ESM, CJS, and more
  • Supports a custom fetch implementation for request middleware (e.g., custom headers, logging)

Supported models

  • ✅ OpenAI and OpenAI-compatible Chat, Completion, and Embedding models
  • ✅ Cohere and Cohere-compatible Generation and Embedding models
  • ✅ Anthropic and Anthropic-compatible Completion models
  • ✅ HuggingFace text generation inference API and Inference Endpoints
  • ✅ Ollama.ai models running locally
  • ✅ Azure OpenAI
  • ✅ Google Gemini
  • ✅ TogetherAI (Llama2, Mistral, etc.)

Documentation

View the Guides or the reference:

Example Usage

import { OpenAIChat } from '@axflow/models/openai/chat';
import { CohereGenerate } from '@axflow/models/cohere/generate';
import { StreamToIterable } from '@axflow/models/shared';

const gpt4Stream = OpenAIChat.stream(
  {
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'What is the Eiffel tower?' }],
  },
  {
    apiKey: '<openai api key>',
  },
);

const cohereStream = CohereGenerate.stream(
  {
    model: 'command-nightly',
    prompt: 'What is the Eiffel tower?',
  },
  {
    apiKey: '<cohere api key>',
  },
);

// StreamToIterable is optional in recent node versions as
// ReadableStreams already implement the async iterator protocol
for await (const chunk of StreamToIterable(gpt4Stream)) {
  console.log(chunk.choices[0].delta.content);
}

for await (const chunk of StreamToIterable(cohereStream)) {
  console.log(chunk.text);
}

For models that support streaming, there is a convenience method for streaming only the string tokens.

import { OpenAIChat } from '@axflow/models/openai/chat';

const tokenStream = OpenAIChat.streamTokens(
  {
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'What is the Eiffel tower?' }],
  },
  {
    apiKey: '<openai api key>',
  },
);

// Example stdout output:
//
// The Eiffel Tower is a renowned wrought-iron landmark located in Paris, France, known globally as a symbol of romance and elegance.
//
for await (const token of tokenStream) {
  process.stdout.write(token);
}

process.stdout.write('\n');

useChat hook for dead simple UI integration

We've made building chat and completion UIs trivial. It doesn't get any easier than this 🚀

///////////////////
// On the server //
///////////////////
import { OpenAIChat } from '@axflow/models/openai/chat';
import { StreamingJsonResponse, type MessageType } from '@axflow/models/shared';

export const runtime = 'edge';

export async function POST(request: Request) {
  const { messages } = await request.json();

  const stream = await OpenAIChat.streamTokens(
    {
      model: 'gpt-4',
      messages: messages.map((msg: MessageType) => ({ role: msg.role, content: msg.content })),
    },
    {
      apiKey: process.env.OPENAI_API_KEY!,
    },
  );

  return new StreamingJsonResponse(stream);
}

///////////////////
// On the client //
///////////////////
import { useChat } from '@axflow/models/react';

function ChatComponent() {
  const { input, messages, onChange, onSubmit } = useChat();

  return (
    <>
      <Messages messages={messages} />
      <Form input={input} onChange={onChange} onSubmit={onSubmit} />
    </>
  );
}

Next.js edge proxy example

Sometimes you just want to create a proxy to the underlying LLM API. In this example, the server intercepts the request on the edge, adds the proper API key, and forwards the byte stream back to the client.

Note this pattern works exactly the same with our other models that support streaming, like Cohere and Anthropic.

import { NextRequest, NextResponse } from 'next/server';
import { OpenAIChat } from '@axflow/models/openai/chat';

export const runtime = 'edge';

// POST /api/openai/chat
export async function POST(request: NextRequest) {
  const chatRequest = await request.json();

  // We'll stream the bytes from OpenAI directly to the client
  const stream = await OpenAIChat.streamBytes(chatRequest, {
    apiKey: process.env.OPENAI_API_KEY!,
  });

  return new NextResponse(stream);
}

On the client, we can use OpenAIChat.stream with a custom apiUrl in place of the apiKey that points to our Next.js edge route.

DO NOT expose api keys to your frontend.

import { OpenAIChat } from '@axflow/models/openai/chat';
import { StreamToIterable } from '@axflow/models/shared';

const stream = await OpenAIChat.stream(
  {
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'What is the Eiffel tower?' }],
  },
  {
    apiUrl: '/api/openai/chat',
  },
);

for await (const chunk of StreamToIterable(stream)) {
  console.log(chunk.choices[0].delta.content);
}

Express.js example

Uses express + React hook on frontend.

///////////////////
// On the server //
///////////////////
const express = require('express');
const { OpenAIChat } = require('@axflow/models/openai/chat');
const { streamJsonResponse } = require('@axflow/models/node');

const app = express();
app.use(express.json());

app.post('/api/chat', async (req, res) => {
  const { messages } = req.body;

  const stream = await OpenAIChat.streamTokens(
    {
      model: 'gpt-3.5-turbo',
      messages: messages.map((msg) => ({
        role: msg.role,
        content: msg.content,
      })),
    },
    {
      apiKey: process.env.OPENAI_API_KEY,
    },
  );

  return streamJsonResponse(stream, res);
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

///////////////////
// On the client //
///////////////////
import { useChat } from '@axflow/models/react';

function ChatComponent() {
  const { input, messages, onChange, onSubmit } = useChat();

  return (
    <>
      <Messages messages={messages} />
      <Form input={input} onChange={onChange} onSubmit={onSubmit} />
    </>
  );
}