@valerypopoff/rivet2-core 2.8.0 → 2.10.0

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.
Files changed (35) hide show
  1. package/dist/cjs/bundle.cjs +508 -320
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  4. package/dist/esm/model/GraphPreprocessor.js +11 -0
  5. package/dist/esm/model/GraphProcessor.js +60 -3
  6. package/dist/esm/model/LegacyChatEditorCache.js +50 -0
  7. package/dist/esm/model/NodeExclusionPolicy.js +1 -0
  8. package/dist/esm/model/Nodes.js +6 -0
  9. package/dist/esm/model/StreamingOutputWatch.js +18 -18
  10. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  11. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +2 -1
  12. package/dist/esm/model/nodes/ChatNodeBase.js +18 -13
  13. package/dist/esm/model/nodes/CoalesceNewNode.js +22 -0
  14. package/dist/esm/model/nodes/CoalesceNode.js +15 -133
  15. package/dist/esm/model/nodes/CoalesceNodeBase.js +131 -0
  16. package/dist/esm/model/nodes/GraphCallPathNode.js +42 -0
  17. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +2 -0
  18. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +17 -15
  19. package/dist/esm/plugins/google/google.js +8 -128
  20. package/dist/esm/plugins/google/googleGenerativeAi.js +101 -0
  21. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +36 -15
  22. package/dist/types/model/GraphPreprocessor.d.ts +2 -0
  23. package/dist/types/model/GraphProcessor.d.ts +3 -1
  24. package/dist/types/model/LegacyChatEditorCache.d.ts +39 -0
  25. package/dist/types/model/Nodes.d.ts +4 -2
  26. package/dist/types/model/ProcessContext.d.ts +2 -0
  27. package/dist/types/model/StreamingOutputWatch.d.ts +13 -11
  28. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -0
  29. package/dist/types/model/nodes/CoalesceNewNode.d.ts +10 -0
  30. package/dist/types/model/nodes/CoalesceNode.d.ts +9 -15
  31. package/dist/types/model/nodes/CoalesceNodeBase.d.ts +19 -0
  32. package/dist/types/model/nodes/GraphCallPathNode.d.ts +12 -0
  33. package/dist/types/plugins/google/google.d.ts +3 -110
  34. package/dist/types/plugins/google/googleGenerativeAi.d.ts +110 -0
  35. package/package.json +1 -1
@@ -1,144 +1,26 @@
1
- import { NodeImpl } from '../NodeImpl.js';
2
- import {} from '../NodeBase.js';
3
- import { unwrapDataValue } from '../DataValue.js';
4
- import { nanoid } from 'nanoid/non-secure';
5
- import {} from '../GraphProcessor.js';
6
1
  import { dedent } from 'ts-dedent';
7
2
  import { nodeDefinition } from '../NodeDefinition.js';
