@juspay/neurolink 9.68.3 → 9.68.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,215 +1,58 @@
1
- import { createOpenAI } from "@ai-sdk/openai";
2
- import { BaseProvider } from "../core/baseProvider.js";
3
- import { DEFAULT_MAX_STEPS } from "../core/constants.js";
4
- import { streamAnalyticsCollector } from "../core/streamAnalytics.js";
5
- import { isNeuroLink } from "../neurolink.js";
6
- import { createProxyFetch } from "../proxy/proxyFetch.js";
7
- import { createLoggingFetch } from "../utils/loggingFetch.js";
8
- import { tracers, ATTR, withClientStreamSpan } from "../telemetry/index.js";
9
1
  import { NetworkError, ProviderError } from "../types/index.js";
10
2
  import { logger } from "../utils/logger.js";
11
- import { composeAbortSignals, createTimeoutController, TimeoutError, } from "../utils/timeout.js";
12
- import { emitToolEndFromStepFinish } from "../utils/toolEndEmitter.js";
13
- import { resolveToolChoice } from "../utils/toolChoice.js";
14
- import { toAnalyticsStreamResult } from "./providerTypeUtils.js";
15
- import { stepCountIs } from "../utils/tool.js";
16
- import { streamText } from "../utils/generation.js";
3
+ import { TimeoutError } from "../utils/timeout.js";
4
+ import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
17
5
  const LLAMACPP_DEFAULT_BASE_URL = "http://localhost:8080/v1";
18
6
  const LLAMACPP_PLACEHOLDER_KEY = "llamacpp";
19
- const FALLBACK_MODEL = "loaded-model";
20
7
  const getLlamaCppBaseURL = () => {
21
8
  return process.env.LLAMACPP_BASE_URL || LLAMACPP_DEFAULT_BASE_URL;
22
9
  };
23
10
  /**
24
- * llama.cpp Provider
11
+ * Strip embedded `user:pass@` credentials from a URL before logging it or
12
+ * surfacing it in a user-facing error. Preserves host/port/path so the URL
13
+ * stays useful for diagnostics.
14
+ */
15
+ const redactUrlCredentials = (url) => url.replace(/\/\/[^/@]+@/, "//***@");
16
+ /**
17
+ * llama.cpp Provider — direct HTTP, no AI SDK.
18
+ *
25
19
  * Wraps a llama-server process (https://github.com/ggerganov/llama.cpp) that
26
20
  * exposes an OpenAI-compatible API at http://localhost:8080/v1 by default.
27
21
  * llama-server hosts ONE model loaded at startup; /v1/models returns just that.
22
+ * All request/stream/tool-loop orchestration lives in
23
+ * `OpenAIChatCompletionsProvider`; this class only declares configuration
24
+ * and provider-specific error mapping.
25
+ *
26
+ * @see https://github.com/ggerganov/llama.cpp
28
27
  */
