AI ใน Web Development

เพิ่มความสามารถให้แอปด้วย AI — ตั้งแต่ chatbot, text generation ไปจนถึง image processing โดยไม่ต้องสร้าง model เองตั้งแต่ศูนย์


AI ใน Web App ทำงานอย่างไร?

// Web App ไม่ได้รัน AI model โดยตรง — เรียกผ่าน API

User ──▶ Web App ──▶ AI API (OpenAI / Anthropic / Gemini)
                          ↓
User ◀── Web App ◀── AI Response (JSON)

// เหมือนกับการเรียก REST API ทั่วไป
// ต่างกันแค่ response เป็น text ที่ AI สร้างขึ้น


AI API ยอดนิยมสำหรับ Web Developer

OpenAI GPT-4o, DALL-E, Whisper — ecosystem ใหญ่ที่สุด เอกสารครบ

Anthropic Claude — เก่งด้าน reasoning และ long context อ่านเอกสารยาวได้ดี

Google Gemini — multimodal เข้าใจ text, image, video และ audio

Vercel AI SDK abstraction layer รองรับหลาย provider เขียนโค้ดชุดเดียว


ตัวอย่าง — เรียก Anthropic API พื้นฐาน

// ติดตั้ง SDK
// npm install @anthropic-ai/sdk

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

async function generateText(prompt: string): Promise<string> {
  const message = await client.messages.create({
    model: 'claude-opus-4-5',
    max_tokens: 1024,
    messages: [
      { role: 'user', content: prompt }
    ],
  });

  return message.content[0].type === 'text'
    ? message.content[0].text
    : '';
}


ตัวอย่าง — API Route ใน Next.js

// app/api/chat/route.ts
import Anthropic from '@anthropic-ai/sdk';
import { NextRequest, NextResponse } from 'next/server';

const client = new Anthropic();

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

  if (!message) {
    return NextResponse.json({ error: 'Message is required' }, { status: 400 });
  }

  const response = await client.messages.create({
    model: 'claude-opus-4-5',
    max_tokens: 1024,
    system: 'คุณเป็น assistant ที่ช่วยตอบคำถามด้าน programming',
    messages: [{ role: 'user', content: message }],
  });

  const text = response.content[0].type === 'text'
    ? response.content[0].text
    : '';

  return NextResponse.json({ reply: text });
}


ตัวอย่าง — Streaming Response

// Streaming ทำให้ UI แสดงผลทีละคำ ไม่ต้องรอ response ทั้งหมด
// app/api/chat/route.ts

import { anthropic } from '@ai-sdk/anthropic';
import { streamText } from 'ai';

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

  const result = streamText({
    model: anthropic('claude-opus-4-5'),
    system: 'คุณเป็น assistant ที่ช่วยตอบคำถามด้าน programming',
    messages,
  });

  return result.toDataStreamResponse();
}


// Frontend — ใช้ Vercel AI SDK useChat hook
'use client';
import { useChat } from 'ai/react';

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

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          <strong>{m.role === 'user' ? 'คุณ' : 'AI'}:</strong>
          <p>{m.content}</p>
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="พิมพ์ข้อความ..."
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading}>ส่ง</button>
      </form>
    </div>
  );
}


ตัวอย่าง — Structured Output (JSON)

// บอกให้ AI ตอบเป็น JSON โครงสร้างที่กำหนดไว้
async function analyzeCode(code: string) {
  const response = await client.messages.create({
    model: 'claude-opus-4-5',
    max_tokens: 1024,
    system: `วิเคราะห์โค้ดและตอบเป็น JSON รูปแบบนี้เท่านั้น:
{
  "quality": "good" | "bad" | "average",
  "issues": string[],
  "suggestions": string[],
  "score": number (0-100)
}`,
    messages: [{ role: 'user', content: code }],
  });

  const text = response.content[0].type === 'text'
    ? response.content[0].text : '{}';

  return JSON.parse(text);
}


Use Cases ยอดนิยมใน Web App

1. Chatbot และ Customer Support

ตอบคำถามอัตโนมัติ ส่ง context ของ user ไปพร้อมกับ prompt เพื่อตอบได้ตรงประเด็น

2. Text Generation และ Summarization

สรุปบทความ, เขียน description สินค้า, แปลภาษา โดยกำหนด format ผ่าน system prompt

3. Code Assistant

ช่วย review โค้ด, แนะนำ bug fix, generate boilerplate ตาม pattern ของ project

4. Search ด้วย Semantic Understanding

แปลง query เป็น embedding แล้วค้นหาเนื้อหาที่ความหมายใกล้เคียง ไม่ใช่แค่ keyword


Best Practices

ห้าม เก็บ API key ใน client-side code — ต้องผ่าน backend เสมอ

ห้าม ส่ง user input ตรงๆ โดยไม่ validate — ป้องกัน prompt injection

ควร ใช้ streaming สำหรับ response ยาว ทำให้ UX ดีขึ้นมาก

ควร กำหนด max_tokens และ timeout ป้องกัน cost บานปลาย

ควร cache response ที่เหมือนกัน ลด API call และค่าใช้จ่าย