8
- import {} from '../EditorDefinition.js';
9
- import { getNextVariadicPortIndex } from './variadicPortIndex.js';
10
- const INPUT_PORT_ID_PATTERN = /^input(\d+)$/;
11
- const IGNORE_NULL_LABEL = "Ignore 'null'";
12
- const IGNORE_UNDEFINED_LABEL = "Ignore 'undefined'";
13
- export class CoalesceNodeImpl extends NodeImpl {
14
- static create = () => {
15
- const chartNode = {
16
- type: 'coalesce',
17
- title: 'Coalesce',
18
- id: nanoid(),
19
- data: {
20
- ignoreNull: false,
21
- ignoreUndefined: false,
22
- },
23
- visualData: {
24
- x: 0,
25
- y: 0,
26
- width: 190,
27
- },
28
- };
29
- return chartNode;
30
- };
31
- getInputDefinitions(connections) {
32
- const inputs = [];
33
- const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'strict-positive');
34
- inputs.push({
35
- dataType: 'boolean',
36
- id: 'conditional',
37
- title: 'Conditional',
38
- });
39
- for (let i = 1; i <= inputCount; i++) {
40
- inputs.push({
41
- dataType: 'any',
42
- id: `input${i}`,
43
- title: `Input ${i}`,
44
- });
45
- }
46
- return inputs;
47
- }
48
- getOutputDefinitions() {
49
- return [
50
- {
51
- dataType: 'any',
52
- id: 'output',
53
- title: 'Output',
54
- },
55
- ];
56
- }
57
- getEditors() {
58
- return [
59
- {
60
- type: 'toggle',
61
- label: IGNORE_NULL_LABEL,
62
- dataKey: 'ignoreNull',
63
- },
64
- {
65
- type: 'toggle',
66
- label: IGNORE_UNDEFINED_LABEL,
67
- dataKey: 'ignoreUndefined',
68
- },
69
- ];
70
- }
71
- getBody() {
72
- const ignoredValues = [];
73
- if (this.data.ignoreNull) {
74
- ignoredValues.push(IGNORE_NULL_LABEL);
75
- }
76
- if (this.data.ignoreUndefined) {
77
- ignoredValues.push(IGNORE_UNDEFINED_LABEL);
78
- }
79
- return ignoredValues.length > 0 ? ignoredValues.join('\n') : undefined;
80
- }
3
+ import {} from '../NodeImpl.js';
4
+ import {} from '../NodeBase.js';
5
+ import { CoalesceNodeBase, createCoalesceNode } from './CoalesceNodeBase.js';
6
+ /** Display-only label; the persisted node type remains the stable `coalesce`. */
7
+ export const coalesceLegacyDisplayName = 'Coalesce (legacy)';
8
+ /** The persisted `coalesce` type remains available for existing graphs. */
9
+ export class CoalesceNodeImpl extends CoalesceNodeBase {
10
+ includesLegacyConditionalInput = true;
11
+ static create = () => createCoalesceNode('coalesce', coalesceLegacyDisplayName);
81
12
  static getUIData() {
82
13
  return {
83
14
  infoBoxBody: dedent `
84
- Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
15
+ Legacy Coalesce node. Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
85
16
 
86
- Null and undefined input values are emitted by default, but the node can be configured to skip either value and continue checking later inputs.
17
+ Its Conditional input can exclude the node itself. New graphs should use Coalesce instead, which has the same fallback behavior without that port.
87
18
  `,
88
- infoBoxTitle: 'Coalesce Node',
89
- contextMenuTitle: 'Coalesce',
19
+ infoBoxTitle: `${coalesceLegacyDisplayName} Node`,
20
+ contextMenuTitle: coalesceLegacyDisplayName,
90
21
  group: ['Logic'],
91
22
  };
92
23
  }
93
- async process(inputData) {
94
- const conditional = inputData['conditional'];
95
- // This lets the coalesce actually be control-flow-excluded itself, because otherwise
96
- // the input control-flow-excluded are consumed.
97
- if (conditional?.type === 'control-flow-excluded') {
98
- return {
99
- ['output']: {
100
- type: 'control-flow-excluded',
101
- value: undefined,
102
- },
103
- };
104
- }
105
- const inputCount = this.#getInputCountFromValues(inputData);
106
- for (let i = 1; i <= inputCount; i++) {
107
- const inputValue = inputData[`input${i}`];
108
- if (inputValue && inputValue.type !== 'control-flow-excluded' && !this.#shouldSkipInputValue(inputValue)) {
109
- return {
110
- ['output']: inputValue,
111
- };
112
- }
113
- }
114
- return {
115
- ['output']: {
116
- type: 'control-flow-excluded',
117
- value: undefined,
118
- },
119
- };
120
- }
121
- #getInputCountFromValues(inputData) {
122
- let maxInputNumber = 0;
123
- for (const inputId of Object.keys(inputData)) {
124
- const inputNumber = this.#getInputPortNumber(inputId);
125
- if (inputNumber && inputNumber > maxInputNumber) {
126
- maxInputNumber = inputNumber;
127
- }
128
- }
129
- return maxInputNumber;
130
- }
131
- #getInputPortNumber(inputId) {
132
- const match = INPUT_PORT_ID_PATTERN.exec(inputId);
133
- if (!match) {
134
- return undefined;
135
- }
136
- const inputNumber = Number(match[1]);
137
- return Number.isSafeInteger(inputNumber) && inputNumber > 0 ? inputNumber : undefined;
138
- }
139
- #shouldSkipInputValue(inputValue) {
140
- const value = unwrapDataValue(inputValue).value;
141
- return ((this.data.ignoreNull === true && value === null) || (this.data.ignoreUndefined === true && value === undefined));
142
- }
143
24
  }
