Skip to content

Commit b9f7457

Browse files
committed
feat: call ai gateway through the workers ai binding
1 parent 44c209a commit b9f7457

17 files changed

Lines changed: 175 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: 24 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,35 @@ 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+
config: { maxAttempts: 3, retryDelay: 1000, backoff: "exponential" },
578582
});
583+
// 인증은 바인딩이 하므로 게이트웨이 토큰을 싣지 않는다
584+
expect(request.headers).not.toHaveProperty("cf-aig-authorization");
579585
});
580586
});
581587

‎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) {

‎handlers/webhooks.js‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ async function handlePullRequestEvent(payload, env, ctx) {
258258
}
259259

260260
// AI 핸들러들을 별도 Worker 호출로 디스패치 (각각 독립적인 subrequest 예산)
261-
if (env.AI_GATEWAY_TOKEN && env.INTERNAL_SECRET && env.WORKER_URL) {
261+
if (env.AI && env.INTERNAL_SECRET && env.WORKER_URL) {
262262
const baseUrl = env.WORKER_URL;
263263

264264
const dispatchHeaders = {
@@ -298,7 +298,7 @@ async function handlePullRequestEvent(payload, env, ctx) {
298298
);
299299

300300
console.log(`[handlePullRequestEvent] Dispatched 2 AI handlers for PR #${prNumber}`);
301-
} else if (env.AI_GATEWAY_TOKEN) {
301+
} else if (env.AI) {
302302
// INTERNAL_SECRET/WORKER_URL 미설정 시 기존 방식으로 폴백 (동일 invocation에서 순차 실행)
303303
console.warn("[handlePullRequestEvent] INTERNAL_SECRET or WORKER_URL not set, running handlers in-process");
304304

@@ -310,14 +310,14 @@ async function handlePullRequestEvent(payload, env, ctx) {
310310
pr.head.sha,
311311
pr,
312312
appToken,
313-
env.AI_GATEWAY_TOKEN
313+
env.AI
314314
);
315315
} catch (error) {
316316
console.error(`[handlePullRequestEvent] tagPatterns failed: ${error.message}`);
317317
}
318318

319319
try {
320-
await postLearningStatus(repoOwner, repoName, prNumber, pr.user.login, appToken, env.AI_GATEWAY_TOKEN);
320+
await postLearningStatus(repoOwner, repoName, prNumber, pr.user.login, appToken, env.AI);
321321
} catch (error) {
322322
console.error(`[handlePullRequestEvent] learningStatus failed: ${error.message}`);
323323
}
@@ -481,9 +481,9 @@ async function handleIssueCommentEvent(payload, env) {
481481
// AI 코드 리뷰 요청 처리
482482
console.log(`AI review requested for PR #${prNumber}${mention.userRequest ? ` - Request: ${mention.userRequest}` : ""}`);
483483

484-
// AI_GATEWAY_TOKEN 확인
485-
if (!env.AI_GATEWAY_TOKEN) {
486-
console.log("AI_GATEWAY_TOKEN not configured");
484+
// AI 바인딩 확인
485+
if (!env.AI) {
486+
console.log("AI binding not configured");
487487
return corsResponse({ message: "AI review not configured" });
488488
}
489489

@@ -506,7 +506,7 @@ async function handleIssueCommentEvent(payload, env) {
506506
issue.title,
507507
issue.body,
508508
appToken,
509-
env.AI_GATEWAY_TOKEN,
509+
env.AI,
510510
mention.userRequest
511511
);
512512

@@ -551,9 +551,9 @@ async function handlePullRequestReviewCommentEvent(payload, env) {
551551

552552
console.log(`AI review requested for PR #${prNumber} (review comment)${mention.userRequest ? ` - Request: ${mention.userRequest}` : ""}`);
553553

554-
// AI_GATEWAY_TOKEN 확인
555-
if (!env.AI_GATEWAY_TOKEN) {
556-
console.log("AI_GATEWAY_TOKEN not configured");
554+
// AI 바인딩 확인
555+
if (!env.AI) {
556+
console.log("AI binding not configured");
557557
return corsResponse({ message: "AI review not configured" });
558558
}
559559

@@ -579,7 +579,7 @@ async function handlePullRequestReviewCommentEvent(payload, env) {
579579
pullRequest.title,
580580
pullRequest.body,
581581
appToken,
582-
env.AI_GATEWAY_TOKEN,
582+
env.AI,
583583
mention.userRequest,
584584
comment.id // 스레드 답변으로 작성
585585
);

0 commit comments

Comments
 (0)