Skip to content

Commit 0e190c7

Browse files
Copilotna-trium-144
andcommitted
Use openai SDK for OpenRouter integration instead of direct fetch
Co-authored-by: na-trium-144 <100704180+na-trium-144@users.noreply.github.com>
1 parent cec9872 commit 0e190c7

File tree

3 files changed

+33
-21
lines changed

3 files changed

+33
-21
lines changed

app/actions/openrouter.ts

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

3+
import OpenAI from "openai";
4+
35
export async function generateContent(
46
prompt: string,
57
systemInstruction?: string
@@ -13,33 +15,20 @@ export async function generateContent(
1315
);
1416
}
1517

16-
const messages: { role: string; content: string }[] = [];
18+
const client = new OpenAI({
19+
apiKey,
20+
baseURL: "https://openrouter.ai/api/v1",
21+
});
22+
23+
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [];
1724
if (systemInstruction) {
1825
messages.push({ role: "system", content: systemInstruction });
1926
}
2027
messages.push({ role: "user", content: prompt });
2128

22-
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
23-
method: "POST",
24-
headers: {
25-
Authorization: `Bearer ${apiKey}`,
26-
"Content-Type": "application/json",
27-
},
28-
body: JSON.stringify({ model, messages }),
29-
});
30-
31-
if (!response.ok) {
32-
const errorText = await response.text();
33-
throw new Error(
34-
`OpenRouter API error: ${response.status} ${response.statusText} - ${errorText}`
35-
);
36-
}
37-
38-
const data = (await response.json()) as {
39-
choices: { message: { content: string } }[];
40-
};
29+
const completion = await client.chat.completions.create({ model, messages });
4130

42-
const text = data.choices[0]?.message?.content;
31+
const text = completion.choices[0]?.message?.content;
4332
if (!text) {
4433
throw new Error("OpenRouterからの応答が空でした");
4534
}

package-lock.json

Lines changed: 22 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"js-yaml": "^4.1.1",
3636
"mocha": "^11.7.4",
3737
"next": "^15.5.11",
38+
"openai": "^6.27.0",
3839
"pg": "^8.16.3",
3940
"prismjs": "^1.30.0",
4041
"react": "^19",

0 commit comments

Comments
 (0)