iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😺

Vercel AI SDK is Absolutely Incredible

に公開
2023/06/26

Introduction

I welcome comments or edit requests on GitHub for any corrections or additions.

Main Topic

It looked interesting, so I decided to try it out.

https://vercel.com/blog/introducing-the-vercel-ai-sdk

How to Use

Implement the API.

app/api/chat/route.ts
import { OpenAIStream, StreamingTextResponse } from 'ai'
import { Configuration, OpenAIApi } from 'openai-edge'

// Create an OpenAI API client.
const config = new Configuration({
  apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(config)

// Important! Set the runtime to edge.
export const runtime = 'edge'

export async function POST(req: Request) {
  // Extract `messages` from the request body.
  const { messages } = await req.json()
  // Request streaming chat completion from OpenAI with the specified prompt.
  const response = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    stream: true,
    messages
  })
  // Convert the response into a friendly text stream.
  const stream = OpenAIStream(response)
  // Respond with the stream.
  return new StreamingTextResponse(stream)
}

Create the page.

app/chat/page.tsx
'use client'

import { useChat } from 'ai/react'

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat()
  // You can specify the URL by using useChat({ api: `/api/chat` }).

  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.role}: {m.content}
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <label>
          Say something...
          <input
            value={input}
            onChange={handleInputChange}
          />
        </label>
      </form>
    </div>
  )
}

It works with just this.
Furthermore, since it operates via streaming, responses return in real-time.

A Little Improvement

Let's make it possible to specify the model type.

app/api/chat/[model]/route.ts
import { OpenAIStream, StreamingTextResponse } from 'ai'
import { Configuration, OpenAIApi } from 'openai-edge'

// Create an OpenAI API client.
const config = new Configuration({
  apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(config)

// Important! Set the runtime to edge.
export const runtime = 'edge'

export async function POST(
  req: Request,
  { params }: { params: { model: string } },
) {
  const model = params.model;
  // Extract `messages` from the request body.
  const { messages } = await req.json()
  // Request streaming chat completion from OpenAI with the specified prompt.
  const response = await openai.createChatCompletion({
    model,
    stream: true,
    messages
  })
  // Convert the response into a friendly text stream.
  const stream = OpenAIStream(response)
  // Respond with the stream.
  return new StreamingTextResponse(stream)
}
app/chat/page.tsx
"use client";

import { useChat } from "ai/react";
import { useState } from "react";
export default function Chat() {
  const [model, setModel] = useState("gpt-3.5-turbo-16k");
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: `/api/chat/${model}`,
  });

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          {m.role}: {m.content}
        </div>
      ))}
      <select onChange={(e) => setModel(e.target.value)} value={model}>
        <option value="gpt-3.5-turbo">gpt-3.5-turbo</option>
        <option value="gpt-3.5-turbo-16k">gpt-3.5-turbo-16k</option>
        <option value="gpt-4">gpt-4</option>
      </select>
      <form onSubmit={handleSubmit}>
        <label>
          Say something...
          <input value={input} onChange={handleInputChange} />
        </label>
      </form>
    </div>
  );
}

Official Playground

https://sdk.vercel.ai/

Summary

It's seriously amazing.
It's so convenient that I almost feel like this is all I need.
While it allows for lightning-fast development, the dependency on Next.js is a bit scary.

GitHubで編集を提案

Discussion