커스텀 OpenAI 호환 프로바이더 작성
커스텀 OpenAI 호환 프로바이더 작성
AI SDK의 OpenAI 호환 프로바이더 패키지를 기반으로 자체 프로바이더 패키지를 만들어 npm에 배포하면, 사용자들이 프로바이더 모델을 쉽게 쓰고 변경사항도 따라잡을 수 있습니다. 타입 세이프하게 createExample 팩토리와 기본 인스턴스 example을 노출해 다른 AI SDK 프로바이더와 동일한 사용성을 제공합니다.
출처: 공식문서
본문
파일 구조
packages/example/
├── src/
│ ├── example-chat-settings.ts # Chat model types and settings
│ ├── example-completion-settings.ts # Completion model types and settings
│ ├── example-embedding-settings.ts # Embedding model types and settings
│ ├── example-image-settings.ts # Image model types and settings
│ ├── example-provider.ts # Main provider implementation
│ ├── example-provider.test.ts # Provider tests
│ └── index.ts # Public exports
├── package.json
├── tsconfig.json
├── tsup.config.ts # Build configuration
└── README.md
주요 파일
example-chat-settings.ts — 채팅 모델 ID와 설정 정의:
export type ExampleChatModelId =
| 'example/chat-model-1'
| 'example/chat-model-2'
| (string & {});
example-provider.ts — 핵심 프로바이더 구현. OpenAI 호환 클래스를 감싸고 공통 설정(provider, URL, headers, fetch)을 재사용:
import { LanguageModelV4, EmbeddingModelV4 } from '@ai-sdk/provider';
import {
OpenAICompatibleChatLanguageModel,
OpenAICompatibleCompletionLanguageModel,
OpenAICompatibleEmbeddingModel,
OpenAICompatibleImageModel,
} from '@ai-sdk/openai-compatible';
import {
FetchFunction,
loadApiKey,
withoutTrailingSlash,
} from '@ai-sdk/provider-utils';
export function createExample(
options: ExampleProviderSettings = {},
): ExampleProvider {
const baseURL = withoutTrailingSlash(
options.baseURL ?? 'https://api.example.com/v1',
);
const getHeaders = () => ({
Authorization: `Bearer ${loadApiKey({
apiKey: options.apiKey,
environmentVariableName: 'EXAMPLE_API_KEY',
description: 'Example API key',
})}`,
...options.headers,
});
// ... chat/completion/embedding/image 모델 팩토리 구성
return provider;
}
// Export default instance
export const example = createExample();
index.ts — 공개 export:
export { createExample, example } from './example-provider';
export type {
ExampleProvider,
ExampleProviderSettings,
} from './example-provider';
package.json — 핵심 의존성: @ai-sdk/openai-compatible, @ai-sdk/provider, @ai-sdk/provider-utils.
또한 프로바이더 설정 인터페이스 ExampleProviderSettings(apiKey, baseURL, headers, queryParams, fetch)와 ExampleProvider 인터페이스(호출 가능 함수 + chatModel·completionModel·embeddingModel·imageModel 팩토리)를 정의합니다.
사용
배포 후 사용자는 다음과 같이 사용합니다:
import { example } from '@company-name/example';
import { generateText } from 'ai';
const { text } = await generateText({
model: example('example/chat-model-1'),
prompt: 'Hello, how are you?',
});
내부 API
프로바이더 개발 중 @ai-sdk/openai-compatible/internal 패키지의 내부 API(예: convertToOpenAICompatibleChatMessages)를 사용할 수 있습니다. 최신 export 목록은 AI SDK GitHub 저장소를 참고하세요.
더 알아보기
- OpenAI 호환 프로바이더 — 기본 설정과 인스턴스 생성
- 커스텀 프로바이더 작성 (Language Model Specification) — V4 스펙 기반 자체 프로바이더
- AI SDK Core —
generateText·streamText