SDK 가이드
Go
Go의 공식 openai-go 라이브러리에서 option.WithBaseURL로 api14를 지정하는 방법입니다. 채팅, 스트리밍, 도구 호출, 구조화된 출력, 임베딩, 타임아웃과 재시도 예제를 제공합니다. 이미지 입력과 추가 파라미터도 다룹니다.
api14에서 공식 openai-go 라이브러리를 사용하세요. option.WithBaseURL이 api14를 가리키게 하고, 아무 모델 ID(예: openai/gpt-5-mini)를 모델로 전달합니다.
설치
go get github.com/openai/openai-go
export API14_API_KEY="sk-api14-..."
설정
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
var client = openai.NewClient(
option.WithBaseURL("https://api14.com/api/v1/"),
option.WithAPIKey(os.Getenv("API14_API_KEY")),
)
var ctx = context.Background()
// 아래 스니펫은 func main() 안에서 실행됩니다.
옵션 없이 openai.NewClient()를 호출하면 OPENAI_BASE_URL과 OPENAI_API_KEY를 읽으므로, 환경 변수로도 설정할 수 있습니다.
export OPENAI_BASE_URL="https://api14.com/api/v1/"
export OPENAI_API_KEY="sk-api14-..."
채팅
resp, err := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
Model: "openai/gpt-5-mini",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Explain vector databases in two sentences."),
},
})
if err != nil {
panic(err)
}
fmt.Println(resp.Choices[0].Message.Content)
스트리밍
stream := client.Chat.Completions.NewStreaming(ctx, openai.ChatCompletionNewParams{
Model: "anthropic/claude-sonnet-4.5",
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Write a haiku about APIs.")},
})
for stream.Next() {
chunk := stream.Current()
if len(chunk.Choices) > 0 {
fmt.Print(chunk.Choices[0].Delta.Content)
}
}
if err := stream.Err(); err != nil {
panic(err)
}
스트리밍을 참고하세요.
도구 호출
params := openai.ChatCompletionNewParams{
Model: "openai/gpt-5-mini",
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("What's the weather in Istanbul?")},
Tools: []openai.ChatCompletionToolParam{{
Function: openai.FunctionDefinitionParam{
Name: "get_weather",
Description: openai.String("Current weather for a city"),
Parameters: openai.FunctionParameters{
"type": "object",
"properties": map[string]any{"city": map[string]string{"type": "string"}},
"required": []string{"city"},
},
},
}},
}
for {
resp, err := client.Chat.Completions.New(ctx, params)
if err != nil {
panic(err)
}
msg := resp.Choices[0].Message
if len(msg.ToolCalls) == 0 {
fmt.Println(msg.Content)
break
}
params.Messages = append(params.Messages, msg.ToParam())
for _, call := range msg.ToolCalls {
var args struct{ City string }
json.Unmarshal([]byte(call.Function.Arguments), &args)
params.Messages = append(params.Messages, openai.ToolMessage(getWeather(args.City), call.ID))
}
}
getWeather는 문자열을 반환하는 직접 작성한 함수입니다. 도구 호출을 참고하세요.
구조화된 출력
schema := map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]string{"type": "string"},
"born": map[string]string{"type": "integer"},
},
"required": []string{"name", "born"},
"additionalProperties": false,
}
resp, err := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
Model: "openai/gpt-5-mini",
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Extract: Ada Lovelace, born 1815.")},
ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{
OfJSONSchema: &openai.ResponseFormatJSONSchemaParam{
JSONSchema: openai.ResponseFormatJSONSchemaJSONSchemaParam{
Name: "person", Schema: schema, Strict: openai.Bool(true),
},
},
},
})
var person struct {
Name string `json:"name"`
Born int `json:"born"`
}
_ = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &person)
구조화된 출력을 참고하세요.
이미지 입력
resp, err := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
Model: "google/gemini-2.5-flash",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage([]openai.ChatCompletionContentPartUnionParam{
openai.TextContentPart("What is in this picture?"),
openai.ImageContentPart(openai.ChatCompletionContentPartImageImageURLParam{
URL: "https://example.com/photo.jpg", // 또는 data:image/png;base64,... URL
}),
}),
},
})
비전 및 파일을 참고하세요.
추가 파라미터
SDK에 타입이 없는 필드(reasoning, provider, models)는 option.WithJSONSet으로 추가합니다.
resp, err := client.Chat.Completions.New(ctx, params,
option.WithJSONSet("reasoning", map[string]any{"effort": "high"}),
option.WithJSONSet("provider", map[string]any{"sort": "throughput"}),
)
임베딩
emb, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{
Model: "openai/text-embedding-3-small",
Input: openai.EmbeddingNewParamsInputUnion{OfArrayOfStrings: []string{"The quick brown fox", "Lorem ipsum"}},
})
if err == nil {
fmt.Println(len(emb.Data[0].Embedding))
}
오류
API 오류는 *openai.Error로 반환되며, HTTP 상태, 머신용 Code, 원시 응답이 들어 있습니다.
import "errors"
var apiErr *openai.Error
if errors.As(err, &apiErr) {
switch apiErr.StatusCode {
case 402: // insufficient_balance
fmt.Println("Balance too low, add funds:", apiErr.Code)
case 429: // rate_limited or daily_limit_reached
fmt.Println("Retry after", apiErr.Response.Header.Get("Retry-After"), "s:", apiErr.Code)
}
}
오류를 참고하세요.
타임아웃과 재시도
클라이언트는 기본적으로 408, 409, 429, 5xx를 지수 백오프로 두 번 재시도합니다. 재시도 횟수와 시도별 타임아웃은 클라이언트 또는 요청 옵션으로 설정하고, 전체 호출은 컨텍스트로 제한하세요.
client := openai.NewClient(
option.WithBaseURL("https://api14.com/api/v1/"),
option.WithAPIKey(os.Getenv("API14_API_KEY")),
option.WithMaxRetries(4),
option.WithRequestTimeout(60*time.Second), // 시도별
)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) // 모든 시도 합계
defer cancel()
daily_limit_reached나 insufficient_balance는 재시도해도 소용없습니다. 속도 제한을 참고하세요.
모든 기능
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api14.com/api/v1",
apiKey: process.env.API14_API_KEY,
});
const result = await client.chat.completions.create({
"model": "openai/gpt-5-mini",
"messages": [
{
"role": "user",
"content": "Explain vector databases in two sentences."
}
]
});
console.log(result.choices[0].message.content);