Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set path, hostname, auth #272

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/commands/aicommits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,29 @@ export default async (
);

const { env } = process;
const config = await getConfig({
OPENAI_KEY: env.OPENAI_KEY || env.OPENAI_API_KEY,
proxy:
env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY,
generate: generate?.toString(),
type: commitType?.toString(),
});
const config = await getConfig(
{
OPENAI_KEY: env.OPENAI_KEY || env.OPENAI_API_KEY,
authHeaderName: env.authHeaderName,
hostname: env.hostname,
apipath: env.apipath,
proxy:
env.https_proxy ||
env.HTTPS_PROXY ||
env.http_proxy ||
env.HTTP_PROXY,
generate: generate?.toString(),
type: commitType?.toString(),
},
false
);

const s = spinner();
s.start('The AI is analyzing your changes');
let messages: string[];
try {
messages = await generateCommitMessage(
config.authHeaderName,
config.OPENAI_KEY,
config.model,
config.locale,
Expand All @@ -73,6 +83,8 @@ export default async (
config['max-length'],
config.type,
config.timeout,
config.hostname,
config.apipath,
config.proxy
);
} finally {
Expand Down
5 changes: 4 additions & 1 deletion src/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ export default command(

if (mode === 'set') {
await setConfigs(
keyValues.map((keyValue) => keyValue.split('=') as [string, string])
keyValues.map((keyValue) => {
const equals = keyValue.indexOf('=')
return [keyValue.substring(0,equals), keyValue.substring(equals+1)]
})
);
return;
}
Expand Down
3 changes: 3 additions & 0 deletions src/commands/prepare-commit-msg-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export default () =>
let messages: string[];
try {
messages = await generateCommitMessage(
config.authHeaderName,
config.OPENAI_KEY,
config.model,
config.locale,
Expand All @@ -48,6 +49,8 @@ export default () =>
config['max-length'],
config.type,
config.timeout,
config.hostname,
config.apipath,
config.proxy
);
} finally {
Expand Down
29 changes: 27 additions & 2 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ const configParsers = {
'Please set your OpenAI API key via `aicommits config set OPENAI_KEY=<your token>`'
);
}
parseAssert('OPENAI_KEY', key.startsWith('sk-'), 'Must start with "sk-"');
// Key can range from 43~51 characters. There's no spec to assert this.

return key;
},
Expand Down Expand Up @@ -115,6 +113,33 @@ const configParsers = {

return parsed;
},
authHeaderName(authHeaderName?: string) {
if (!authHeaderName) {
return 'Authorization';
}

return authHeaderName;
},
hostname(hostname?: string) {
if (!hostname) {
return 'api.openai.com';
}

parseAssert(
'hostname',
!/^http/i.test(hostname) && !/\/$/.test(hostname),
'Do not include protocol or path in hostname, only hostname'
);

return hostname;
},
apipath(apipath?: string) {
if (!apipath) {
return '/v1/chat/completions';
}

return apipath;
},
} as const;

type ConfigKeys = keyof typeof configParsers;
Expand Down
24 changes: 17 additions & 7 deletions src/utils/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { generatePrompt } from './prompt.js';

const httpsPost = async (
hostname: string,
path: string,
apipath: string,
headers: Record<string, string>,
json: unknown,
timeout: number,
Expand All @@ -31,7 +31,7 @@ const httpsPost = async (
{
port: 443,
hostname,
path,
path: apipath,
method: 'POST',
headers: {
...headers,
Expand Down Expand Up @@ -68,17 +68,21 @@ const httpsPost = async (
});

const createChatCompletion = async (
authHeaderName: string,
apiKey: string,
json: CreateChatCompletionRequest,
timeout: number,
hostname: string,
apipath: string,
proxy?: string
) => {
let headers: any = {};
headers[authHeaderName] = `${apiKey}`;

const { response, data } = await httpsPost(
'api.openai.com',
'/v1/chat/completions',
{
Authorization: `Bearer ${apiKey}`,
},
hostname,
apipath,
headers,
json,
timeout,
proxy
Expand Down Expand Up @@ -131,6 +135,7 @@ const deduplicateMessages = (array: string[]) => Array.from(new Set(array));
// };

export const generateCommitMessage = async (
authHeaderName: string,
apiKey: string,
model: TiktokenModel,
locale: string,
Expand All @@ -139,10 +144,13 @@ export const generateCommitMessage = async (
maxLength: number,
type: CommitType,
timeout: number,
hostname: string,
apipath: string,
proxy?: string
) => {
try {
const completion = await createChatCompletion(
authHeaderName,
apiKey,
{
model,
Expand All @@ -165,6 +173,8 @@ export const generateCommitMessage = async (
n: completions,
},
timeout,
hostname,
apipath,
proxy
);

Expand Down
37 changes: 27 additions & 10 deletions tests/specs/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,6 @@ export default testSuite(({ describe }) => {
expect(stderr).toMatch('Invalid config property: UNKNOWN');
});

test('set invalid OPENAI_KEY', async () => {
const { stderr } = await aicommits(['config', 'set', 'OPENAI_KEY=abc'], {
reject: false,
});

expect(stderr).toMatch(
'Invalid config property OPENAI_KEY: Must start with "sk-"'
);
});

await test('set config file', async () => {
await aicommits(['config', 'set', openAiToken]);

Expand Down Expand Up @@ -106,6 +96,33 @@ export default testSuite(({ describe }) => {
});
});

await describe('hostname', ({ test }) => {
test('must be an hostname', async () => {
const { stderr } = await aicommits(
['config', 'set', 'hostname=https://api.openai.com/'],
{ reject: false }
);

expect(stderr).toMatch(
'Do not include protocol or path in hostname, only hostname'
);
});

test('updates config', async () => {
const defaultConfig = await aicommits(['config', 'get', 'hostname']);
expect(defaultConfig.stdout).toBe('hostname=api.openai.com');

const hostname = 'hostname=api.chatanywhere.com.cn';
await aicommits(['config', 'set', hostname]);

const configFile = await fs.readFile(configPath, 'utf8');
expect(configFile).toMatch(hostname);

const get = await aicommits(['config', 'get', 'hostname']);
expect(get.stdout).toBe(hostname);
});
});

await test('set config file', async () => {
await aicommits(['config', 'set', openAiToken]);

Expand Down
7 changes: 5 additions & 2 deletions tests/specs/openai/conventional-commits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { generateCommitMessage } from '../../../src/utils/openai.js';
import type { ValidConfig } from '../../../src/utils/config.js';
import { getDiff } from '../../utils.js';

const { OPENAI_KEY } = process.env;
const { OPENAI_KEY, authHeaderName, hostname, apipath } = process.env;

export default testSuite(({ describe }) => {
if (!OPENAI_KEY) {
Expand Down Expand Up @@ -139,14 +139,17 @@ export default testSuite(({ describe }) => {
...configOverrides,
} as ValidConfig;
const commitMessages = await generateCommitMessage(
authHeaderName ?? 'Authorization',
OPENAI_KEY!,
'gpt-3.5-turbo',
config.locale,
gitDiff,
config.generate,
config['max-length'],
config.type,
7000
7000,
hostname ?? 'api.openai.com',
apipath ?? '/v1/completions'
);

return commitMessages[0];
Expand Down