AI API calls - Reading-Advantage-Thailand/reading-advantage GitHub Wiki

Introduction to Vercel AI SDK / บทนำเกี่ยวกับ Vercel AI SDK

English

The Vercel AI SDK is a powerful tool that allows developers to easily integrate Large Language Models (LLMs) into their applications. With the recent updates, it now supports OpenAI's Structured Outputs feature, providing even more reliability and type safety in AI-generated responses.

Key Features:

  1. GenerateObject and StreamObject: These functions, used with Zod schemas and Structured Outputs, ensure type-safe and schema-adherent responses from AI models.

  2. Structured Outputs: This feature guarantees that the model's output adheres to your specified JSON schema, eliminating issues like missing required keys or invalid enum values.

  3. Type Safety: No need for additional validation or retries due to incorrectly formatted responses.

  4. Explicit Refusals: Safety-based model refusals are now programmatically detectable.

  5. Simplified Prompting: Achieve consistent formatting without the need for strongly worded prompts.

Best Practices:

  • By default, use GenerateObject or StreamObject with Zod schemas and set structuredOutputs: true for all AI API calls.
  • Only use unstructured data for specific cases like chatbots where free-form text is necessary.

Example Usage:

const { object } = await generateObject({
  model: openai('gpt-4o-2024-08-06', {
    structuredOutputs: true,
  }),
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(
        z.object({
          name: z.string(),
          amount: z.string(),
        }),
      ),
      steps: z.array(z.string()),
    }),
  }),
  prompt: 'Generate a lasagna recipe.',
});

This approach ensures that your AI-generated content is reliable, type-safe, and adheres to your specified structure, making it easier to build robust AI-powered applications.

ภาษาไทย

Vercel AI SDK เป็นเครื่องมือที่ทรงพลังที่ช่วยให้นักพัฒนาสามารถผสานรวมโมเดลภาษาขนาดใหญ่ (LLMs) เข้ากับแอปพลิเคชันของตนได้อย่างง่ายดาย ด้วยการอัปเดตล่าสุด ตอนนี้รองรับฟีเจอร์ Structured Outputs ของ OpenAI ซึ่งช่วยเพิ่มความน่าเชื่อถือและความปลอดภัยของประเภทข้อมูลในการตอบสนองที่สร้างโดย AI

คุณสมบัติหลัก:

  1. GenerateObject และ StreamObject: ฟังก์ชันเหล่านี้ใช้ร่วมกับ Zod schemas และ Structured Outputs เพื่อรับประกันการตอบสนองที่ปลอดภัยด้านประเภทข้อมูลและสอดคล้องกับสคีมาที่กำหนดจากโมเดล AI

  2. Structured Outputs: ฟีเจอร์นี้รับประกันว่าผลลัพธ์ของโมเดลจะเป็นไปตามสคีมา JSON ที่คุณกำหนด ช่วยขจัดปัญหาเช่น คีย์ที่จำเป็นหายไปหรือค่า enum ที่ไม่ถูกต้อง

  3. ความปลอดภัยของประเภทข้อมูล: ไม่จำเป็นต้องตรวจสอบความถูกต้องเพิ่มเติมหรือลองใหม่เนื่องจากการตอบสนองที่มีรูปแบบไม่ถูกต้อง

  4. การปฏิเสธที่ชัดเจน: การปฏิเสธของโมเดลตามหลักความปลอดภัยสามารถตรวจจับได้ด้วยโปรแกรม

  5. การกำหนดคำสั่งที่ง่ายขึ้น: ได้รูปแบบที่สอดคล้องกันโดยไม่จำเป็นต้องใช้คำสั่งที่เข้มงวด

