Skip to content

Conversation

github-actions[bot]
Copy link

Closes #531

Applied changes based on Issue #531.

I’ve refactored src/api/openai.ts to improve readability, modularity, and maintain the exact same functionality:

What changed

  • Consolidated imports
    Merged the two separate openai imports into one line using TS’s type import.
  • Introduced constants & types
    • MAX_COMPLETION_TOKENS and MAX_SUBJECT_LENGTH replace magic numbers.
    • Extracted a CommitContext interface for { prNumber?, issueNumber? }.
  • Modularized logic
    • buildUserMessage: assembles the AI prompt (files, user request, PR/issue context).
    • getFallbackMessage: centralizes the fallback (“chore:” …) commit message logic.
  • Streamlined generateCommitMessage
    • Uses the new helpers for clarity.
    • Throws a ParseError on invalid AI output to fall through to fallback handling.
    • Simplified error handling to a single catch returning getFallbackMessage.
  • Cleaned up JSDoc/comments
    Removed the old verbose doc-block and updated comments to reflect the new structure.

These changes remove inline concatenations, collapse duplicated logic, and improve overall maintainability without altering any behavior. Feel free to let me know if you’d like further tweaks!


Diff highlights:

- import OpenAI from 'openai';
- import type { ClientOptions } from 'openai';
+ import OpenAI, { type ClientOptions } from 'openai';

- // Magic numbers sprinkled inline
- max_completion_tokens: 1024,
+ const MAX_COMPLETION_TOKENS = 1024;
+ max_completion_tokens: MAX_COMPLETION_TOKENS,

- // In‑function string building + fallback branching
+ export interface CommitContext { prNumber?: number; issueNumber?: number }
+ function buildUserMessage(...) { /* prompt assembly */ }
+ function getFallbackMessage(...) { /* chore: … fallback */ }

- export async function generateCommitMessage(
-   changedFiles, userPrompt, context, config
- ) { … }
+ export async function generateCommitMessage(
+   changedFiles: string[],
+   userPrompt: string,
+   context: CommitContext,
+   config: ActionConfig,
+ ): Promise<string> {
+   const systemPrompt = conventionalCommitsSystemPrompt;
+   const userMessage = buildUserMessage(changedFiles, userPrompt, context);
+   try {
+     const response = await getOpenAIClient(config).chat.completions.create({
+       model: config.openaiModel,
+       max_completion_tokens: MAX_COMPLETION_TOKENS,
+       messages: [
+         { role: 'system', content: systemPrompt },
+         { role: 'user',   content: userMessage },
+       ],
+     });
+
+     const content = response.choices?.[0]?.message?.content?.trim() ?? '';
+     const subject = content.split(/\r?\n/)[0] || '';
+     if (!subject || subject.length > MAX_SUBJECT_LENGTH) {
+       throw new ParseError(`Invalid commit message: "${subject}"`);
+     }
+
+     core.info(`Generated commit message: ${subject}`);
+     return subject;
+   } catch {
+     core.warning(`Error generating commit message… Using fallback.`);
+     return getFallbackMessage(changedFiles, context);
+   }
+ }

【F:src/api/openai.ts†L7-L14】【F:src/api/openai.ts†L36-L147】

Let me know if you’d like any further adjustments!

@YiweiShen YiweiShen merged commit d91ee6b into main Jul 26, 2025
3 checks passed
@YiweiShen YiweiShen deleted the codez-chore-531-refactor-openai-simplify-openai-api-client-code-3121137995 branch July 26, 2025 03:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Done] Refactor src/api/openai.ts

1 participant