메인 콘텐츠로 건너뛰기
Vercel AI SDK는 Next.js, React, Svelte, Vue 앱에서 AI 기능을 만들 때 가장 인기 있는 방법입니다. Venice는 OpenAI 호환 공급자로 즉시 동작합니다.

설정

npm install ai @ai-sdk/openai

공급자 구성

OpenAI 호환 어댑터로 Venice 공급자를 생성하세요:
// lib/venice.ts
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({
  apiKey: process.env.VENICE_API_KEY!,
  baseURL: 'https://api.venice.ai/api/v1',
});

// Venice의 chat completions endpoint와 호환되도록 .chat() 사용
export const venice = (modelId: string) => openai.chat(modelId);
.chat()을 사용하면 요청이 Venice의 /chat/completions endpoint로 전달됩니다. 기본 openai('model') 문법은 Venice가 아직 지원하지 않는 더 새로운 OpenAI endpoint를 사용할 수 있습니다.

스트리밍 채팅 (Next.js App Router)

API 라우트

// app/api/chat/route.ts
import { streamText } from 'ai';
import { venice } from '@/lib/venice';

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

  const result = streamText({
    model: venice('venice-uncensored'),
    system: 'You are a helpful, privacy-respecting AI assistant.',
    messages,
  });

  return result.toDataStreamResponse();
}

React 컴포넌트

// app/page.tsx
'use client';

import { useChat } from '@ai-sdk/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();

  return (
    <div className="max-w-2xl mx-auto p-4">
      <div className="space-y-4 mb-4">
        {messages.map((m) => (
          <div key={m.id} className={m.role === 'user' ? 'text-right' : 'text-left'}>
            <span className="font-bold">{m.role === 'user' ? 'You' : 'Venice'}:</span>
            <p className="whitespace-pre-wrap">{m.content}</p>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Ask anything..."
          className="flex-1 border rounded px-3 py-2"
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading} className="bg-red-600 text-white px-4 py-2 rounded">
          Send
        </button>
      </form>
    </div>
  );
}

텍스트 생성(비스트리밍)

import { generateText } from 'ai';
import { venice } from '@/lib/venice';

const { text } = await generateText({
  model: venice('zai-org-glm-5-1'),
  prompt: 'Explain zero-knowledge proofs in simple terms.',
});

console.log(text);

구조화된 출력

import { generateObject } from 'ai';
import { venice } from '@/lib/venice';
import { z } from 'zod';

const { object } = await generateObject({
  model: venice('venice-uncensored'),
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(z.string()),
      steps: z.array(z.string()),
      prepTimeMinutes: z.number(),
    }),
  }),
  prompt: 'Generate a recipe for chocolate chip cookies.',
});

console.log(object.recipe.name);
console.log(`Prep time: ${object.recipe.prepTimeMinutes} minutes`);

도구 호출(Tool Calling)

import { streamText, tool } from 'ai';
import { venice } from '@/lib/venice';
import { z } from 'zod';

const result = streamText({
  model: venice('zai-org-glm-5-1'),
  messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],
  tools: {
    getWeather: tool({
      description: 'Get current weather for a location',
      parameters: z.object({
        location: z.string().describe('City name'),
      }),
      execute: async ({ location }) => {
        // 여기에 weather API 호출
        return { temperature: 22, condition: 'Sunny', location };
      },
    }),
  },
});

for await (const part of result.fullStream) {
  if (part.type === 'text-delta') {
    process.stdout.write(part.textDelta);
  } else if (part.type === 'tool-result') {
    console.log('Tool result:', part.result);
  }
}

이미지 생성

Venice 이미지 생성은 AI SDK와 별개로 직접 호출할 수 있습니다:
// app/api/image/route.ts
export async function POST(req: Request) {
  const { prompt } = await req.json();

  const response = await fetch('https://api.venice.ai/api/v1/image/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.VENICE_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'qwen-image',
      prompt,
      width: 1024,
      height: 1024,
    }),
  });

  const data = await response.json();
  return Response.json({ image: data.images[0] });
}