144
- export const coalesceNode = nodeDefinition(CoalesceNodeImpl, 'Coalesce');
25
+ export {} from './CoalesceNodeBase.js';
26
+ export const coalesceNode = nodeDefinition(CoalesceNodeImpl, coalesceLegacyDisplayName);
@@ -0,0 +1,131 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { unwrapDataValue } from '../DataValue.js';
3
+ import {} from '../EditorDefinition.js';
4
+ import {} from '../GraphProcessor.js';
5
+ import { NodeImpl } from '../NodeImpl.js';
6
+ import {} from '../NodeBase.js';
7
+ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
8
+ const INPUT_PORT_ID_PATTERN = /^input(\d+)$/;
9
+ const IGNORE_NULL_LABEL = "Ignore 'null'";
10
+ const IGNORE_UNDEFINED_LABEL = "Ignore 'undefined'";
11
+ export function createCoalesceNode(type, title) {
12
+ return {
13
+ type,
14
+ title,
15
+ id: nanoid(),
16
+ data: {
17
+ ignoreNull: false,
18
+ ignoreUndefined: false,
19
+ },
20
+ visualData: {
21
+ x: 0,
22
+ y: 0,
23
+ width: 190,
24
+ },
25
+ };
26
+ }
27
+ /** Shared fallback behavior for the current and compatibility Coalesce nodes. */
28
+ export class CoalesceNodeBase extends NodeImpl {
29
+ getInputDefinitions(connections) {
30
+ const inputs = [];
31
+ const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'strict-positive');
32
+ if (this.includesLegacyConditionalInput) {
33
+ inputs.push({
34
+ dataType: 'boolean',
35
+ id: 'conditional',
36
+ title: 'Conditional',
37
+ });
38
+ }
39
+ for (let i = 1; i <= inputCount; i++) {
40
+ inputs.push({
41
+ dataType: 'any',
42
+ id: `input${i}`,
43
+ title: `Input ${i}`,
44
+ });
45
+ }
46
+ return inputs;
47
+ }
48
+ getOutputDefinitions() {
49
+ return [
50
+ {
51
+ dataType: 'any',
52
+ id: 'output',
53
+ title: 'Output',
54
+ },
55
+ ];
56
+ }
57
+ getEditors() {
58
+ return [
59
+ {
60
+ type: 'toggle',
61
+ label: IGNORE_NULL_LABEL,
62
+ dataKey: 'ignoreNull',
63
+ },
64
+ {
65
+ type: 'toggle',
66
+ label: IGNORE_UNDEFINED_LABEL,
67
+ dataKey: 'ignoreUndefined',
68
+ },
69
+ ];
70
+ }
71
+ getBody() {
72
+ const ignoredValues = [];
73
+ if (this.data.ignoreNull) {
74
+ ignoredValues.push(IGNORE_NULL_LABEL);
75
+ }
76
+ if (this.data.ignoreUndefined) {
77
+ ignoredValues.push(IGNORE_UNDEFINED_LABEL);
78
+ }
79
+ return ignoredValues.length > 0 ? ignoredValues.join('\n') : undefined;
80
+ }
81
+ async process(inputData) {
82
+ const conditional = inputData['conditional'];
83
+ // Only the legacy dedicated port gates fallback selection here.
84
+ // The processor handles the standard If option for both node types.
85
+ if (this.includesLegacyConditionalInput && conditional?.type === 'control-flow-excluded') {
86
+ return {
87
+ ['output']: {
88
+ type: 'control-flow-excluded',
89
+ value: undefined,
90
+ },
91
+ };
92
+ }
93
+ const inputCount = this.#getInputCountFromValues(inputData);
94
+ for (let i = 1; i <= inputCount; i++) {
95
+ const inputValue = inputData[`input${i}`];
96
+ if (inputValue && inputValue.type !== 'control-flow-excluded' && !this.#shouldSkipInputValue(inputValue)) {
97
+ return {
98
+ ['output']: inputValue,
99
+ };
100
+ }
101
+ }
102
+ return {
103
+ ['output']: {
104
+ type: 'control-flow-excluded',
105
+ value: undefined,
106
+ },
107
+ };
108
+ }
109
+ #getInputCountFromValues(inputData) {
110
+ let maxInputNumber = 0;
111
+ for (const inputId of Object.keys(inputData)) {
112
+ const inputNumber = this.#getInputPortNumber(inputId);
113
+ if (inputNumber && inputNumber > maxInputNumber) {
114
+ maxInputNumber = inputNumber;
115
+ }
116
+ }
117
+ return maxInputNumber;
118
+ }
119
+ #getInputPortNumber(inputId) {
120
+ const match = INPUT_PORT_ID_PATTERN.exec(inputId);
121
+ if (!match) {
122
+ return undefined;
123
+ }
124
+ const inputNumber = Number(match[1]);
125
+ return Number.isSafeInteger(inputNumber) && inputNumber > 0 ? inputNumber : undefined;
126
+ }
127
+ #shouldSkipInputValue(inputValue) {
128
+ const value = unwrapDataValue(inputValue).value;
129
+ return ((this.data.ignoreNull === true && value === null) || (this.data.ignoreUndefined === true && value === undefined));
130
+ }
131
+ }
@@ -0,0 +1,42 @@
1
+ import { NodeImpl } from '../NodeImpl.js';
2
+ import { nodeDefinition } from '../NodeDefinition.js';
3
+ import { newId } from '../../utils/index.js';
4
+ export class GraphCallPathNodeImpl extends NodeImpl {
5
+ static create() {
6
+ return {
7
+ id: newId(),
8
+ type: 'graphCallPath',
9
+ title: 'Graph Call Path',
10
+ visualData: { x: 0, y: 0, width: 250 },
11
+ data: {},
12
+ };
13
+ }
14
+ getInputDefinitions() {
15
+ return [];
16
+ }
17
+ getOutputDefinitions() {
18
+ return [
19
+ { id: 'currentGraphName', title: 'Current Graph Name', dataType: 'string' },
20
+ { id: 'graphPath', title: 'Graph Path', dataType: 'string[]' },
21
+ ];
22
+ }
23
+ getEditors() {
24
+ return [];
25
+ }
26
+ static getUIData() {
27
+ return {
28
+ contextMenuTitle: 'Graph Call Path',
29
+ infoBoxTitle: 'Graph Call Path',
30
+ infoBoxBody: 'Returns the current graph name and the names of graph calls from the entry graph to this graph. Internal async and streaming branches do not add a graph hop.',
31
+ group: ['Debug'],
32
+ };
33
+ }
34
+ async process(_inputs, context) {
35
+ const graphPath = [...context.graphCallPath];
36
+ return {
37
+ ['currentGraphName']: { type: 'string', value: graphPath.at(-1) ?? '(Unnamed Graph)' },
38
+ ['graphPath']: { type: 'string[]', value: graphPath },
39
+ };
40
+ }
41
+ }
42
+ export const graphCallPathNode = nodeDefinition(GraphCallPathNodeImpl, 'Graph Call Path');
@@ -27,6 +27,8 @@ export class StopWatchingStreamingOutputNodeImpl extends NodeImpl {
27
27
  Accepts a value from a Watch Streaming Output branch, stops future streaming
28
28
  snapshots, and lets its completed output continue through the ordinary graph.
29
29
  In parallel mode, the first completed branch to reach this node wins.
30
+ If the stream ends without a value reaching this node, it is shown as Not ran
31
+ and its ordinary downstream nodes receive the usual excluded value.
30
32
  `,
31
33
  };
32
34
  }
@@ -14,8 +14,7 @@ import { coercePromptToChatMessages } from '../../../model/chat/chatMessages.js'
14
14
  import { clampMaxTokensToModelLimit, setRequestAndResponseTokenOutputs } from '../../../model/chat/tokenBudget.js';
15
15
  import { createAssistantMessagesOutput } from '../../../model/chat/streamChatResponse.js';
16
16
  import { logRuntimeDebug, summarizeErrorForLog } from '../../../utils/runtimeLogging.js';
17
- // Temporary
18
- const cache = new Map();
17
+ import { resolveLegacyChatEditorCache, writeLegacyChatEditorCache } from '../../../model/LegacyChatEditorCache.js';
19
18
  export const ChatAnthropicNodeImpl = {
20
19
  create() {
21
20
  const chartNode = {
@@ -260,8 +259,9 @@ export const ChatAnthropicNodeImpl = {
260
259
  editors: [
261
260
  {
262
261
  type: 'toggle',
263
- label: 'Cache (same inputs, same outputs)',
262
+ label: 'Cache outputs (editor only)',
264
263
  dataKey: 'cache',
264
+ helperMessage: 'Reuses a matching ordinary chat response while this project remains open. Tool-capable requests always run normally.',
265
265
  },
266
266
  {
267
267
  type: 'toggle',
@@ -374,6 +374,10 @@ export const ChatAnthropicNodeImpl = {
374
374
  ...context.settings.chatNodeHeaders,
375
375
  ...additionalHeaders,
376
376
  });
377
+ const apiKey = context.getPluginConfig('anthropicApiKey');
378
+ const defaultApiEndpoint = context.getPluginConfig('anthropicApiEndpoint') || 'https://api.anthropic.com/v1';
379
+ const configuredEndpoint = getInputOrData(data, inputs, 'endpoint');
380
+ const apiEndpoint = configuredEndpoint?.trim() ? configuredEndpoint : defaultApiEndpoint;
377
381
  try {
378
382
  return await retry(async () => {
379
383
  const completionOptions = {
@@ -396,19 +400,17 @@ export const ChatAnthropicNodeImpl = {
396
400
  ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }))
397
401
  : undefined,
398
402
  };
399
- const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);
400
- if (data.cache) {
401
- const cached = cache.get(cacheKey);
402
- if (cached) {
403
- context.markResultAsEditorCacheHit?.();
404
- return cached;
405
- }
403
+ const { cache, cachedOutputs } = resolveLegacyChatEditorCache({
404
+ context,
405
+ enabled: data.cache && !data.enableToolUse,
406
+ providerIdentity: { apiEndpoint, apiKey, headers: allAdditionalHeaders },
407
+ request: useMessageApi ? messageOptions : completionOptions,
408
+ });
409
+ if (cachedOutputs != null) {
410
+ context.markResultAsEditorCacheHit?.();
411
+ return cachedOutputs;
406
412
  }
407
413
  const startTime = Date.now();
408
- const apiKey = context.getPluginConfig('anthropicApiKey');
409
- const defaultApiEndpoint = context.getPluginConfig('anthropicApiEndpoint') || 'https://api.anthropic.com/v1';
410
- const configuredEndpoint = getInputOrData(data, inputs, 'endpoint');
411
- const apiEndpoint = configuredEndpoint?.trim() ? configuredEndpoint : defaultApiEndpoint;
412
414
  if (useMessageApi) {
413
415
  // Use the messages API for Claude 3 models
414
416
  const chunks = streamMessageApi({
@@ -580,7 +582,7 @@ export const ChatAnthropicNodeImpl = {
580
582
  const duration = endTime - startTime;
581
583
  output['duration'] = { type: 'number', value: duration };
582
584
  Object.freeze(output);
583
- cache.set(cacheKey, output);
585
+ writeLegacyChatEditorCache(cache, output);
584
586
  return output;
585
587
  }, {
586
588
  forever: true,
@@ -1,84 +1,4 @@
1
- import {} from '@google/genai';
2
- export const googleModelsDeprecated = {
3
- 'gemini-pro': {
4
- maxTokens: 32760,
5
- cost: {
6
- prompt: NaN,
7
- completion: NaN,
8
- },
9
- displayName: 'Gemini Pro',
10
- },
11
- 'gemini-pro-vision': {
12
- maxTokens: 16384,
13
- cost: {
14
- prompt: NaN,
15
- completion: NaN,
16
- },
17
- displayName: 'Gemini Pro Vision',
18
- },
19
- };
20
- export const generativeAiGoogleModels = {
21
- 'gemini-2.5-pro': {
22
- maxTokens: 1048576,
23
- cost: {
24
- prompt: 1.25 / 1000, // <= 200k tokens, > 200k tokens is 2.5 / 1000
25
- completion: 10 / 1000, // <= 200k tokens, > 200k tokens is 15 / 1000
26
- },
27
- displayName: 'Gemini 2.5 Pro',
28
- },
29
- 'gemini-2.5-flash': {
30
- maxTokens: 1048576,
31
- cost: {
32
- prompt: 0.3 / 1000,
33
- completion: 2.5 / 1000,
34
- },
35
- displayName: 'Gemini 2.5 Flash',
36
- },
37
- 'gemini-2.5-flash-lite-preview-06-17': {
38
- maxTokens: 1000000,
39
- cost: {
40
- prompt: 0.1 / 1000,
41
- completion: 0.4 / 1000,
42
- },
43
- displayName: 'Gemini 2.5 Flash Lite Preview',
44
- },
45
- 'gemini-2.0-flash': {
46
- maxTokens: 1048576,
47
- cost: {
48
- prompt: 0.1 / 1000,
49
- completion: 0.4 / 1000,
50
- },
51
- displayName: 'Gemini 2.0 Flash',
52
- },
53
- 'gemini-2.0-flash-lite': {
54
- maxTokens: 1048576,
55
- cost: {
56
- prompt: 0.075 / 1000,
57
- completion: 0.3 / 1000,
58
- },
59
- displayName: 'Gemini 2.0 Flash Lite',
60
- },
61
- 'gemini-1.5-pro': {
62
- maxTokens: 2097152,
63
- displayName: 'Gemini 1.5 Pro',
64
- // The retained legacy model stays selectable, but its old catalog did not
65
- // carry a reliable token rate. Do not turn that absence into a false $0.
66
- pricing: 'unpriced',
67
- },
68
- 'gemini-1.5-flash': {
69
- maxTokens: 1048576,
70
- displayName: 'Gemini 1.5 Flash',
71
- pricing: 'unpriced',
72
- },
73
- };
74
- export const googleModelOptionsDeprecated = Object.entries(googleModelsDeprecated).map(([id, { displayName }]) => ({
75
- value: id,
76
- label: displayName,
77
- }));
78
- export const generativeAiOptions = Object.entries(generativeAiGoogleModels).map(([id, { displayName }]) => ({
79
- value: id,
80
- label: displayName,
81
- }));
1
+ export { generativeAiGoogleModels, generativeAiOptions, googleModelOptionsDeprecated, googleModelsDeprecated, streamGenerativeAi, } from './googleGenerativeAi.js';
82
2
  export function getVertexGenerativeModelOptions(options) {
83
3
  return {
84
4
  model: options.model,
@@ -91,56 +11,16 @@ export function getVertexGenerativeModelOptions(options) {
91
11
  },
92
12
  };
93
13
  }
94
- export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt, maxOutputTokens, temperature, topP, topK, signal, tools, thinkingBudget, additionalHeaders, }) {
95
- const { GoogleGenAI } = await import('@google/genai');
96
- const genAi = new GoogleGenAI({ apiKey });
97
- const result = await genAi.models.generateContentStream({
98
- model,
99
- contents: prompt,
100
- config: {
101
- systemInstruction: systemPrompt,
102
- maxOutputTokens,
103
- temperature,
104
- topP,
105
- topK,
106
- tools,
107
- abortSignal: signal,
108
- thinkingConfig: {
109
- thinkingBudget,
110
- },
111
- httpOptions: {
112
- headers: {
113
- ...additionalHeaders,
114
- },
115
- },
116
- },
117
- });
118
- for await (const chunk of result) {
119
- const outChunk = {
120
- completion: undefined,
121
- finish_reason: undefined,
122
- function_calls: undefined,
123
- model,
124
- };
125
- const functionCalls = chunk.functionCalls;
126
- if (functionCalls) {
127
- outChunk.function_calls = functionCalls;
128
- }
129
- if (chunk.candidates) {
130
- outChunk.completion = chunk.candidates[0]?.content?.parts?.[0]?.text;
131
- outChunk.finish_reason = chunk.candidates[0]?.finishReason;
132
- }
133
- if (outChunk.completion || outChunk.function_calls) {
134
- yield outChunk;
135
- }
136
- }
137
- }
138
14
  export async function* streamChatCompletions({ project, location, applicationCredentials, model, signal, max_output_tokens, temperature, top_p, top_k, systemPrompt, prompt, }) {
139
15
  // Dynamic import: the Google auth library fails under static CJS require.
140
16
  const { VertexAI } = await import('@google-cloud/vertexai');
141
- // Can't find a way to pass the credentials path in
142
- process.env.GOOGLE_APPLICATION_CREDENTIALS = applicationCredentials;
143
- const vertexAi = new VertexAI({ project, location });
17
+ // Keep the credential path on this client. Writing GOOGLE_APPLICATION_CREDENTIALS
18
+ // would let concurrent legacy Vertex runs overwrite each other's identity.
19
+ const vertexAi = new VertexAI({
20
+ project,
21
+ location,
22
+ googleAuthOptions: { keyFilename: applicationCredentials },
23
+ });
144
24
  const generativeModel = vertexAi.preview.getGenerativeModel(getVertexGenerativeModelOptions({
145
25
  model,
146
26
  systemPrompt,
@@ -0,0 +1,101 @@
1
+ import {} from '@google/genai';
2
+ export const googleModelsDeprecated = {
3
+ 'gemini-pro': {
4
+ maxTokens: 32760,
5
+ cost: { prompt: NaN, completion: NaN },
6
+ displayName: 'Gemini Pro',
7
+ },
8
+ 'gemini-pro-vision': {
9
+ maxTokens: 16384,
10
+ cost: { prompt: NaN, completion: NaN },
11
+ displayName: 'Gemini Pro Vision',
12
+ },
13
+ };
14
+ export const generativeAiGoogleModels = {
15
+ 'gemini-2.5-pro': {
16
+ maxTokens: 1048576,
17
+ cost: {
18
+ prompt: 1.25 / 1000, // <= 200k tokens, > 200k tokens is 2.5 / 1000
19
+ completion: 10 / 1000, // <= 200k tokens, > 200k tokens is 15 / 1000
20
+ },
21
+ displayName: 'Gemini 2.5 Pro',
22
+ },
23
+ 'gemini-2.5-flash': {
24
+ maxTokens: 1048576,
25
+ cost: { prompt: 0.3 / 1000, completion: 2.5 / 1000 },
26
+ displayName: 'Gemini 2.5 Flash',
27
+ },
28
+ 'gemini-2.5-flash-lite-preview-06-17': {
29
+ maxTokens: 1000000,
30
+ cost: { prompt: 0.1 / 1000, completion: 0.4 / 1000 },
31
+ displayName: 'Gemini 2.5 Flash Lite Preview',
32
+ },
33
+ 'gemini-2.0-flash': {
34
+ maxTokens: 1048576,
35
+ cost: { prompt: 0.1 / 1000, completion: 0.4 / 1000 },
36
+ displayName: 'Gemini 2.0 Flash',
37
+ },
38
+ 'gemini-2.0-flash-lite': {
39
+ maxTokens: 1048576,
40
+ cost: { prompt: 0.075 / 1000, completion: 0.3 / 1000 },
41
+ displayName: 'Gemini 2.0 Flash Lite',
42
+ },
43
+ 'gemini-1.5-pro': {
44
+ maxTokens: 2097152,
45
+ displayName: 'Gemini 1.5 Pro',
46
+ // The retained legacy model stays selectable, but its old catalog did not
47
+ // carry a reliable token rate. Do not turn that absence into a false $0.
48
+ pricing: 'unpriced',
49
+ },
50
+ 'gemini-1.5-flash': {
51
+ maxTokens: 1048576,
52
+ displayName: 'Gemini 1.5 Flash',
53
+ pricing: 'unpriced',
54
+ },
55
+ };
56
+ export const googleModelOptionsDeprecated = Object.entries(googleModelsDeprecated).map(([id, { displayName }]) => ({
57
+ value: id,
58
+ label: displayName,
59
+ }));
60
+ export const generativeAiOptions = Object.entries(generativeAiGoogleModels).map(([id, { displayName }]) => ({
61
+ value: id,
62
+ label: displayName,
63
+ }));
64
+ export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt, maxOutputTokens, temperature, topP, topK, signal, tools, thinkingBudget, additionalHeaders, }) {
65
+ const { GoogleGenAI } = await import('@google/genai');
66
+ const genAi = new GoogleGenAI({ apiKey });
67
+ const result = await genAi.models.generateContentStream({
68
+ model,
69
+ contents: prompt,
70
+ config: {
71
+ systemInstruction: systemPrompt,
72
+ maxOutputTokens,
73
+ temperature,
74
+ topP,
75
+ topK,
76
+ tools,
77
+ abortSignal: signal,
78
+ thinkingConfig: { thinkingBudget },
79
+ httpOptions: { headers: { ...additionalHeaders } },
80
+ },
81
+ });
82
+ for await (const chunk of result) {
83
+ const outChunk = {
84
+ completion: undefined,
85
+ finish_reason: undefined,
86
+ function_calls: undefined,
87
+ model,
88
+ };
89
+ const functionCalls = chunk.functionCalls;
90
+ if (functionCalls) {
91
+ outChunk.function_calls = functionCalls;
92
+ }
93
+ if (chunk.candidates) {
94
+ outChunk.completion = chunk.candidates[0]?.content?.parts?.[0]?.text;
95
+ outChunk.finish_reason = chunk.candidates[0]?.finishReason;
96
+ }
97
+ if (outChunk.completion || outChunk.function_calls) {
98
+ yield outChunk;
99
+ }
100
+ }
101
+ }