Skip to content

Commit f3fdd50

Browse files
authored
Merge pull request #60 from DaleStudy/ai-gateway-binding
feat: call AI Gateway through the Workers AI binding
2 parents 8ea82a6 + d80256c commit f3fdd50

18 files changed

Lines changed: 181 additions & 176 deletions

โ€Ž.github/workflows/deploy.ymlโ€Ž

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,9 @@ jobs:
3131
packageManager: bun
3232
secrets: |
3333
PRIVATE_KEY
34-
AI_GATEWAY_TOKEN
3534
INTERNAL_SECRET
3635
WEBHOOK_SECRET
3736
env:
3837
PRIVATE_KEY: ${{ secrets.APP_PRIVATE_KEY }}
39-
AI_GATEWAY_TOKEN: ${{ secrets.AI_GATEWAY_TOKEN }}
4038
INTERNAL_SECRET: ${{ secrets.INTERNAL_SECRET }}
4139
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}

โ€ŽAGENTS.mdโ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,15 @@ GitHub webhook
7979
| ---------------------- | ----------------------------------------------------------------------------------- |
8080
| `APP_ID`, `WORKER_URL` | `wrangler.jsonc` ์˜ `vars` (๊ณต๊ฐœ ๊ฐ’) |
8181
| `PRIVATE_KEY` | GitHub org secret `APP_PRIVATE_KEY` |
82-
| `AI_GATEWAY_TOKEN` | GitHub org secret `AI_GATEWAY_TOKEN` |
82+
| `AI` | `wrangler.jsonc` ์˜ AI ๋ฐ”์ธ๋”ฉ. ๊ฐ™์€ ๊ณ„์ •์˜ AI Gateway `dalestudy` ๋ฅผ ํ† ํฐ ์—†์ด ๋ถ€๋ฅธ๋‹ค |
8383
| `INTERNAL_SECRET` | GitHub ์ €์žฅ์†Œ secret `INTERNAL_SECRET` |
8484
| `WEBHOOK_SECRET` | GitHub ์ €์žฅ์†Œ secret `WEBHOOK_SECRET`. GitHub App ์›นํ›… ์„ค์ •์˜ secret ๊ณผ ๊ฐ™์€ ๊ฐ’์ด๋‹ค |
8585

8686
GitHub secret ์€ ๋ฐฐํฌํ•  ๋•Œ๋งˆ๋‹ค Worker secret ์œผ๋กœ ๋“ค์–ด๊ฐ€๋ฏ€๋กœ `wrangler secret put` ์œผ๋กœ ๋”ฐ๋กœ ๋ฐ”๊พธ์ง€ ์•Š๋Š”๋‹ค. ๋‹ค์Œ ๋ฐฐํฌ ๋•Œ GitHub ๊ฐ’์œผ๋กœ ๋ฎ์ธ๋‹ค.
8787
๋กœ์ปฌ์—์„œ๋Š” `.dev.vars` ์— ๊ฐ™์€ ์ด๋ฆ„์œผ๋กœ ๋„ฃ๋Š”๋‹ค. `.dev.vars`, `*.pem` ์€ ์ปค๋ฐ‹ํ•˜์ง€ ์•Š๋Š”๋‹ค.
8888

89+
OpenAI ํ‚ค๋Š” Worker ์— ๋‘์ง€ ์•Š๋Š”๋‹ค. AI Gateway `dalestudy` ์˜ Provider Keys(BYOK)์— ์ €์žฅ๋ผ ์žˆ๊ณ , ๊ฒŒ์ดํŠธ์›จ์ด๋Š” BYOK only ๋ผ ํ‚ค๊ฐ€ ์—†์œผ๋ฉด Unified Billing ์œผ๋กœ ๋„˜์–ด๊ฐ€์ง€ ์•Š๊ณ  ์‹คํŒจํ•œ๋‹ค. AI ๋ฐ”์ธ๋”ฉ์€ `wrangler dev` ์—์„œ๋„ ์›๊ฒฉ ๊ฒŒ์ดํŠธ์›จ์ด๋ฅผ ๋ถ€๋ฅด๋ฏ€๋กœ `wrangler login` ์ด dalestudy ๊ณ„์ •์— ๋˜์–ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.
90+
8991
## GitHub App ์„ค์ •
9092

9193
https://github.com/organizations/DaleStudy/settings/apps/dalestudy

โ€Žhandlers/complexity-analysis.jsโ€Ž

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
* - LLM : actualTime / actualSpace / feedback / suggestion / headerLine ๋งŒ ์ฑ…์ž„.
1111
*/
1212

13-
import { aiGatewayHeaders, OPENAI_CHAT_COMPLETIONS_URL } from "../utils/constants.js";
13+
import { createChatCompletion } from "../utils/openai.js";
1414

1515
// โ”€โ”€ ์ƒ์ˆ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1616

@@ -242,35 +242,24 @@ export function composeSolution(modelSol, originalContent) {
242242
};
243243
}
244244

245-
export async function callComplexityAnalysis(fileEntries, gatewayToken) {
245+
export async function callComplexityAnalysis(fileEntries, ai) {
246246
const userPrompt = fileEntries
247247
.map(
248248
(f) =>
249249
`${FILE_DELIMITER} ${f.problemName} ${FILE_DELIMITER}\n\`\`\`\n${addLineNumbers(stripComplexityComments(f.content))}\n\`\`\``
250250
)
251251
.join("\n\n");
252252

253-
const response = await fetch(OPENAI_CHAT_COMPLETIONS_URL, {
254-
method: "POST",
255-
headers: aiGatewayHeaders(gatewayToken),
256-
body: JSON.stringify({
257-
model: "gpt-5-nano",
258-
messages: [
259-
{ role: "system", content: SYSTEM_PROMPT },
260-
{ role: "user", content: userPrompt },
261-
],
262-
response_format: { type: "json_object" },
263-
max_completion_tokens: 5000,
264-
reasoning_effort: "minimal",
265-
}),
253+
const data = await createChatCompletion(ai, {
254+
model: "gpt-5-nano",
255+
messages: [
256+
{ role: "system", content: SYSTEM_PROMPT },
257+
{ role: "user", content: userPrompt },
258+
],
259+
response_format: { type: "json_object" },
260+
max_completion_tokens: 5000,
261+
reasoning_effort: "minimal",
266262
});
267-
268-
if (!response.ok) {
269-
const error = await response.text();
270-
throw new Error(`OpenAI API error: ${error}`);
271-
}
272-
273-
const data = await response.json();
274263
const content = data.choices[0]?.message?.content;
275264
if (!content) throw new Error("Empty response from OpenAI");
276265

โ€Žhandlers/complexity-analysis.test.jsโ€Ž

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
callComplexityAnalysis,
1212
renderComplexitySection,
1313
} from "./complexity-analysis.js";
14+
import { createFakeAi } from "../tests/fakeAi.js";
1415

1516
const PLAIN_SOURCE = "function solution() { return 0; }";
1617

@@ -452,6 +453,8 @@ function solution() {}`;
452453
// โ”€โ”€ callComplexityAnalysis โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
453454

454455
describe("callComplexityAnalysis", () => {
456+
const ai = createFakeAi();
457+
455458
beforeEach(() => {
456459
vi.clearAllMocks();
457460
});
@@ -471,7 +474,7 @@ describe("callComplexityAnalysis", () => {
471474
{ problemName: "valid-parentheses", content: PLAIN_SOURCE },
472475
];
473476

474-
const results = await callComplexityAnalysis(fileEntries, "fake-key");
477+
const results = await callComplexityAnalysis(fileEntries, ai);
475478

476479
expect(results).toHaveLength(2);
477480
expect(results[0].problemName).toBe("two-sum");
@@ -485,7 +488,7 @@ describe("callComplexityAnalysis", () => {
485488
await expect(
486489
callComplexityAnalysis(
487490
[{ problemName: "two-sum", content: PLAIN_SOURCE }],
488-
"fake-key"
491+
ai
489492
)
490493
).rejects.toThrow("OpenAI API error");
491494
});
@@ -498,7 +501,7 @@ describe("callComplexityAnalysis", () => {
498501
await expect(
499502
callComplexityAnalysis(
500503
[{ problemName: "two-sum", content: PLAIN_SOURCE }],
501-
"fake-key"
504+
ai
502505
)
503506
).rejects.toThrow("Empty response from OpenAI");
504507
});
@@ -513,7 +516,7 @@ describe("callComplexityAnalysis", () => {
513516
await expect(
514517
callComplexityAnalysis(
515518
[{ problemName: "two-sum", content: PLAIN_SOURCE }],
516-
"fake-key"
519+
ai
517520
)
518521
).rejects.toThrow("OpenAI returned invalid JSON");
519522
});
@@ -530,7 +533,7 @@ describe("callComplexityAnalysis", () => {
530533
{ problemName: "longest-prefix", content: PLAIN_SOURCE },
531534
];
532535

533-
const results = await callComplexityAnalysis(fileEntries, "fake-key");
536+
const results = await callComplexityAnalysis(fileEntries, ai);
534537

535538
expect(results).toHaveLength(1);
536539
expect(results[0].problemName).toBe("longest-prefix");
@@ -550,32 +553,39 @@ describe("callComplexityAnalysis", () => {
550553
function solution() { return 0; }`;
551554
await callComplexityAnalysis(
552555
[{ problemName: "two-sum", content: source }],
553-
"fake-key"
556+
ai
554557
);
555558

556559
expect(captured).toContain("L1: \nL2: \nL3: function solution()");
557560
expect(captured).not.toContain("TC: O(n)");
558561
expect(captured).not.toContain("SC: O(1)");
559562
});
560563

561-
it("AI Gateway ์ธ์ฆ ํ—ค๋”์™€ ์žฌ์‹œ๋„ ํ—ค๋”๋ฅผ ํ•จ๊ป˜ ๋ณด๋‚ธ๋‹ค", async () => {
562-
let captured = null;
563-
globalThis.fetch = vi.fn().mockImplementation(async (url, opts) => {
564-
captured = opts.headers;
565-
return await makeOpenAIResponse([makeSingleSolutionAnalysis("two-sum")]);
566-
});
564+
it("dalestudy ๊ฒŒ์ดํŠธ์›จ์ด์˜ OpenAI chat/completions ๋กœ ์žฌ์‹œ๋„ ํ—ค๋”์™€ ํ•จ๊ป˜ ๋ณด๋‚ธ๋‹ค", async () => {
565+
globalThis.fetch = vi
566+
.fn()
567+
.mockResolvedValueOnce(
568+
await makeOpenAIResponse([makeSingleSolutionAnalysis("two-sum")])
569+
);
567570

568571
await callComplexityAnalysis(
569572
[{ problemName: "two-sum", content: PLAIN_SOURCE }],
570-
"fake-key"
573+
ai
571574
);
572575

573-
expect(captured).toMatchObject({
574-
"cf-aig-authorization": "Bearer fake-key",
575-
"cf-aig-max-attempts": "3",
576-
"cf-aig-retry-delay": "1000",
577-
"cf-aig-backoff": "exponential",
576+
expect(ai.gateway).toHaveBeenCalledWith("dalestudy");
577+
const request = ai.run.mock.calls[0][0];
578+
expect(request).toMatchObject({
579+
provider: "openai",
580+
endpoint: "chat/completions",
581+
headers: {
582+
"cf-aig-max-attempts": 3,
583+
"cf-aig-retry-delay": 1000,
584+
"cf-aig-backoff": "exponential",
585+
},
578586
});
587+
// ์ธ์ฆ์€ ๋ฐ”์ธ๋”ฉ์ด ํ•˜๋ฏ€๋กœ ๊ฒŒ์ดํŠธ์›จ์ด ํ† ํฐ์„ ์‹ฃ์ง€ ์•Š๋Š”๋‹ค
588+
expect(request.headers).not.toHaveProperty("cf-aig-authorization");
579589
});
580590
});
581591

โ€Žhandlers/internal-dispatch.jsโ€Ž

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ async function handleTagPatterns(payload, appToken, env) {
7272
headSha,
7373
prData,
7474
appToken,
75-
env.AI_GATEWAY_TOKEN
75+
env.AI
7676
);
7777
return corsResponse({ handler: "tag-patterns", result });
7878
}
@@ -85,7 +85,7 @@ async function handleLearningStatus(payload, appToken, env) {
8585
prNumber,
8686
username,
8787
appToken,
88-
env.AI_GATEWAY_TOKEN
88+
env.AI
8989
);
9090
return corsResponse({ handler: "learning-status", result });
9191
}

โ€Žhandlers/internal-dispatch.test.jsโ€Ž

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import { tagPatterns } from "./tag-patterns.js";
1717
import { postLearningStatus } from "./learning-status.js";
1818
import { generateGitHubAppToken } from "../utils/github.js";
1919

20+
const FAKE_AI = { gateway: () => {} };
21+
2022
const VALID_SECRET = "test-secret-123";
2123

2224
function makeRequest(pathname, { secret, body } = {}) {
@@ -88,7 +90,7 @@ describe("handleInternalDispatch โ€” ์ธ์ฆ", () => {
8890
});
8991

9092
describe("handleInternalDispatch โ€” ๋ผ์šฐํŒ…", () => {
91-
const env = { INTERNAL_SECRET: VALID_SECRET, AI_GATEWAY_TOKEN: "fake-gateway-token" };
93+
const env = { INTERNAL_SECRET: VALID_SECRET, AI: FAKE_AI };
9294

9395
beforeEach(() => {
9496
vi.clearAllMocks();
@@ -123,7 +125,7 @@ describe("handleInternalDispatch โ€” ๋ผ์šฐํŒ…", () => {
123125
"abc123",
124126
prData,
125127
"fake-token",
126-
"fake-gateway-token"
128+
FAKE_AI
127129
);
128130
expect(postLearningStatus).not.toHaveBeenCalled();
129131
});
@@ -154,7 +156,7 @@ describe("handleInternalDispatch โ€” ๋ผ์šฐํŒ…", () => {
154156
42,
155157
"testuser",
156158
"fake-token",
157-
"fake-gateway-token"
159+
FAKE_AI
158160
);
159161
expect(tagPatterns).not.toHaveBeenCalled();
160162
});
@@ -200,7 +202,7 @@ describe("handleInternalDispatch โ€” ๋ผ์šฐํŒ…", () => {
200202
});
201203

202204
describe("handleInternalDispatch โ€” ์—๋Ÿฌ ์ฒ˜๋ฆฌ", () => {
203-
const env = { INTERNAL_SECRET: VALID_SECRET, AI_GATEWAY_TOKEN: "fake-gateway-token" };
205+
const env = { INTERNAL_SECRET: VALID_SECRET, AI: FAKE_AI };
204206

205207
beforeEach(() => {
206208
vi.clearAllMocks();

โ€Žhandlers/learning-status.jsโ€Ž

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ function buildCategoryProgress(categories, solvedProblems) {
9393
* @param {number} prNumber
9494
* @param {string} username
9595
* @param {string} appToken - GitHub App installation token
96-
* @param {string} openaiApiKey
96+
* @param {Ai} ai - Worker ์˜ AI ๋ฐ”์ธ๋”ฉ (env.AI)
9797
* @returns {Promise<{ skipped: string }|{ analyzed: number, matched: number }>}
9898
*/
9999
export async function postLearningStatus(
@@ -102,7 +102,7 @@ export async function postLearningStatus(
102102
prNumber,
103103
username,
104104
appToken,
105-
openaiApiKey
105+
ai
106106
) {
107107
// 1. ๋ฌธ์ œ ์นดํ…Œ๊ณ ๋ฆฌ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ์กฐํšŒ
108108
const categories = await fetchProblemCategories(repoOwner, repoName, appToken);
@@ -167,7 +167,7 @@ export async function postLearningStatus(
167167
fileContent,
168168
submission.problemName,
169169
problemInfo,
170-
openaiApiKey
170+
ai
171171
);
172172

173173
if (analysis.usage) {

โ€Žhandlers/tag-patterns.jsโ€Ž

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const MAX_CHECK_RUN_OUTPUT_LENGTH = 65535;
3535
* @param {string} headSha - PR head commit SHA
3636
* @param {object} prData - PR ๊ฐ์ฒด (draft, labels ํฌํ•จ)
3737
* @param {string} appToken - GitHub App installation token
38-
* @param {string} openaiApiKey
38+
* @param {Ai} ai - Worker ์˜ AI ๋ฐ”์ธ๋”ฉ (env.AI)
3939
*/
4040
export async function tagPatterns(
4141
repoOwner,
@@ -44,7 +44,7 @@ export async function tagPatterns(
4444
headSha,
4545
prData,
4646
appToken,
47-
openaiApiKey
47+
ai
4848
) {
4949
// 2-1. Skip ์กฐ๊ฑด
5050
if (prData.draft === true) {
@@ -84,7 +84,7 @@ export async function tagPatterns(
8484
const fileEntries = await downloadFileEntries(solutionFiles);
8585

8686
// 2-4. ๋ณต์žก๋„ ๋ถ„์„์€ 1์ฝœ์ด๋ฏ€๋กœ ํŒจํ„ด ๋ฃจํ”„์™€ ๋ณ‘๋ ฌ ์ง„ํ–‰. ์‹คํŒจํ•ด๋„ ํŒจํ„ด ๋ถ„์„์€ ๊ฒŒ์‹œ.
87-
const complexityPromise = callComplexityAnalysis(fileEntries, openaiApiKey)
87+
const complexityPromise = callComplexityAnalysis(fileEntries, ai)
8888
.catch((err) => {
8989
console.error(`[tagPatterns] complexity analysis failed: ${err.message}`);
9090
return [];
@@ -97,7 +97,7 @@ export async function tagPatterns(
9797
const analysis = await generatePatternAnalysis(
9898
fe.content,
9999
fe.problemName,
100-
openaiApiKey
100+
ai
101101
);
102102
analyses.push({ fileEntry: fe, analysis });
103103
} catch (error) {

0 commit comments

Comments
ย (0)