แนวทางปฏิบัติที่ดีที่สุด:

  • โดยค่าเริ่มต้น ใช้ GenerateObject หรือ StreamObject กับ Zod schemas และตั้งค่า structuredOutputs: true สำหรับการเรียก AI API ทั้งหมด
  • ใช้ข้อมูลที่ไม่มีโครงสร้างเฉพาะในกรณีพิเศษ เช่น แชทบอทที่ต้องการข้อความแบบอิสระ

ตัวอย่างการใช้งาน:

const { object } = await generateObject({
  model: openai('gpt-4o-2024-08-06', {
    structuredOutputs: true,
  }),
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(
        z.object({
          name: z.string(),
          amount: z.string(),
        }),
      ),
      steps: z.array(z.string()),
    }),
  }),
  prompt: 'สร้างสูตรอาหารลาซานญ่า',
});

วิธีการนี้ช่วยให้มั่นใจได้ว่าเนื้อหาที่สร้างโดย AI ของคุณมีความน่าเชื่อถือ ปลอดภัยด้านประเภทข้อมูล และเป็นไปตามโครงสร้างที่คุณกำหนด ทำให้การสร้างแอปพลิเคชันที่ขับเคลื่อนด้วย AI ที่แข็งแกร่งเป็นเรื่องง่ายขึ้น

Vercel AI SDK: Additional Options and Features / Vercel AI SDK: ตัวเลือกและคุณสมบัติเพิ่มเติม

English

In addition to generateObject and streamObject, the Vercel AI SDK offers several other powerful functions and features. Here's an overview of these additional options:

1. generateText

The generateText function is used for generating text content and invoking tools. It's suitable for non-interactive tasks such as writing emails or summarizing web pages.

Example usage:

const { text } = await generateText({
  model: openai("gpt-4"),
  prompt: "Summarize the main points of climate change.",
});

2. streamText

streamText is used for streaming text content and invoking tools. It's ideal for interactive use cases such as chatbots and real-time content streaming.

Example usage:

const stream = await streamText({
  model: openai("gpt-4"),
  prompt: "Tell me a story about a brave knight.",
});

for await (const chunk of stream) {
  console.log(chunk);
}

3. Function Calling

Vercel AI SDK supports function calling, which allows the model to interact with external tools or APIs.

Example usage:

const { text, functionCalls } = await generateText({
  model: openai("gpt-4"),
  prompt: "What's the weather like in New York?",
  functions: [
    {
      name: "get_weather",
      description: "Get the current weather in a given location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. San Francisco, CA",
          },
        },
        required: ["location"],
      },
    },
  ],
});

4. Model Providers

The SDK supports multiple AI model providers, including OpenAI, Anthropic, and Cohere. You can easily switch between providers:

import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";
import { cohere } from "@ai-sdk/cohere";

// Using OpenAI
const openaiResult = await generateText({
  model: openai("gpt-4"),
  prompt: "Hello, world!",
});

// Using Anthropic
const anthropicResult = await generateText({
  model: anthropic("claude-2"),
  prompt: "Hello, world!",
});

// Using Cohere
const cohereResult = await generateText({
  model: cohere("command"),
  prompt: "Hello, world!",
});

5. Error Handling

The SDK provides robust error handling capabilities. You can catch and handle various types of errors that may occur during API calls.

Example:

try {
  const result = await generateText({
    model: openai("gpt-4"),
    prompt: "Generate a complex response",
  });
} catch (error) {
  if (error instanceof OpenAIError) {
    console.error("OpenAI API error:", error.message);
  } else {
    console.error("Unexpected error:", error);
  }
}

These additional options and features make the Vercel AI SDK a versatile tool for integrating AI capabilities into your applications, offering flexibility in how you generate and process AI-powered content.

ภาษาไทย

นอกเหนือจาก generateObject และ streamObject แล้ว Vercel AI SDK ยังมีฟังก์ชันและคุณสมบัติที่ทรงพลังอื่นๆ อีกมากมาย ต่อไปนี้คือภาพรวมของตัวเลือกเพิ่มเติมเหล่านี้:

1. generateText

