Skip to content

Commit cec9872

Browse files
Copilotna-trium-144
andcommitted
Add OpenRouter support as fallback to Gemini in chatActions
Co-authored-by: na-trium-144 <100704180+na-trium-144@users.noreply.github.com>
1 parent 1833ebf commit cec9872

File tree

3 files changed

+81
-134
lines changed

3 files changed

+81
-134
lines changed

app/actions/chatActions.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
"use server";
22

33
// import { z } from "zod";
4-
import { generateContent } from "./gemini";
4+
import { generateContent as generateContentGemini } from "./gemini";
5+
import { generateContent as generateContentOpenRouter } from "./openrouter";
56
import { DynamicMarkdownSection } from "../[lang]/[pageId]/pageContent";
67
import { ReplCommand, ReplOutput } from "@my-code/runtime/interface";
78
import { addChat, ChatWithMessages } from "@/lib/chatHistory";
89
import { getPagesList, introSectionId, PagePath, SectionId } from "@/lib/docs";
910

11+
function generateContent(prompt: string, systemInstruction?: string) {
12+
if (process.env.OPENROUTER_API_KEY && process.env.OPENROUTER_MODEL) {
13+
return generateContentOpenRouter(prompt, systemInstruction);
14+
}
15+
return generateContentGemini(prompt, systemInstruction);
16+
}
17+
1018
type ChatResult =
1119
| {
1220
error: string;

app/actions/openrouter.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"use server";
2+
3+
export async function generateContent(
4+
prompt: string,
5+
systemInstruction?: string
6+
): Promise<{ text: string }> {
7+
const apiKey = process.env.OPENROUTER_API_KEY;
8+
const model = process.env.OPENROUTER_MODEL;
9+
10+
if (!apiKey || !model) {
11+
throw new Error(
12+
"OPENROUTER_API_KEY and OPENROUTER_MODEL environment variables must be set"
13+
);
14+
}
15+
16+
const messages: { role: string; content: string }[] = [];
17+
if (systemInstruction) {
18+
messages.push({ role: "system", content: systemInstruction });
19+
}
20+
messages.push({ role: "user", content: prompt });
21+
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+
};
41+
42+
const text = data.choices[0]?.message?.content;
43+
if (!text) {
44+
throw new Error("OpenRouterからの応答が空でした");
45+
}
46+
return { text };
47+
}

0 commit comments

Comments
 (0)