Chuyển đến nội dung chính

Tổng quan

Vercel AI SDK là một bộ công cụ TypeScript để xây dựng các ứng dụng streaming hỗ trợ AI với React, Next.js, Vue, Svelte và nhiều nền tảng khác. LemonData hoạt động mượt mà thông qua provider tương thích với OpenAI.

Cài đặt

npm install ai @ai-sdk/openai

Cấu hình cơ bản

import { createOpenAI } from '@ai-sdk/openai';

const lemondata = createOpenAI({
  apiKey: 'sk-your-lemondata-key',
  baseURL: 'https://api.lemondata.cc/v1',
});

Tạo văn bản

import { generateText } from 'ai';

const { text } = await generateText({
  model: lemondata('gpt-4o'),
  prompt: 'What is LemonData?',
});

console.log(text);

Streaming văn bản

import { streamText } from 'ai';

const result = await streamText({
  model: lemondata('gpt-4o'),
  prompt: 'Write a poem about AI.',
});

for await (const textPart of result.textStream) {
  process.stdout.write(textPart);
}

Tin nhắn Chat

import { generateText } from 'ai';

const { text } = await generateText({
  model: lemondata('gpt-4o'),
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What is the capital of France?' },
  ],
});

Sử dụng các Model khác nhau

// OpenAI GPT-4o
const gpt4Response = await generateText({
  model: lemondata('gpt-4o'),
  prompt: 'Hello!',
});

// Anthropic Claude
const claudeResponse = await generateText({
  model: lemondata('claude-sonnet-4-5'),
  prompt: 'Hello!',
});

// Google Gemini
const geminiResponse = await generateText({
  model: lemondata('gemini-2.5-flash'),
  prompt: 'Hello!',
});

// DeepSeek
const deepseekResponse = await generateText({
  model: lemondata('deepseek-r1'),
  prompt: 'Hello!',
});

Next.js API Route

// app/api/chat/route.ts
import { createOpenAI } from '@ai-sdk/openai';
import { streamText } from 'ai';

const lemondata = createOpenAI({
  apiKey: process.env.LEMONDATA_API_KEY,
  baseURL: 'https://api.lemondata.cc/v1',
});

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

  const result = streamText({
    model: lemondata('gpt-4o'),
    messages,
  });

  return result.toDataStreamResponse();
}

React Chat Component

'use client';

import { useChat } from 'ai/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: '/api/chat',
  });

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

      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

Tool Calling

import { generateText, tool } from 'ai';
import { z } from 'zod';

const { text, toolCalls } = await generateText({
  model: lemondata('gpt-4o'),
  tools: {
    weather: tool({
      description: 'Get the weather in a location',
      parameters: z.object({
        location: z.string().describe('The location to get weather for'),
      }),
      execute: async ({ location }) => {
        return { temperature: 72, condition: 'sunny' };
      },
    }),
  },
  prompt: 'What is the weather in San Francisco?',
});

Kết quả có cấu trúc

import { generateObject } from 'ai';
import { z } from 'zod';

const { object } = await generateObject({
  model: lemondata('gpt-4o'),
  schema: z.object({
    name: z.string(),
    age: z.number(),
    email: z.string().email(),
  }),
  prompt: 'Generate a fake user profile.',
});

console.log(object);

Biến môi trường

# .env.local
LEMONDATA_API_KEY=sk-your-lemondata-key
const lemondata = createOpenAI({
  apiKey: process.env.LEMONDATA_API_KEY,
  baseURL: 'https://api.lemondata.cc/v1',
});

Thực hành tốt nhất

Luôn sử dụng streaming cho các ứng dụng chat để cung cấp phản hồi theo thời gian thực.
Triển khai các error boundary phù hợp trong các component React.
Không bao giờ để lộ API key trong mã nguồn phía client. Luôn sử dụng các API route phía server.