Add createStreamFn for CORS proxy support

- createStreamFn(proxyUrl?) returns a sync streamFn that applies proxy
- Example reads proxy settings once when creating Agent
- Matches old ProviderTransport behavior
This commit is contained in:
Mario Zechner 2025-12-28 11:37:42 +01:00
parent e49e787322
commit e0be2e650d
3 changed files with 28 additions and 1 deletions

View file

@ -1,4 +1,5 @@
import type { Api, Model } from "@mariozechner/pi-ai";
import type { Api, Context, Model, SimpleStreamOptions } from "@mariozechner/pi-ai";
import { streamSimple } from "@mariozechner/pi-ai";
/**
* Centralized proxy decision logic.
@ -110,3 +111,21 @@ export function isCorsError(error: unknown): boolean {
return false;
}
/**
* Create a streamFn that applies CORS proxy when needed.
*
* @param proxyUrl - CORS proxy URL, or undefined to disable
* @returns A streamFn compatible with Agent's streamFn option
*/
export function createStreamFn(proxyUrl?: string) {
return (model: Model<any>, context: Context, options?: SimpleStreamOptions) => {
const apiKey = options?.apiKey;
if (!apiKey || !proxyUrl) {
return streamSimple(model, context, options);
}
const proxiedModel = applyProxyIfNeeded(model, apiKey, proxyUrl);
return streamSimple(proxiedModel, context, options);
};
}