Rumah  >  Artikel  >  hujung hadapan web  >  Vercel AI SDK

Vercel AI SDK

WBOY
WBOYasal
2024-08-16 06:12:02443semak imbas

Memperkenalkan pengesanan, lampiran berbilang modal, penstriman JSON kepada pelanggan dan banyak lagi.

Vercel AI SDK ialah kit alat untuk membina aplikasi AI dengan JavaScript dan TypeScript. API bersatu membolehkan anda menggunakan mana-mana model bahasa dan menyediakan integrasi UI yang berkuasa ke dalam rangka kerja web terkemuka seperti Next.js dan Svelte.

Vercel AI SDK 3.3 memperkenalkan empat ciri utama:

  • Menjejak (percubaan): instrumen AI SDK berfungsi menggunakan OpenTelemetry
  • Lampiran Fail Berbilang Modal (percubaan): hantar lampiran fail dengan useChat
  • useObject hook (percubaan): aliran penjanaan objek berstruktur kepada pelanggan
  • Tetapan LLM Tambahan: JSON mentah untuk alatan dan penjanaan objek berstruktur, urutan berhenti dan menghantar pengepala tersuai

Kami juga telah menambah pembekal model AWS Bedrock dan Chrome AI (komuniti) serta banyak ciri dan tambahan yang lebih kecil. Anda boleh menemui semua perubahan termasuk ciri kecil dalam log perubahan kami.

Ciri eksperimen membolehkan anda menggunakan fungsi AI SDK terkini secepat mungkin. Walau bagaimanapun, mereka boleh berubah dalam versi tampalan. Sila semat versi tampung jika anda memutuskan untuk menggunakan ciri percubaan.

Menjejak

Memandangkan sifat model bahasa yang tidak menentukan, kebolehmerhatian adalah penting untuk memahami dan membangunkan aplikasi AI. Anda perlu dapat mengesan dan memahami pemasaan, penggunaan token, gesaan dan kandungan respons untuk panggilan model individu.

Vercel AI SDK kini menyokong pengesanan dengan OpenTelemetry, standard sumber terbuka untuk merekod maklumat telemetri, sebagai ciri percubaan. Berikut ialah contoh bagaimana visualisasi surih kelihatan dengan penyepaduan Vercel Datadog:

Vercel AI SDK

Jejak visualisasi dengan Datadog dan Vercel AI SDK

Anda boleh menganalisis data pengesanan AI SDK dengan penyepaduan kebolehmerhatian Vercel seperti Datadog, Sentry dan Axiom. Sebagai alternatif, anda boleh menggunakan penyedia kebolehmerhatian LLM seperti LangFuse, Braintrust atau LangSmith.

Untuk menggunakan telemetri dengan Vercel AI SDK, anda perlu mengkonfigurasinya untuk aplikasi anda. Kami mengesyorkan menggunakan @vercel/otel . Jika anda menggunakan Next.js dan gunakan pada Vercel, anda boleh menambah instrumentation.ts dengan kod berikut pada projek anda:

import { registerOTel } from '@vercel/otel';

export function register() {
  registerOTel({ serviceName: 'your-project-nameapp' });
}

Oleh kerana ciri pengesanan adalah percubaan, anda perlu ikut serta untuk merekod maklumat menggunakan pilihan eksperimen_telemetri. Anda juga boleh membekalkan ID fungsi untuk mengenal pasti lokasi panggilan serta metadata tambahan yang ingin anda rakam.

const result = await generateText({
  model: anthropic('claude-3-5-sonnet-20240620'),
  prompt: 'Write a short story about a cat.',
  experimental_telemetry: { 
    isEnabled: true,
    functionId: 'my-awesome-function',
    metadata: {
      something: 'custom',
      someOtherThing: 'other-value',
    },
  },
});

Mendayakan ciri akan merekodkan data pengesanan untuk panggilan fungsi anda. Anda boleh mendapatkan butiran lanjut dalam dokumentasi telemetri AI SDK. Jika anda ingin bermula, lihat templat pengesanan AI SDK Next.js kami yang boleh digunakan.

Lampiran Fail Pelbagai Modal

Dalam banyak aplikasi sembang AI, pengguna perlu menghantar lampiran bersama-sama dengan mesej mereka, seperti imej, PDF dan pelbagai fail media. Lampiran ini juga perlu tersedia untuk pratonton bersama mesej untuk dilihat oleh pengguna.

Akibatnya, kami telah menambahkan lampiran_eksperimen pada pengendali handleSubmit() bagi cangkuk useChat() React.

Vercel AI SDK

Menghantar lampiran imej dan teks dengan useChat

Lihat contoh ini dalam tindakan dan gunakan templat.

Terdapat dua cara untuk menghantar lampiran dengan mesej, sama ada dengan menyediakan objek FileList atau senarai URL ke fungsi handleSubmit:

Senarai fail

Dengan menggunakan FileList, anda boleh menghantar berbilang fail sebagai lampiran bersama-sama dengan mesej menggunakan elemen input fail. Cangkuk useChat akan menukarnya secara automatik menjadi URL data dan menghantarnya kepada pembekal AI.

const { input, handleSubmit, handleInputChange } = useChat();
const [files, setFiles] = useState<FileList | undefined>(undefined);
return (
  <form
    onSubmit={(event) => {
      handleSubmit(event, {
        experimental_attachments: files,
      });
    }}
  >
    <input
      type="file"
      onChange={(event) => {
        if (event.target.files) {
          setFiles(event.target.files);
        }
      }}
      multiple
    />
    <input type="text" value={input} onChange={handleInputChange} />
  </form>
);

URL

Anda juga boleh menghantar URL sebagai lampiran bersama-sama dengan mesej. Ini berguna untuk menghantar pautan ke sumber luaran atau kandungan media.

const { input, handleSubmit, handleInputChange } = useChat();
const [attachments] = useState<Attachment[]>([
  {
    name: 'earth.png',
    contentType: 'image/png',
    url: 'https://example.com/earth.png',
  }
]);
return (
  <form
    onSubmit={event => {
      handleSubmit(event, {
        experimental_attachments: attachments,
      });
    }}
  >
    <input type="text" value={input} onChange={handleInputChange} />
  </form>
)

Anda boleh mengetahui lebih lanjut dalam panduan bot sembang berbilang mod kami.

useObject cangkuk

Penjanaan data berstruktur ialah keperluan biasa dalam aplikasi AI, mis. untuk mengekstrak maklumat daripada input bahasa semula jadi. Dengan cangkuk useObject baharu, anda boleh menstrim penjanaan objek berstruktur terus kepada pelanggan. Ciri percubaan ini, tersedia hari ini untuk React, membolehkan anda membuat antara muka dinamik yang menunjukkan objek JSON semasa ia distrim.

Sebagai contoh, bayangkan permohonan yang membolehkan anda memasukkan perbelanjaan anda sebagai teks untuk pembayaran balik. Anda boleh menggunakan AI untuk menukar input teks kepada objek berstruktur dan menstrim perbelanjaan berstruktur kepada pengguna semasa ia diproses:

Vercel AI SDK

Extracting and streaming an expense from plain text with useObject

Here's how you could implement this in a Next.js application. First, define a schema for the expenses. The schema is shared between client and server:

import { z } from 'zod';

export const expenseSchema = z.object({
  expense: z.object({
    category: z
      .string()
      .describe(
        'Category of the expense. Allowed categories: ' +
        'TRAVEL, MEALS, ENTERTAINMENT, OFFICE SUPPLIES, OTHER.',
      ),
    amount: z.number().describe('Amount of the expense in USD.'),
    date: z
      .string()
      .describe('Date of the expense. Format yyyy-mmm-dd, e.g. 1952-Feb-19.'),
    details: z.string().describe('Details of the expense.'),
  }),
});

export type PartialExpense = DeepPartial<typeof expenseSchema>['expense'];
export type Expense = z.infer<typeof expenseSchema>['expense'];

Then, you use streamObject on the server to call the language model and stream an object:

import { anthropic } from '@ai-sdk/anthropic';
import { streamObject } from 'ai';
import { expenseSchema } from './schema';

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
  const { expense }: { expense: string } = await req.json();
  const result = await streamObject({
    model: anthropic('claude-3-5-sonnet-20240620'),
    system:
      'You categorize expenses into one of the following categories: ' +
      'TRAVEL, MEALS, ENTERTAINMENT, OFFICE SUPPLIES, OTHER.' +
      // provide date (including day of week) for reference:
      'The current date is: ' +
      new Date()
        .toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'short',
          day: '2-digit',
          weekday: 'short',
        })
        .replace(/(\w+), (\w+) (\d+), (\d+)/, '$4-$2-$3 ($1)') +
      '. When no date is supplied, use the current date.',
    prompt: `Please categorize the following expense: "${expense}"`,
    schema: expenseSchema,
    onFinish({ object }) {
      // you could save the expense to a database here
    },
  });
  return result.toTextStreamResponse();
}

