MCPcopy
hub / github.com/lobehub/lobehub / LobeCloudflareAI

Class LobeCloudflareAI

packages/model-runtime/src/providers/cloudflare/index.ts:55–205  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

53}
54
55export class LobeCloudflareAI implements LobeRuntimeAI {
56 baseURL: string;
57 accountID: string;
58 apiKey?: string;
59
60 constructor({ apiKey, baseURLOrAccountID }: LobeCloudflareParams = {}) {
61 if (!baseURLOrAccountID) {
62 throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);
63 }
64 if (baseURLOrAccountID.startsWith('http')) {
65 this.baseURL = baseURLOrAccountID.endsWith('/')
66 ? baseURLOrAccountID
67 : baseURLOrAccountID + '/';
68 // Try get accountID from baseURL
69 this.accountID = baseURLOrAccountID.replaceAll(/^.*\/([\da-f]{32})\/.*$/gi, '$1');
70 } else {
71 if (!apiKey) {
72 throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);
73 }
74 this.accountID = baseURLOrAccountID;
75 this.baseURL = fillUrl(baseURLOrAccountID);
76 }
77 this.apiKey = apiKey;
78 }
79
80 async chat(payload: ChatStreamPayload, options?: ChatMethodOptions): Promise<Response> {
81 // Remove internal apiMode parameter to prevent sending to Cloudflare API
82 const { model, tools, apiMode: _, ...restPayload } = payload;
83 const functions = tools?.map((tool) => tool.function);
84 const headers = options?.headers || {};
85 if (this.apiKey) {
86 headers['Authorization'] = `Bearer ${this.apiKey}`;
87 }
88 const url = new URL(model, this.baseURL);
89 const desensitizedEndpoint = desensitizeCloudflareUrl(url.toString());
90
91 let response: Response;
92 try {
93 response = await fetch(url, {
94 body: JSON.stringify({ tools: functions, ...restPayload }),
95 headers: { 'Content-Type': 'application/json', ...headers },
96 method: 'POST',
97 signal: options?.signal,
98 });
99 } catch (error) {
100 throw AgentRuntimeError.chat({
101 endpoint: desensitizeCloudflareUrl(this.baseURL),
102 error: error as any,
103 errorType: AgentRuntimeErrorType.ProviderBizError,
104 message: extractProviderErrorMessage(error) ?? 'Cloudflare API request failed',
105 provider: ModelProvider.Cloudflare,
106 });
107 }
108
109 if (response.status === 400) {
110 const bodyText = await response.text().catch(() => '');
111 let parsedBody: unknown = bodyText;
112 if (bodyText) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected