Skip to content

Commit 76e060e

Browse files
committed
zapi
1 parent 49722b5 commit 76e060e

2 files changed

Lines changed: 65 additions & 57 deletions

File tree

.github/scripts/enhance-commits.js

Lines changed: 63 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@ const { exec } = require('child_process');
22
const fs = require('fs').promises;
33
const path = require('path');
44
const axios = require('axios');
5-
const { GoogleGenerativeAI } = require('@google/generative-ai');
65

76
// Configuration
87
const MAX_DIFF_SIZE = 20000; // Characters - truncate if larger
98
const MAX_FILES_TO_SAMPLE = 5; // Maximum number of files to include in the diff
109
const SAMPLE_LINES_PER_FILE = 200; // Maximum lines to include per file
1110

11+
// Z.AI GLM API Configuration
12+
const ZAI_API_ENDPOINT = 'https://api.z.ai/api/coding/paas/v4/chat/completions';
13+
const ZAI_MODEL = 'glm-4.7';
14+
1215
// --- Error Handling ---
1316
class ScriptError extends Error {
1417
constructor(message, context = {}) {
@@ -25,18 +28,39 @@ function log(level, message, context = {}) {
2528
console.log(`[${timestamp}] [${level.toUpperCase()}] ${message}`, context);
2629
}
2730

28-
// Initialize Gemini API
29-
let model;
30-
try {
31-
if (!process.env.GEMINI_API_KEY) {
32-
throw new Error('GEMINI_API_KEY environment variable is not set.');
33-
}
34-
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
35-
model = genAI.getGenerativeModel({ model: 'gemini-3-flash-preview' }); // Change to a version now supported.
36-
log('info', 'Gemini API initialized successfully.');
37-
} catch (error) {
38-
log('error', 'Failed to initialize Gemini API', { error: error.message });
39-
process.exit(1); // Exit if API key is missing or init fails
31+
// Validate Z.AI API key
32+
if (!process.env.ZAI_API_KEY) {
33+
log('error', 'ZAI_API_KEY environment variable is not set.');
34+
process.exit(1);
35+
}
36+
log('info', 'Z.AI API configuration loaded successfully.');
37+
38+
/**
39+
* Calls the Z.AI GLM API with system and user prompts.
40+
* @param {string} systemPrompt - The system instructions.
41+
* @param {string} userPrompt - The user message/data.
42+
* @returns {Promise<string|null>} - The API response content or null if failed.
43+
*/
44+
async function callZaiApi(systemPrompt, userPrompt) {
45+
const requestBody = {
46+
model: ZAI_MODEL,
47+
messages: [
48+
{ role: 'system', content: systemPrompt },
49+
{ role: 'user', content: userPrompt }
50+
],
51+
temperature: 0.7,
52+
stream: false
53+
};
54+
55+
const response = await axios.post(ZAI_API_ENDPOINT, requestBody, {
56+
headers: {
57+
'Content-Type': 'application/json',
58+
'Authorization': `Bearer ${process.env.ZAI_API_KEY}`
59+
},
60+
timeout: 60000
61+
});
62+
63+
return response.data?.choices?.[0]?.message?.content?.trim() || null;
4064
}
4165

4266
// --- Git Operations ---
@@ -361,7 +385,7 @@ async function getRecentBranchCommits(branchName) {
361385
// --- AI Enhancement ---
362386

363387
/**
364-
* Enhances the commit message using the Gemini API.
388+
* Enhances the commit message using the Z.AI API.
365389
* @param {string} originalMessage - The original commit message.
366390
* @param {string} diff - The summarized code diff.
367391
* @param {string} branchName - The current Git branch name.
@@ -376,8 +400,7 @@ async function enhanceCommitMessage(originalMessage, diff, branchName, dirSummar
376400
? `* **Recent Steps on Branch (${branchName}):**\n${recentCommits.map(s => ` * ${s}`).join('\n')}`
377401
: `* **Recent Steps on Branch (${branchName}):** (This appears to be the first commit on this branch since merging from the base branch)`;
378402

379-
const prompt = `
380-
You are an expert developer assistant tasked with refining Git commit messages for the "Raspberry Ninja" project. Your goal is to create a message that follows Conventional Commits format (e.g., "feat:", "fix:", "chore:", "refactor:", "style:", "test:", "docs:", "build:", "ci:") and provides clear, concise, and informative context about the changes.
403+
const systemPrompt = `You are an expert developer assistant tasked with refining Git commit messages for the "Raspberry Ninja" project. Your goal is to create a message that follows Conventional Commits format (e.g., "feat:", "fix:", "chore:", "refactor:", "style:", "test:", "docs:", "build:", "ci:") and provides clear, concise, and informative context about the changes.
381404
382405
**Project Context: Raspberry Ninja**
383406
@@ -386,9 +409,7 @@ You are an expert developer assistant tasked with refining Git commit messages f
386409
* **Key Components:** \`publish.py\` (main RTMP/video publishing script), platform-specific directories (\`raspberry_pi/\`, \`nvidia_jetson/\`, \`orangepi/\`, etc.), installation scripts, system service configurations, hardware-specific optimizations.
387410
* **Technology Stack:** Python, Bash scripting, GStreamer, FFmpeg, system services (systemd), hardware video encoders (H.264/H.265), WebRTC (via VDO.Ninja integration).
388411
389-
**Task:**
390-
391-
Analyze the provided information (original message, code diff, branch context, directory summary, recent commits) and generate an improved commit message adhering to the following guidelines:
412+
**Guidelines:**
392413
393414
1. **Format:** Use the Conventional Commits specification (<type>[optional scope]: <description>). Choose the most appropriate type (feat, fix, chore, refactor, style, test, docs, build, ci). The scope (e.g., \`feat(api)\`, \`fix(twitch)\`, \`chore(deps)\`) is optional but encouraged if the change primarily affects a specific component.
394415
2. **Subject Line:**
@@ -399,12 +420,12 @@ Analyze the provided information (original message, code diff, branch context, d
399420
* Separate the subject from the body with a blank line.
400421
* Explain the *what* and *why* of the change in more detail.
401422
* Use bullet points (-) for distinct changes if applicable.
402-
* Reference specific files, components (e.g., \`dock.html\`, TTS module, GitHub Actions), or features affected.
423+
* Reference specific files, components (e.g., \`publish.py\`, platform directories, GitHub Actions), or features affected.
403424
* Incorporate context from the branch name, directory summary, and recent commits if relevant (e.g., "Continues work on feature X from previous commits").
404425
4. **Tone:** Professional and clear.
405-
5. **Focus:** The message should *only* contain the commit message itself, starting directly with the type/scope. Do not add introductions like "Here is the enhanced commit message:". Crucially, do not include bracketed tags like '[skip ci]', '[auto-enhanced]', '[skip pages]', etc., in your generated message text.
426+
5. **Focus:** The message should *only* contain the commit message itself, starting directly with the type/scope. Do not add introductions like "Here is the enhanced commit message:". Crucially, do not include bracketed tags like '[skip ci]', '[auto-enhanced]', '[skip pages]', etc., in your generated message text.`;
406427

407-
**Input Data:**
428+
const userPrompt = `Analyze the provided information and generate an improved commit message:
408429
409430
* **Original Commit Message:**
410431
\`\`\`
@@ -418,32 +439,26 @@ ${recentCommitLines}
418439
${diff}
419440
\`\`\`
420441
421-
**Generate the improved commit message now:**
422-
`;
442+
**Generate the improved commit message now:**`;
423443

424444
try {
425-
log('debug', 'Sending prompt to Gemini API.');
426-
if (!model) {
427-
throw new Error('Gemini model is not initialized.');
428-
}
429-
const result = await model.generateContent(prompt);
430-
if (!result || !result.response || typeof result.response.text !== 'function') {
431-
log('error', 'Invalid response structure received from Gemini API.', { response: result });
432-
throw new Error('Invalid response structure from Gemini API.');
445+
log('debug', 'Sending prompt to Z.AI API.');
446+
const enhancedMessage = await callZaiApi(systemPrompt, userPrompt);
447+
if (!enhancedMessage) {
448+
throw new Error('Empty response from Z.AI API.');
433449
}
434-
const enhancedMessage = result.response.text().trim();
435-
log('info', 'Successfully received enhanced commit message from Gemini API.');
436-
log('debug', 'Enhanced Message:', { message: enhancedMessage });
450+
log('info', 'Successfully received enhanced commit message from Z.AI API.');
451+
log('debug', 'Enhanced Message:', { message: enhancedMessage });
437452
if (!/^(feat|fix|chore|refactor|style|test|docs|build|ci)/.test(enhancedMessage)) {
438453
log('warn', 'Generated message does not strictly follow Conventional Commit format.', { message: enhancedMessage });
439454
}
440455
return enhancedMessage;
441456
} catch (error) {
442-
log('error', 'Error calling Gemini API', { errorMessage: error.message, promptLength: prompt.length });
457+
log('error', 'Error calling Z.AI API', { errorMessage: error.message });
443458
if (error.response) {
444-
log('error', 'Gemini API Error Response:', { data: error.response.data });
459+
log('error', 'Z.AI API Error Response:', { data: error.response.data });
445460
}
446-
return null;
461+
return null;
447462
}
448463
}
449464

@@ -550,28 +565,23 @@ async function updatePRDescription() {
550565

551566
log('info', `Generating enhanced PR description (diff size: ${diffSnippet.length} chars)...`);
552567

553-
// Generate enhanced description using Gemini
554-
const prompt = `
555-
You are an expert developer assistant helping refine a Pull Request description for the "Social Stream Ninja" project.
568+
// Generate enhanced description using Z.AI
569+
const systemPrompt = `You are an expert developer assistant helping refine a Pull Request description for the "Raspberry Ninja" project.
556570
557571
**Project Context:** (Same as commit message context - wireless HDMI capture, RTMP/WebRTC streaming, multi-platform SBC support, etc.)
558572
559-
**Task:**
560-
561-
Review the existing PR information (title, original description, code diff) and generate an improved, comprehensive PR description. The goal is to clearly explain the PR's purpose, changes, and potential impact.
562-
563573
**Guidelines:**
564574
565575
1. **Structure:** Organize the description logically (e.g., Purpose, Changes, How to Test, Considerations). Use Markdown formatting (headings, lists).
566576
2. **Purpose:** Clearly state the main goal of the PR. What problem does it solve or what feature does it add?
567-
3. **Key Changes:** Summarize the main modifications using bullet points. Mention affected components or features (e.g., "Updated Twitch integration", "Refactored API error handling", "Improved \`dock.html\` layout").
577+
3. **Key Changes:** Summarize the main modifications using bullet points. Mention affected components or features (e.g., "Updated publish.py", "Refactored platform support", "Improved installation scripts").
568578
4. **Context/Why:** Briefly explain the reasoning behind the changes if not obvious.
569579
5. **Testing:** (Optional but helpful) Suggest how reviewers can test the changes.
570580
6. **Relate to Diff:** Ensure the description accurately reflects the code changes shown in the diff summary.
571581
7. **Tone:** Professional and informative.
572-
8. **Output:** Provide *only* the enhanced PR description text in Markdown format. Do not include introductory phrases like "Here's the updated description:". If the original description is good, you can refine it or even state that no major changes are needed (though usually, adding structure is beneficial).
582+
8. **Output:** Provide *only* the enhanced PR description text in Markdown format. Do not include introductory phrases like "Here's the updated description:". If the original description is good, you can refine it or even state that no major changes are needed (though usually, adding structure is beneficial).`;
573583

574-
**Input Data:**
584+
const userPrompt = `Review the existing PR information and generate an improved, comprehensive PR description:
575585
576586
* **PR Title:** ${prTitle}
577587
* **Target Branch:** ${prTargetBranch}
@@ -585,14 +595,12 @@ Review the existing PR information (title, original description, code diff) and
585595
${diffSnippet}
586596
\`\`\`
587597
588-
**Generate the improved PR description now:**
589-
`;
598+
**Generate the improved PR description now:**`;
590599

591-
const enhancedDescriptionResult = await model.generateContent(prompt);
592-
if (!enhancedDescriptionResult || !enhancedDescriptionResult.response || typeof enhancedDescriptionResult.response.text !== 'function') {
593-
throw new Error('Invalid response structure from Gemini API for PR description.');
600+
const enhancedDescription = await callZaiApi(systemPrompt, userPrompt);
601+
if (!enhancedDescription) {
602+
throw new Error('Empty response from Z.AI API for PR description.');
594603
}
595-
const enhancedDescription = enhancedDescriptionResult.response.text().trim();
596604

597605
// Update PR description via GitHub API
598606
const [owner, repo] = repoFullName.split('/');
@@ -691,7 +699,7 @@ async function main() {
691699
// Check if enhancement was successful (API returned something)
692700
// REMOVED: || enhancedMessage.toLowerCase().includes("error")
693701
if (!enhancedMessage || enhancedMessage.trim() === '') {
694-
log('error', 'Failed to generate a valid enhanced commit message from Gemini API (empty response). Aborting update.');
702+
log('error', 'Failed to generate a valid enhanced commit message from Z.AI API (empty response). Aborting update.');
695703
process.exit(1); // Exit with error if enhancement failed critically
696704
}
697705

.github/workflows/enhance-commits.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ jobs:
2727
node-version: '18'
2828

2929
- name: Install dependencies
30-
run: npm install @google/generative-ai axios
30+
run: npm install axios
3131

3232
- name: Configure Git
3333
run: |
@@ -37,6 +37,6 @@ jobs:
3737
- name: Enhance commit messages
3838
id: enhance
3939
env:
40-
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
40+
ZAI_API_KEY: ${{ secrets.ZAI_API_KEY }}
4141
GITHUB_TOKEN: ${{ secrets.COMMIT_ENHANCER_PAT }} # This is used by the script for PR updates
4242
run: node .github/scripts/enhance-commits.js

0 commit comments

Comments
 (0)