29
- export class LlamaCppProvider extends BaseProvider {
30
- model;
31
- // Caller-supplied model name — never overwritten by discovery, so a
32
- // FALLBACK_MODEL miss can't poison the explicit-vs-discover branch on
33
- // subsequent calls.
34
- requestedModelName;
35
- baseURL;
36
- apiKey;
37
- discoveredModel;
38
- llamaCppClient;
28
+ export class LlamaCppProvider extends OpenAIChatCompletionsProvider {
39
29
  constructor(modelName, sdk, _region, credentials) {
40
- const validatedNeurolink = isNeuroLink(sdk) ? sdk : undefined;
41
- super(modelName, "llamacpp", validatedNeurolink);
42
- this.requestedModelName = modelName;
43
- this.baseURL = credentials?.baseURL ?? getLlamaCppBaseURL();
44
- // llama-server doesn't authenticate, but the AI SDK's createOpenAI() requires
45
- // an apiKey. Allow override via credentials/env for users who run llama-server
46
- // behind an auth-proxying reverse-proxy.
47
- this.apiKey =
48
- credentials?.apiKey ??
49
- process.env.LLAMACPP_API_KEY ??
50
- LLAMACPP_PLACEHOLDER_KEY;
51
- this.llamaCppClient = createOpenAI({
52
- baseURL: this.baseURL,
53
- apiKey: this.apiKey,
54
- fetch: createLoggingFetch("llamacpp"),
55
- });
30
+ const baseURL = credentials?.baseURL?.trim() || getLlamaCppBaseURL();
31
+ // llama-server doesn't authenticate, but the base class requires an
32
+ // apiKey. Allow override via credentials/env for users who run
33
+ // llama-server behind an auth-proxying reverse-proxy.
34
+ const apiKey = credentials?.apiKey?.trim() ||
35
+ process.env.LLAMACPP_API_KEY ||
36
+ LLAMACPP_PLACEHOLDER_KEY;
37
+ super("llamacpp", modelName, sdk, { baseURL, apiKey });
56
38
  logger.debug("llama.cpp Provider initialized", {
57
39
  modelName: this.modelName,
58
40
  providerName: this.providerName,
59
- baseURL: this.baseURL,
60
- });
61
- }
62
- async getAvailableModels(callerSignal) {
63
- const url = `${this.baseURL.replace(/\/$/, "")}/models`;
64
- // Use the proxy-aware fetch + bearer auth so users running llama-server
65
- // behind an auth-proxying reverse-proxy can still discover the model.
66
- // Compose the caller's request signal (per-request timeout / abort) with
67
- // a fixed 5s discovery cap so cancellation propagates AND a hung server
68
- // can't stall provider initialization.
69
- const proxyFetch = createProxyFetch();
70
- const discoveryTimeout = AbortSignal.timeout(5000);
71
- const composedSignal = callerSignal
72
- ? AbortSignal.any([callerSignal, discoveryTimeout])
73
- : discoveryTimeout;
74
- const response = await proxyFetch(url, {
75
- headers: this.apiKey && this.apiKey !== LLAMACPP_PLACEHOLDER_KEY
76
- ? { Authorization: `Bearer ${this.apiKey}` }
77
- : undefined,
78
- signal: composedSignal,
41
+ baseURL: redactUrlCredentials(this.config.baseURL),
79
42
  });
80
- if (!response.ok) {
81
- throw new Error(`llama-server /v1/models returned ${response.status}: ${response.statusText}`);
82
- }
83
- const data = (await response.json());
84
- return data.data.map((m) => m.id);
85
- }
86
- async getAISDKModel(signal) {
87
- if (this.model) {
88
- return this.model;
89
- }
90
- let modelToUse;
91
- let discoverySucceeded = false;
92
- // Use requestedModelName, not this.modelName — refreshHandlersForModel()
93
- // mutates this.modelName, so on a retry after a discovery miss the
94
- // FALLBACK_MODEL would look like an explicit user choice. See lmStudio.ts.
95
- const explicit = this.requestedModelName;
96
- if (explicit && explicit.trim() !== "") {
97
- modelToUse = explicit;
98
- discoverySucceeded = true; // explicit user choice — treat as success
99
- }
100
- else {
101
- try {
102
- const models = await this.getAvailableModels(signal);
103
- if (models.length > 0) {
104
- this.discoveredModel = models[0];
105
- modelToUse = this.discoveredModel;
106
- discoverySucceeded = true;
107
- logger.info(`llama.cpp loaded model: ${modelToUse}`);
108
- }
109
- else {
110
- modelToUse = FALLBACK_MODEL;
111
- }
112
- }
113
- catch (error) {
114
- logger.warn(`llama.cpp model discovery failed: ${error instanceof Error ? error.message : String(error)}`);
115
- modelToUse = FALLBACK_MODEL;
116
- }
117
- }
118
- // Persist resolved model on the instance and rebuild the composed
119
- // handlers (TelemetryHandler, MessageBuilder, etc.) so pricing /
120
- // telemetry / span attributes report the discovered model name. Plain
121
- // assignment to `this.modelName` is not enough — handlers cached the
122
- // pre-discovery value at construction time.
123
- this.refreshHandlersForModel(modelToUse);
124
- // .chat() — llama-server exposes /v1/chat/completions, not /v1/responses
125
- const resolvedModel = this.llamaCppClient.chat(modelToUse);
126
- // Only memoize on success — see lmStudio.ts for the same rationale: a
127
- // discovery miss should let the next call retry instead of being stuck
128
- // on FALLBACK_MODEL until the provider instance is recreated.
129
- if (discoverySucceeded) {
130
- this.model = resolvedModel;
131
- }
132
- return resolvedModel;
133
- }
134
- async executeStream(options, _analysisSchema) {
135
- // Resolve the llama.cpp model BEFORE opening the span so OTEL
136
- // attributes, MessageBuilder, and downstream image/tool adapters all see
137
- // the discovered model id rather than the empty pre-discovery placeholder.
138
- // Pass the caller's abort signal so user cancellation / per-request
139
- // timeouts are honored during the discovery probe.
140
- await this.getAISDKModel(options.abortSignal);
141
- return withClientStreamSpan({
142
- name: "neurolink.provider.stream",
143
- tracer: tracers.provider,
144
- attributes: {
145
- [ATTR.GEN_AI_SYSTEM]: "llamacpp",
146
- [ATTR.GEN_AI_MODEL]: this.modelName || this.discoveredModel || FALLBACK_MODEL,
147
- [ATTR.GEN_AI_OPERATION]: "stream",
148
- [ATTR.NL_STREAM_MODE]: true,
149
- },
150
- }, async () => this.executeStreamInner(options), (r) => r.stream, (r, wrapped) => ({ ...r, stream: wrapped }));
151
- }
152
- async executeStreamInner(options) {
153
- this.validateStreamOptions(options);
154
- const startTime = Date.now();
155
- const timeout = this.getTimeout(options);
156
- const timeoutController = createTimeoutController(timeout, this.providerName, "stream");
157
- try {
158
- const shouldUseTools = !options.disableTools && this.supportsTools();
159
- const tools = shouldUseTools
160
- ? options.tools || (await this.getAllTools())
161
- : {};
162
- // Resolve the AI SDK model BEFORE building messages so message/image
163
- // adapters see the same handlers/model that streamText will use. See
164
- // lmStudio.ts for the same rationale.
165
- const model = await this.getAISDKModelWithMiddleware(options);
166
- const messages = await this.buildMessagesForStream(options);
167
- const result = await streamText({
168
- model,
169
- messages,
170
- temperature: options.temperature,
171
- maxOutputTokens: options.maxTokens,
172
- tools,
173
- stopWhen: stepCountIs(options.maxSteps || DEFAULT_MAX_STEPS),
174
- toolChoice: resolveToolChoice(options, tools, shouldUseTools),
175
- abortSignal: composeAbortSignals(options.abortSignal, timeoutController?.controller.signal),
176
- experimental_telemetry: this.telemetryHandler.getTelemetryConfig(options),
177
- experimental_repairToolCall: this.getToolCallRepairFn(options),
178
- onStepFinish: ({ toolCalls, toolResults }) => {
179
- emitToolEndFromStepFinish(this.neurolink?.getEventEmitter(), toolResults);
180
- this.handleToolExecutionStorage(toolCalls, toolResults, options, new Date()).catch((error) => {
181
- logger.warn("[LlamaCppProvider] Failed to store tool executions", {
182
- provider: this.providerName,
183
- error: error instanceof Error ? error.message : String(error),
184
- });
185
- });
186
- },
187
- });
188
- timeoutController?.cleanup();
189
- const transformedStream = this.createTextStream(result);
190
- const analyticsPromise = streamAnalyticsCollector.createAnalytics(this.providerName, this.modelName || this.discoveredModel || FALLBACK_MODEL, toAnalyticsStreamResult(result), Date.now() - startTime, {
191
- requestId: `llamacpp-stream-${Date.now()}`,
192
- streamingMode: true,
193
- });
194
- return {
195
- stream: transformedStream,
196
- provider: this.providerName,
197
- model: this.modelName || this.discoveredModel || FALLBACK_MODEL,
198
- analytics: analyticsPromise,
199
- metadata: { startTime, streamId: `llamacpp-${Date.now()}` },
200
- };
201
- }
202
- catch (error) {
203
- timeoutController?.cleanup();
204
- throw this.handleProviderError(error);
205
- }
206
43
  }
207
44
  getProviderName() {
208
- return this.providerName;
45
+ return "llamacpp";
209
46
  }
210
47
  getDefaultModel() {
211
48
  return process.env.LLAMACPP_MODEL || "";
212
49
  }
50
+ getFallbackModelName() {
51
+ return "loaded-model";
52
+ }
53
+ getFallbackModels() {
54
+ return ["loaded-model"];
55
+ }
213
56
  formatProviderError(error) {
214
57
  if (error instanceof TimeoutError) {
215
58
  return new NetworkError(`Request timed out: ${error.message}`, "llamacpp");
@@ -224,7 +67,7 @@ export class LlamaCppProvider extends BaseProvider {
224
67
  message.includes("ECONNREFUSED") ||
225
68
  message.includes("Failed to fetch") ||
226
69
  message.includes("fetch failed")) {
227
- return new NetworkError(`llama.cpp server not reachable at ${this.baseURL}. ` +
70
+ return new NetworkError(`llama.cpp server not reachable at ${redactUrlCredentials(this.config.baseURL)}. ` +
228
71
  "Start it with: ./llama-server -m model.gguf --port 8080", "llamacpp");
229
72
  }
230
73
  if (message.includes("400")) {
@@ -232,52 +75,4 @@ export class LlamaCppProvider extends BaseProvider {
232
75
  }
233
76
  return new ProviderError(`llama.cpp error: ${message}`, "llamacpp");
234
77
  }
235
- async validateConfiguration() {
236
- // Retry up to 3x with 500ms backoff. llama-server can be briefly unresponsive
237
- // under load (CPU inference saturates the event loop). Use the proxy-aware
238
- // fetch + bearer auth header so reverse-proxied setups still validate.
239
- const healthURL = this.baseURL.replace(/\/v1\/?$/, "/health");
240
- const modelsURL = `${this.baseURL.replace(/\/$/, "")}/models`;
241
- const proxyFetch = createProxyFetch();
242
- const headers = this.apiKey && this.apiKey !== LLAMACPP_PLACEHOLDER_KEY
243
- ? { Authorization: `Bearer ${this.apiKey}` }
244
- : undefined;
245
- for (let attempt = 0; attempt < 3; attempt++) {
246
- try {
247
- const r = await proxyFetch(healthURL, {
248
- headers,
249
- signal: AbortSignal.timeout(2000),
250
- });
251
- if (r.ok) {
252
- return true;
253
- }
254
- }
255
- catch {
256
- /* fall through */
257
- }
258
- try {
259
- const r2 = await proxyFetch(modelsURL, {
260
- headers,
261
- signal: AbortSignal.timeout(2000),
262
- });
263
- if (r2.ok) {
264
- return true;
265
- }
266
- }
267
- catch {
268
- /* fall through */
269
- }
270
- await new Promise((resolve) => setTimeout(resolve, 500));
271
- }
272
- return false;
273
- }
274
- getConfiguration() {
275
- return {
276
- provider: this.providerName,
277
- model: this.modelName || this.discoveredModel || FALLBACK_MODEL,
278
- defaultModel: this.getDefaultModel(),
279
- baseURL: this.baseURL,
280
- };
281
- }
282
78
  }
283
- export default LlamaCppProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "9.68.3",
3
+ "version": "9.68.4",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "Universal AI Development Platform with working MCP integration, multi-provider support, voice (TTS/STT/realtime), and professional CLI. 58+ external MCP servers discoverable, multimodal file processing, RAG pipelines. Build, test, and deploy AI applications with 21+ providers: OpenAI, Anthropic, Google AI Studio, Google Vertex, AWS Bedrock, Azure OpenAI, Mistral, LiteLLM, SageMaker, Hugging Face, Ollama, OpenAI-compatible, OpenRouter, DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, plus voice (OpenAI TTS, ElevenLabs, Deepgram, Azure Speech).",
6
6
  "author": {