ฟังก์ชัน generateText ใช้สำหรับสร้างเนื้อหาข้อความและเรียกใช้เครื่องมือ เหมาะสำหรับงานที่ไม่ต้องการการโต้ตอบ เช่น การเขียนอีเมลหรือการสรุปหน้าเว็บ

ตัวอย่างการใช้งาน:

const { text } = await generateText({
  model: openai("gpt-4"),
  prompt: "สรุปประเด็นหลักของการเปลี่ยนแปลงสภาพภูมิอากาศ",
});

2. streamText

streamText ใช้สำหรับสตรีมเนื้อหาข้อความและเรียกใช้เครื่องมือ เหมาะสำหรับกรณีการใช้งานแบบโต้ตอบ เช่น แชทบอทและการสตรีมเนื้อหาแบบเรียลไทม์

ตัวอย่างการใช้งาน:

const stream = await streamText({
  model: openai("gpt-4"),
  prompt: "เล่านิทานเกี่ยวกับอัศวินผู้กล้าหาญ",
});

for await (const chunk of stream) {
  console.log(chunk);
}

3. การเรียกใช้ฟังก์ชัน (Function Calling)

Vercel AI SDK รองรับการเรียกใช้ฟังก์ชัน ซึ่งช่วยให้โมเดลสามารถโต้ตอบกับเครื่องมือภายนอกหรือ API ได้

ตัวอย่างการใช้งาน:

const { text, functionCalls } = await generateText({
  model: openai("gpt-4"),
  prompt: "สภาพอากาศในนิวยอร์กเป็นอย่างไร?",
  functions: [
    {
      name: "get_weather",
      description: "รับข้อมูลสภาพอากาศปัจจุบันในสถานที่ที่กำหนด",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "ชื่อเมืองและรัฐ เช่น San Francisco, CA",
          },
        },
        required: ["location"],
      },
    },
  ],
});

4. ผู้ให้บริการโมเดล

SDK รองรับผู้ให้บริการโมเดล AI หลายราย รวมถึง OpenAI, Anthropic และ Cohere คุณสามารถสลับระหว่างผู้ให้บริการได้อย่างง่ายดาย:

import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";
import { cohere } from "@ai-sdk/cohere";

// ใช้ OpenAI
const openaiResult = await generateText({
  model: openai("gpt-4"),
  prompt: "สวัสดีชาวโลก!",
});

// ใช้ Anthropic
const anthropicResult = await generateText({
  model: anthropic("claude-2"),
  prompt: "สวัสดีชาวโลก!",
});

// ใช้ Cohere
const cohereResult = await generateText({
  model: cohere("command"),
  prompt: "สวัสดีชาวโลก!",
});

5. การจัดการข้อผิดพลาด

SDK มีความสามารถในการจัดการข้อผิดพลาดที่แข็งแกร่ง คุณสามารถจับและจัดการกับข้อผิดพลาดประเภทต่างๆ ที่อาจเกิดขึ้นระหว่างการเรียกใช้ API

ตัวอย่าง:

try {
  const result = await generateText({
    model: openai("gpt-4"),
    prompt: "สร้างการตอบสนองที่ซับซ้อน",
  });
} catch (error) {
  if (error instanceof OpenAIError) {
    console.error("ข้อผิดพลาด OpenAI API:", error.message);
  } else {
    console.error("ข้อผิดพลาดที่ไม่คาดคิด:", error);
  }
}

ตัวเลือกและคุณสมบัติเพิ่มเติมเหล่านี้ทำให้ Vercel AI SDK เป็นเครื่องมือที่หลากหลายสำหรับการผสานความสามารถของ AI เข้ากับแอปพลิเคชันของคุณ โดยมอบความยืดหยุ่นในการสร้างและประมวลผลเนื้อหาที่ขับเคลื่อนด้วย AI

⚠️ **GitHub.com Fallback** ⚠️