Skip to content

Commit a259c8b

Browse files
Copilotna-trium-144
andcommitted
Support multiple OpenRouter models with semicolon separator and automatic fallback
Co-authored-by: na-trium-144 <100704180+na-trium-144@users.noreply.github.com>
1 parent 9a28d39 commit a259c8b

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

app/actions/gemini.ts

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"use server";
22

33
import { GoogleGenAI } from "@google/genai";
4-
import OpenAI from "openai";
54

65
export async function generateContent(
76
prompt: string,
@@ -11,23 +10,36 @@ export async function generateContent(
1110
const openRouterModel = process.env.OPENROUTER_MODEL;
1211

1312
if (openRouterApiKey && openRouterModel) {
14-
const client = new OpenAI({
15-
apiKey: openRouterApiKey,
16-
baseURL: "https://openrouter.ai/api/v1",
17-
});
13+
// Support semicolon-separated list of models for automatic fallback via
14+
// OpenRouter's `models` array parameter.
15+
const models = openRouterModel.split(";").map((m) => m.trim()).filter(Boolean);
1816

19-
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [];
17+
const messages: { role: string; content: string }[] = [];
2018
if (systemInstruction) {
2119
messages.push({ role: "system", content: systemInstruction });
2220
}
2321
messages.push({ role: "user", content: prompt });
2422

25-
const completion = await client.chat.completions.create({
26-
model: openRouterModel,
27-
messages,
23+
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
24+
method: "POST",
25+
headers: {
26+
"Content-Type": "application/json",
27+
Authorization: `Bearer ${openRouterApiKey}`,
28+
},
29+
body: JSON.stringify({ models, messages }),
2830
});
2931

30-
const text = completion.choices[0]?.message?.content;
32+
if (!response.ok) {
33+
const body = await response.text();
34+
throw new Error(
35+
`OpenRouter APIエラー: ${response.status} ${response.statusText} - ${body}`
36+
);
37+
}
38+
39+
const data = (await response.json()) as {
40+
choices?: { message?: { content?: string | null } }[];
41+
};
42+
const text = data.choices?.[0]?.message?.content;
3143
if (!text) {
3244
throw new Error("OpenRouterからの応答が空でした");
3345
}

0 commit comments

Comments
 (0)