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

fix: support http protocol for custom OpenAI api url #51

Merged
merged 2 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -686,13 +686,21 @@
"default": ""
},
{
"title": "OpenAI API URL",
"name": "openAIAPIURL",
"title": "OpenAI Endpoint",
"name": "openAIEndpoint",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tisfeng I just noticed you have updated name property of OpenAI API URL option. I am afraid this will cause the endpoint already set by the user to be overwritten by the default value after the update, because it is actually a new option and the old one was removed.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you reminding, I just fixed it 4907c2e

"type": "textfield",
"required": false,
"description": "Your OpenAI API URL",
"description": "Your OpenAI Endpoint",
"default": "https://api.openai.com/v1/chat/completions"
},
{
"title": "OpenAI Model",
"name": "openAIModel",
"type": "textfield",
"required": false,
"description": "OpenAI Model",
"default": "gpt-3.5-turbo"
},
{
"title": "DeepL Auth Key",
"name": "deepLAuthKey",
Expand Down
36 changes: 25 additions & 11 deletions src/axiosConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import { LocalStorage, showToast, Toast } from "@raycast/api";
import axios from "axios";
import EventEmitter from "events";
import { HttpsProxyAgent } from "hpagent";
import { HttpProxyAgent, HttpsProxyAgent } from "hpagent";
import { getMacSystemProxy } from "mac-system-proxy";
import { networkTimeout } from "./consts";

Expand All @@ -28,6 +28,7 @@ configDefaultAxios();
export const requestCostTime = "requestCostTime";

export let httpsAgent: HttpsProxyAgent | undefined;
export let httpAgent: HttpProxyAgent | undefined;

/**
* Becacuse get system proxy will block 0.4s, we need to get it after finish query.
Expand Down Expand Up @@ -184,12 +185,15 @@ export function getSystemProxyURL(): Promise<string | undefined> {
*
* * Note: this function will block ~0.4s, so should call it at the right time.
*/
export function getProxyAgent(): Promise<HttpsProxyAgent | undefined> {
export function getProxyAgent(isHttps: boolean = true): Promise<HttpsProxyAgent | HttpProxyAgent | undefined> {
console.log(`---> start getProxyAgent`);

if (httpsAgent) {
if (isHttps && httpsAgent) {
console.log(`---> return cached httpsAgent`);
return Promise.resolve(httpsAgent);
} else if (!isHttps && httpAgent) {
console.log(`---> return cached httpAgent`);
return Promise.resolve(httpAgent);
}

return new Promise((resolve) => {
Expand All @@ -203,17 +207,27 @@ export function getProxyAgent(): Promise<HttpsProxyAgent | undefined> {
}

console.log(`---> get system proxy url: ${systemProxyURL}`);
const agent = new HttpsProxyAgent({
keepAlive: true,
proxy: systemProxyURL,
});

httpsAgent = agent;
resolve(agent);
if (isHttps) {
httpsAgent = new HttpsProxyAgent({
keepAlive: true,
proxy: systemProxyURL,
});
resolve(httpsAgent);
} else {
httpAgent = new HttpProxyAgent({
keepAlive: true,
proxy: systemProxyURL,
});
resolve(httpAgent);
}
})
.catch((error) => {
console.error(`---> get system proxy url error: ${error}`);
httpsAgent = undefined;
if (isHttps) {
httpsAgent = undefined;
} else {
httpAgent = undefined;
}
resolve(undefined);
});
});
Expand Down
7 changes: 4 additions & 3 deletions src/preferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ export interface MyPreferences {

enableOpenAITranslate: boolean;
openAIAPIKey: string;
openAIAPIURL: string;
openAIEndpoint: string;
openAIModel: string;
}

/**
Expand Down Expand Up @@ -100,9 +101,9 @@ export class AppKeyStore {
static volcanoSecretId = myPreferences.volcanoAccessKeyId.trim();
static volcanoSecretKey = myPreferences.volcanoAccessKeySecret.trim();

private static defaultOpenAIAPIURL = "https://api.openai.com/v1/chat/completions";
static openAIAPIKey = myPreferences.openAIAPIKey.trim();
static openAIAPIURL = myPreferences.openAIAPIURL.trim() || this.defaultOpenAIAPIURL;
static openAIEndpoint = myPreferences.openAIEndpoint.trim() || "https://api.openai.com/v1/chat/completions";
static openAIModel = myPreferences.openAIModel.trim() || "gpt-3.5-turbo";
}

// Test AES online: https://www.sojson.com/encrypt_aes.html
Expand Down
16 changes: 12 additions & 4 deletions src/translation/openAI/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const timeout = setTimeout(() => {
export async function requestOpenAIStreamTranslate(queryWordInfo: QueryWordInfo): Promise<QueryTypeResult> {
console.warn(`---> start request OpenAI`);

const url = AppKeyStore.openAIAPIURL;
const url = AppKeyStore.openAIEndpoint;

const prompt = `translate the following ${queryWordInfo.fromLanguage} text to ${queryWordInfo.toLanguage}, :\n\n${queryWordInfo.word} `;
console.warn(`---> prompt: ${prompt}`);
Expand All @@ -42,7 +42,7 @@ export async function requestOpenAIStreamTranslate(queryWordInfo: QueryWordInfo)
];

const params = {
model: "gpt-3.5-turbo",
model: AppKeyStore.openAIModel,
messages: message,
temperature: 0,
max_tokens: 2000,
Expand All @@ -67,14 +67,22 @@ export async function requestOpenAIStreamTranslate(queryWordInfo: QueryWordInfo)
let openAIResult: QueryTypeResult;

const httpsAgent = await getProxyAgent();
const httpAgent = await getProxyAgent(false);
const agent = function (url: URL) {
if (url.protocol === "http:") {
return httpAgent;
} else {
return httpsAgent;
}
};
console.warn(`---> openai agent: ${JSON.stringify(httpsAgent)}`);

return new Promise((resolve, reject) => {
fetchSSE(`${url}`, {
method: "POST",
headers,
body: JSON.stringify(params),
agent: httpsAgent,
agent: agent,
signal: controller.signal,
onMessage: (msg) => {
// console.warn(`---> openai msg: ${JSON.stringify(msg)}`);
Expand Down Expand Up @@ -165,7 +173,7 @@ export async function requestOpenAIStreamTranslate(queryWordInfo: QueryWordInfo)
export function requestOpenAITextTranslate(queryWordInfo: QueryWordInfo): Promise<QueryTypeResult> {
// console.warn(`---> start request OpenAI`);

const url = AppKeyStore.openAIAPIURL;
const url = AppKeyStore.openAIEndpoint;
// const prompt = `translate from English to Chinese:\n\n"No level of alcohol consumption is safe for our health." =>`;
const prompt = `translate from ${queryWordInfo.fromLanguage} to ${queryWordInfo.toLanguage}:\n\n"${queryWordInfo.word}" =>`;
const message = [
Expand Down