멀티 모델 채팅(모델 선택기)

사용자가 Venice 모델 중에서 선택할 수 있게 하세요:
// app/api/chat/route.ts
import { streamText } from 'ai';
import { venice } from '@/lib/venice';

const ALLOWED_MODELS = [
  'venice-uncensored',
  'zai-org-glm-5-1',
  'qwen3-vl-235b-a22b',
  'qwen3-5-9b',
];

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

  if (!ALLOWED_MODELS.includes(modelId)) {
    return new Response('Invalid model', { status: 400 });
  }

  const result = streamText({
    model: venice(modelId),
    messages,
  });

  return result.toDataStreamResponse();
}
// 모델 선택기가 있는 클라이언트 컴포넌트
'use client';

import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

const MODELS = [
  { id: 'venice-uncensored', name: 'Venice Uncensored', desc: 'Fast & uncensored' },
  { id: 'zai-org-glm-5-1', name: 'GLM 5.1', desc: 'Most intelligent (private)' },
  { id: 'qwen3-vl-235b-a22b', name: 'Qwen Vision', desc: 'Advanced vision + text' },
  { id: 'qwen3-5-9b', name: 'Qwen 3.5 9B', desc: 'Fastest & cheapest' },
];

export default function Chat() {
  const [model, setModel] = useState('venice-uncensored');
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    body: { model },
  });

  return (
    <div>
      <select value={model} onChange={(e) => setModel(e.target.value)}>
        {MODELS.map((m) => (
          <option key={m.id} value={m.id}>{m.name}{m.desc}</option>
        ))}
      </select>
      {/* ... chat UI ... */}
    </div>
  );
}

웹 검색 통합

웹 검색을 위해 Venice 파라미터를 전달하세요:
import { streamText } from 'ai';
import { venice } from '@/lib/venice';

const result = streamText({
  model: venice('venice-uncensored'),
  messages: [{ role: 'user', content: 'What happened in AI news today?' }],
  // Venice 전용 파라미터
  experimental_providerMetadata: {
    venice_parameters: {
      enable_web_search: 'auto',
    },
  },
});
experimental_providerMetadata가 전달되지 않는 경우, 커스텀 fetch 래퍼를 사용하거나 웹 검색 기능을 위해 Venice API를 직접 호출할 수 있습니다.

임베딩(Embeddings)

임베딩에는 공급자에서 직접 textEmbeddingModel()을 사용하세요:
import { embed, embedMany } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({
  apiKey: process.env.VENICE_API_KEY!,
  baseURL: 'https://api.venice.ai/api/v1',
});

// 단일 임베딩
const { embedding } = await embed({
  model: openai.textEmbeddingModel('text-embedding-bge-m3'),
  value: 'Privacy-first AI infrastructure',
});

// 배치 임베딩
const { embeddings } = await embedMany({
  model: openai.textEmbeddingModel('text-embedding-bge-m3'),
  values: [
    'Venice AI provides private inference.',
    'Zero data retention guaranteed.',
    'OpenAI SDK compatible.',
  ],
});

환경 변수

# .env.local
VENICE_API_KEY=your-venice-api-key

권장 모델

Use CaseModelWhy
채팅 앱venice-uncensored빠르고, 저렴하고, 필터링 없음
복잡한 작업zai-org-glm-5-1프라이빗 플래그십 추론
비전 앱qwen3-vl-235b-a22b고급 이미지 이해
대량 처리qwen3-5-9b100만 input 토큰당 0.10,output0.10, output 0.15로 가장 저렴
도구 호출zai-org-glm-5-1신뢰성 있는 함수 호출

Vercel AI SDK 문서

공식 Vercel AI SDK 문서

Venice 모델

모든 Venice 모델 둘러보기