Support proxying AI provider traffic

This commit is contained in:
Alex Gleason committed 2025-10-08 16:22:07 -05:00
1 parent 0b95398f2d
commit 1bb949217a
13 files changed
+126 -30

No files matched your search

+4 -1
View File
@@ -60,17 +60,20 @@ export class SessionManager {
private aiSettings: { providers: AIProvider[] };
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
constructor(
fs: JSRuntimeFS,
aiSettings: { providers: AIProvider[] },
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
corsProxy?: string,
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.corsProxy = corsProxy;
}
/**
@@ -206,7 +209,7 @@ export class SessionManager {
// Initialize OpenAI client
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user);
const openai = createAIClient(provider, user, this.corsProxy);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
+38 -19
View File
@@ -1,39 +1,58 @@
import OpenAI from 'openai';
import { NIP98Client } from '@nostrify/nostrify';
import { NIP98 } from '@nostrify/nostrify';
import { N64 } from '@nostrify/nostrify/utils';
import type { NUser } from '@nostrify/react/login';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { proxyUrl } from './proxyUrl';
/**
* Create an OpenAI client instance with the appropriate configuration.
* If the connection requires Nostr authentication (NIP-98), it will use
* the NIP98Client for authenticated requests.
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
*/
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
defaultHeaders: provider.id === 'openrouter' ? {
// https://openrouter.ai/docs/app-attribution
'HTTP-Referer': 'https://shakespeare.diy',
'X-Title': 'Shakespeare',
} : {},
};
let openai: OpenAI;
const openai = new OpenAI({
...baseConfig,
fetch: async (input, init) => {
let request = new Request(input, init);
// If Nostr authentication is required and we have a user, use NIP-98
if (provider.nostr && user?.signer) {
const nip98Client = new NIP98Client({ signer: user.signer });
// Add OpenRouter headers
// https://openrouter.ai/docs/app-attribution
if (provider.id === 'openrouter') {
const headers = new Headers(request.headers);
headers.set('HTTP-Referer', 'https://shakespeare.diy');
headers.set('X-Title', 'Shakespeare');
request = new Request(request, { headers });
}
openai = new OpenAI({
...baseConfig,
fetch: (input, init) => nip98Client.fetch(input, init),
});
} else {
// Standard OpenAI client
openai = new OpenAI(baseConfig);
}
// If Nostr authentication is required and we have a user, use NIP-98
if (provider.nostr && user?.signer) {
// Create the NIP98 token
const template = await NIP98.template(request);
const event = await user.signer.signEvent(template);
const token = N64.encodeEvent(event);
// Add the Authorization header
const headers = new Headers(request.headers);
headers.set('Authorization', `Nostr ${token}`);
request = new Request(request, { headers });
}
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
if (provider.proxy && corsProxy) {
request = new Request(proxyUrl(corsProxy, request.url), request);
}
return fetch(request);
},
});
const createCompletion: typeof openai.chat.completions.create
= openai.chat.completions.create.bind(openai.chat.completions);
+9
View File
@@ -5,6 +5,7 @@ export interface PresetProvider {
apiKeysURL?: string;
nostr?: boolean;
tosURL?: string;
proxy?: boolean;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -71,6 +72,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
apiKeysURL: "https://platform.deepseek.com/api_keys",
tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html",
},
{
id: "moonshot",
name: "Moonshot AI",
baseURL: "https://api.moonshot.ai/v1",
apiKeysURL: "https://platform.moonshot.ai/console/api-keys",
tosURL: "https://platform.moonshot.ai/docs/agreement/modeluse",
proxy: true,
},
];
// Helper function to get a specific preset by ID
+1
View File
@@ -13,6 +13,7 @@ const aiProviderSchema: z.ZodType<AIProvider> = z.object({
baseURL: z.string().url(),
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
proxy: z.boolean().optional(),
});
const providerModelSchema = z.string().regex(
+6
View File
@@ -195,6 +195,7 @@ const resources = {
baseUrl: 'Base URL',
apiKey: 'API Key',
authentication: 'Authentication',
useCorsProxy: 'Use CORS Proxy',
addCustomProviderButton: 'Add Custom Provider',
providerExists: 'Provider with this name already exists',
agreeToTermsOfService: 'I agree to {{providerName}}’s',
@@ -510,6 +511,7 @@ const resources = {
baseUrl: 'URL Base',
apiKey: 'Chave de API',
authentication: 'Autenticação',
useCorsProxy: 'Usar Proxy CORS',
addCustomProviderButton: 'Adicionar Provedor Personalizado',
providerExists: 'Provedor com este nome já existe',
agreeToTermsOfService: 'Concordo com {{providerName}}',
@@ -831,6 +833,7 @@ const resources = {
baseUrl: '基础URL',
apiKey: 'API密钥',
authentication: '身份验证',
useCorsProxy: '使用CORS代理',
addCustomProviderButton: '添加自定义提供商',
providerExists: '此名称的提供商已存在',
agreeToTermsOfService: '我同意{{providerName}}',
@@ -1152,6 +1155,7 @@ const resources = {
baseUrl: 'URL na Tushe',
apiKey: 'Maɓallin API',
authentication: 'Tabbatarwa',
useCorsProxy: 'Yi amfani da CORS Proxy',
addCustomProviderButton: 'Ƙara Mai Samarwa na Musamman',
providerExists: 'Mai samarwa da wannan suna ya riga ya wanzu',
agreeToTermsOfService: 'Na yarda da {{providerName}}',
@@ -1473,6 +1477,7 @@ const resources = {
baseUrl: 'URL Ipilẹ',
apiKey: 'Bọtini API',
authentication: 'Ijẹrisi',
useCorsProxy: 'Lo CORS Proxy',
addCustomProviderButton: 'Fi Olupese Aṣa kun',
providerExists: 'Olupese pẹlu orukọ yii ti wa tẹlẹ',
agreeToTermsOfService: 'Mo gba {{providerName}}',
@@ -1789,6 +1794,7 @@ const resources = {
baseUrl: 'URL Ntọala',
apiKey: 'Igodo API',
authentication: 'Nkwenye',
useCorsProxy: 'Jiri CORS Proxy',
addCustomProviderButton: 'Tinye Onye Na-enye Omenala',
providerExists: 'Onye na-enye nwere aha a adịlarị',
agreeToTermsOfService: 'Ekwenyere m na {{providerName}}',