Cookieを使用しています. Cookieとブラウザストレージは、ログイン状態の維持と設定の保存に使われます。許可いただいた場合は、サイトの利用状況も計測します。はいつでも変更できます。詳しくはCookieポリシーをご覧ください。

Go

SDKガイド

Go

公式 openai-go ライブラリで api14 を使う方法です。option.WithBaseURL の設定から、チャット、ストリーミング、ツール呼び出し、構造化出力、画像入力、追加パラメーター、埋め込み、再試行までを Go で解説します。

公式の openai-go ライブラリを api14 で使います。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 または daily_limit_reached
		fmt.Println("Retry after", apiErr.Response.Header.Get("Retry-After"), "s:", apiErr.Code)
	}
}

エラーを参照してください。

タイムアウトと再試行

クライアントは、408、409、429、5xx を指数バックオフでデフォルトで 2 回再試行します。再試行回数と 1 回の試行ごとのタイムアウトをクライアントまたはリクエストのオプションとして設定し、呼び出し全体はコンテキストで制限します。

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), // 1 回の試行あたり
)

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);