Finally, you consume the expense stream on a client page. While the expense is streaming, we preview the partial expense, and once the generation is finished, we append it to the list of expenses:

'use client';

import { experimental_useObject as useObject } from 'ai/react';
import {
  Expense,
  expenseSchema,
  PartialExpense,
} from '../api/expense/schema';
import { useState } from 'react';

export default function Page() {
  const [expenses, setExpenses] = useState<Expense[]>([]);
  const { submit, isLoading, object } = useObject({
    api: '/api/expense',
    schema: expenseSchema,
    onFinish({ object }) {
      if (object != null) {
        setExpenses(prev => [object.expense, ...prev]);
      }
    },
  });
  return (
    <div>
      <form onSubmit={e => {
        e.preventDefault();
        const input = e.currentTarget.expense as HTMLInputElement;
        if (input.value.trim()) {
          submit({ expense: input.value });
          e.currentTarget.reset();
        }
      }}
      >
        <input type="text" name="expense" placeholder="Enter expense details"/>
        <button type="submit" disabled={isLoading}>Log expense</button>
      </form>
      {isLoading && object?.expense && (
        <ExpenseView expense={object.expense} />
      )}
      {expenses.map((expense, index) => (
        <ExpenseView key={index} expense={expense} />
      ))}
    </div>
  );
}

The expenses are rendered using an ExpenseView that can handle partial objects with undefined properties with .? and ?? (styling is omitted for illustration purposes):

const ExpenseView = ({ expense }: { expense: PartialExpense | Expense }) => (
  <div>
    <div>{expense?.date ?? ''}</div>
    <div>${expense?.amount?.toFixed(2) ?? ''}</div>
    <div>{expense?.category ?? ''}</p></div>
    <div>{expense?.details ?? ''}</div>
  </div>
);

Check out this example in action and deploy the template.

You can use this approach to create generative user interfaces client-side for many different use cases. You can find more details on how to use it in our object generation documentation.

Additional LLM Settings

Calling language models is at the heart of the Vercel AI SDK. We have listened to your feedback and extended our functions to support the following features:

  • JSON schema support for tools and structured object generation: As an alternative to Zod schemas, you can now use JSON schemas directly with the jsonSchema function. You can supply the type annotations and an optional validation function, giving you more flexibility especially when building applications with dynamic tools and structure generation.
  • Stop sequences: Text sequences that stop generations have been an important feature when working with earlier language models that used raw text prompts. They are still relevant for many use cases, allowing you more control over the end of a text generation. You can now use the stopSequences option to define stop sequences in streamText and generateText.
  • Sending custom headers: Custom headers are important for many use cases, like sending tracing information, enabling beta provider features, and more. You can now send custom headers using the headers option in most AI SDK functions.

With these additional settings, you have more control and flexibility when working with language models in the Vercel AI SDK.

Conclusion

With new features like OpenTelemetry support, useObject, and support for attachments with useChat, it’s never been a better time to start building AI applications.

  • Start a new AI project: Ready to build something new? Check out our multi-modal chatbot guide.
  • Explore our templates: Visit our Template Gallery to see the AI SDK in action and get inspired for your next project.
  • Join the community: Let us know what you’re building with the AI SDK in our GitHub Discussions.

We can't wait to see what you'll build next with Vercel AI SDK 3.3!

Contributors

Vercel AI SDK 3.3 is the result of the combined work of our core team at Vercel and many community contributors.

Special thanks for contributing merged pull requests:

gclark-eightfold, dynamicwebpaige, Und3rf10w, elitan, jon-spaeth, jeasonstudio, InfiniteCodeMonkeys, ruflair, MrMaina100, AntzyMo, samuelint, ian-pascoe, PawelKonie99, BrianHung, Ouvill, gmickel, developaul, elguarir, Kunoacc, florianheysen, rajuAhmed1705, suemor233, eden-chan, DraganAleksic99, karl-richter, rishabhbizzle, vladkampov, AaronFriel, theitaliandev, miguelvictor, jferrettiboke, dhruvvbhavsar, lmcgartland, PikiLee

Your feedback and contributions are invaluable as we continue to evolve the SDK.

Atas ialah kandungan terperinci Vercel AI SDK. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Memahami Kod Bersih: Fungsi ⚡Artikel seterusnya:Memahami Kod Bersih: Fungsi ⚡