langchain 0.0.197-rc.1 → 0.0.198

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 (92) hide show
  1. package/dist/chains/openai_moderation.cjs +2 -2
  2. package/dist/chains/openai_moderation.d.ts +1 -1
  3. package/dist/chains/openai_moderation.js +1 -1
  4. package/dist/chat_models/anthropic.cjs +351 -15
  5. package/dist/chat_models/anthropic.d.ts +157 -1
  6. package/dist/chat_models/anthropic.js +348 -1
  7. package/dist/chat_models/cloudflare_workersai.cjs +5 -0
  8. package/dist/chat_models/cloudflare_workersai.d.ts +3 -0
  9. package/dist/chat_models/cloudflare_workersai.js +5 -0
  10. package/dist/chat_models/fireworks.d.ts +1 -1
  11. package/dist/chat_models/iflytek_xinghuo/common.d.ts +1 -1
  12. package/dist/chat_models/llama_cpp.cjs +24 -0
  13. package/dist/chat_models/llama_cpp.d.ts +3 -1
  14. package/dist/chat_models/llama_cpp.js +24 -0
  15. package/dist/chat_models/minimax.d.ts +1 -1
  16. package/dist/chat_models/openai.cjs +698 -4
  17. package/dist/chat_models/openai.d.ts +137 -4
  18. package/dist/chat_models/openai.js +695 -2
  19. package/dist/document_loaders/fs/openai_whisper_audio.cjs +2 -2
  20. package/dist/document_loaders/fs/openai_whisper_audio.d.ts +1 -1
  21. package/dist/document_loaders/fs/openai_whisper_audio.js +1 -1
  22. package/dist/document_loaders/fs/pptx.cjs +39 -0
  23. package/dist/document_loaders/fs/pptx.d.ts +23 -0
  24. package/dist/document_loaders/fs/pptx.js +35 -0
  25. package/dist/embeddings/openai.cjs +240 -2
  26. package/dist/embeddings/openai.d.ts +82 -1
  27. package/dist/embeddings/openai.js +239 -1
  28. package/dist/experimental/openai_assistant/index.cjs +35 -3
  29. package/dist/experimental/openai_assistant/index.d.ts +27 -1
  30. package/dist/experimental/openai_assistant/index.js +33 -1
  31. package/dist/experimental/openai_assistant/schema.d.ts +1 -1
  32. package/dist/experimental/openai_files/index.cjs +2 -2
  33. package/dist/experimental/openai_files/index.d.ts +1 -1
  34. package/dist/experimental/openai_files/index.js +1 -1
  35. package/dist/experimental/tools/pyinterpreter.cjs +248 -0
  36. package/dist/experimental/tools/pyinterpreter.d.ts +18 -0
  37. package/dist/experimental/tools/pyinterpreter.js +244 -0
  38. package/dist/graphs/neo4j_graph.cjs +49 -14
  39. package/dist/graphs/neo4j_graph.d.ts +30 -0
  40. package/dist/graphs/neo4j_graph.js +49 -14
  41. package/dist/llms/fireworks.d.ts +1 -1
  42. package/dist/llms/hf.cjs +13 -2
  43. package/dist/llms/hf.d.ts +5 -0
  44. package/dist/llms/hf.js +13 -2
  45. package/dist/llms/llama_cpp.cjs +17 -3
  46. package/dist/llms/llama_cpp.d.ts +4 -1
  47. package/dist/llms/llama_cpp.js +17 -3
  48. package/dist/llms/openai-chat.cjs +445 -3
  49. package/dist/llms/openai-chat.d.ts +123 -4
  50. package/dist/llms/openai-chat.js +443 -2
  51. package/dist/llms/openai.cjs +530 -6
  52. package/dist/llms/openai.d.ts +123 -4
  53. package/dist/llms/openai.js +525 -2
  54. package/dist/load/import_constants.cjs +3 -0
  55. package/dist/load/import_constants.js +3 -0
  56. package/dist/output_parsers/json.cjs +4 -0
  57. package/dist/output_parsers/json.js +4 -0
  58. package/dist/schema/index.d.ts +1 -1
  59. package/dist/tools/convert_to_openai.cjs +38 -4
  60. package/dist/tools/convert_to_openai.d.ts +11 -1
  61. package/dist/tools/convert_to_openai.js +35 -1
  62. package/dist/types/openai-types.d.ts +133 -1
  63. package/dist/util/env.cjs +9 -70
  64. package/dist/util/env.d.ts +1 -21
  65. package/dist/util/env.js +1 -62
  66. package/dist/util/openai-format-fndef.cjs +81 -0
  67. package/dist/util/openai-format-fndef.d.ts +44 -0
  68. package/dist/util/openai-format-fndef.js +77 -0
  69. package/dist/util/openai.cjs +18 -2
  70. package/dist/util/openai.d.ts +1 -1
  71. package/dist/util/openai.js +17 -1
  72. package/dist/util/openapi.d.ts +2 -2
  73. package/dist/util/prompt-layer.d.ts +1 -1
  74. package/dist/vectorstores/clickhouse.cjs +286 -0
  75. package/dist/vectorstores/clickhouse.d.ts +126 -0
  76. package/dist/vectorstores/clickhouse.js +259 -0
  77. package/dist/vectorstores/pgvector.cjs +142 -18
  78. package/dist/vectorstores/pgvector.d.ts +21 -0
  79. package/dist/vectorstores/pgvector.js +142 -18
  80. package/dist/vectorstores/weaviate.cjs +45 -2
  81. package/dist/vectorstores/weaviate.d.ts +27 -1
  82. package/dist/vectorstores/weaviate.js +45 -2
  83. package/document_loaders/fs/pptx.cjs +1 -0
  84. package/document_loaders/fs/pptx.d.ts +1 -0
  85. package/document_loaders/fs/pptx.js +1 -0
  86. package/experimental/tools/pyinterpreter.cjs +1 -0
  87. package/experimental/tools/pyinterpreter.d.ts +1 -0
  88. package/experimental/tools/pyinterpreter.js +1 -0
  89. package/package.json +41 -9
  90. package/vectorstores/clickhouse.cjs +1 -0
  91. package/vectorstores/clickhouse.d.ts +1 -0
  92. package/vectorstores/clickhouse.js +1 -0
@@ -0,0 +1,18 @@
1
+ import { loadPyodide, type PyodideInterface } from "pyodide";
2
+ import { Tool, ToolParams } from "../../tools/base.js";
3
+ export type PythonInterpreterToolParams = Parameters<typeof loadPyodide>[0] & ToolParams & {
4
+ instance: PyodideInterface;
5
+ };
6
+ export declare class PythonInterpreterTool extends Tool {
7
+ static lc_name(): string;
8
+ name: string;
9
+ description: string;
10
+ pyodideInstance: PyodideInterface;
11
+ stdout: string;
12
+ stderr: string;
13
+ constructor(options: PythonInterpreterToolParams);
14
+ addPackage(packageName: string): Promise<void>;
15
+ get availableDefaultPackages(): string;
16
+ static initialize(options: Omit<PythonInterpreterToolParams, "instance">): Promise<PythonInterpreterTool>;
17
+ _call(script: string): Promise<string>;
18
+ }
@@ -0,0 +1,244 @@
1
+ import { loadPyodide } from "pyodide";
2
+ import { Tool } from "../../tools/base.js";
3
+ export class PythonInterpreterTool extends Tool {
4
+ static lc_name() {
5
+ return "PythonInterpreterTool";
6
+ }
7
+ constructor(options) {
8
+ super(options);
9
+ Object.defineProperty(this, "name", {
10
+ enumerable: true,
11
+ configurable: true,
12
+ writable: true,
13
+ value: "python_interpreter"
14
+ });
15
+ Object.defineProperty(this, "description", {
16
+ enumerable: true,
17
+ configurable: true,
18
+ writable: true,
19
+ value: `Evaluates python code in a sandbox environment. The environment resets on every execution. You must send the whole script every time and print your outputs. Script should be pure python code that can be evaluated. Packages available:
20
+ ${this.availableDefaultPackages}`
21
+ });
22
+ Object.defineProperty(this, "pyodideInstance", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: void 0
27
+ });
28
+ Object.defineProperty(this, "stdout", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: ""
33
+ });
34
+ Object.defineProperty(this, "stderr", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: ""
39
+ });
40
+ this.pyodideInstance = options.instance;
41
+ this.pyodideInstance.setStderr({
42
+ batched: (text) => {
43
+ this.stderr += text;
44
+ },
45
+ });
46
+ this.pyodideInstance.setStdout({
47
+ batched: (text) => {
48
+ this.stdout += text;
49
+ },
50
+ });
51
+ }
52
+ async addPackage(packageName) {
53
+ await this.pyodideInstance.loadPackage(packageName);
54
+ this.description += `, ${packageName}`;
55
+ }
56
+ get availableDefaultPackages() {
57
+ return [
58
+ "asciitree",
59
+ "astropy",
60
+ "atomicwrites",
61
+ "attrs",
62
+ "autograd",
63
+ "awkward-cpp",
64
+ "bcrypt",
65
+ "beautifulsoup4",
66
+ "biopython",
67
+ "bitarray",
68
+ "bitstring",
69
+ "bleach",
70
+ "bokeh",
71
+ "boost-histogram",
72
+ "brotli",
73
+ "cachetools",
74
+ "Cartopy",
75
+ "cbor-diag",
76
+ "certifi",
77
+ "cffi",
78
+ "cffi_example",
79
+ "cftime",
80
+ "click",
81
+ "cligj",
82
+ "cloudpickle",
83
+ "cmyt",
84
+ "colorspacious",
85
+ "contourpy",
86
+ "coolprop",
87
+ "coverage",
88
+ "cramjam",
89
+ "cryptography",
90
+ "cssselect",
91
+ "cycler",
92
+ "cytoolz",
93
+ "decorator",
94
+ "demes",
95
+ "deprecation",
96
+ "distlib",
97
+ "docutils",
98
+ "exceptiongroup",
99
+ "fastparquet",
100
+ "fiona",
101
+ "fonttools",
102
+ "freesasa",
103
+ "fsspec",
104
+ "future",
105
+ "galpy",
106
+ "gensim",
107
+ "geopandas",
108
+ "gmpy2",
109
+ "gsw",
110
+ "h5py",
111
+ "html5lib",
112
+ "idna",
113
+ "igraph",
114
+ "imageio",
115
+ "iniconfig",
116
+ "jedi",
117
+ "Jinja2",
118
+ "joblib",
119
+ "jsonschema",
120
+ "kiwisolver",
121
+ "lazy-object-proxy",
122
+ "lazy_loader",
123
+ "lightgbm",
124
+ "logbook",
125
+ "lxml",
126
+ "MarkupSafe",
127
+ "matplotlib",
128
+ "matplotlib-pyodide",
129
+ "micropip",
130
+ "mne",
131
+ "more-itertools",
132
+ "mpmath",
133
+ "msgpack",
134
+ "msprime",
135
+ "multidict",
136
+ "munch",
137
+ "mypy",
138
+ "netcdf4",
139
+ "networkx",
140
+ "newick",
141
+ "nlopt",
142
+ "nltk",
143
+ "nose",
144
+ "numcodecs",
145
+ "numpy",
146
+ "opencv-python",
147
+ "optlang",
148
+ "orjson",
149
+ "packaging",
150
+ "pandas",
151
+ "parso",
152
+ "patsy",
153
+ "peewee",
154
+ "Pillow",
155
+ "pillow_heif",
156
+ "pkgconfig",
157
+ "pluggy",
158
+ "protobuf",
159
+ "py",
160
+ "pyb2d",
161
+ "pyclipper",
162
+ "pycparser",
163
+ "pycryptodome",
164
+ "pydantic",
165
+ "pyerfa",
166
+ "Pygments",
167
+ "pyheif",
168
+ "pyinstrument",
169
+ "pynacl",
170
+ "pyodide-http",
171
+ "pyodide-tblib",
172
+ "pyparsing",
173
+ "pyproj",
174
+ "pyrsistent",
175
+ "pyshp",
176
+ "pytest",
177
+ "pytest-benchmark",
178
+ "python-dateutil",
179
+ "python-magic",
180
+ "python-sat",
181
+ "python_solvespace",
182
+ "pytz",
183
+ "pywavelets",
184
+ "pyxel",
185
+ "pyyaml",
186
+ "rebound",
187
+ "reboundx",
188
+ "regex",
189
+ "retrying",
190
+ "RobotRaconteur",
191
+ "ruamel.yaml",
192
+ "rust-panic-test",
193
+ "scikit-image",
194
+ "scikit-learn",
195
+ "scipy",
196
+ "screed",
197
+ "setuptools",
198
+ "shapely",
199
+ "simplejson",
200
+ "six",
201
+ "smart_open",
202
+ "soupsieve",
203
+ "sourmash",
204
+ "sparseqr",
205
+ "sqlalchemy",
206
+ "statsmodels",
207
+ "svgwrite",
208
+ "swiglpk",
209
+ "sympy",
210
+ "termcolor",
211
+ "texttable",
212
+ "threadpoolctl",
213
+ "tomli",
214
+ "tomli-w",
215
+ "toolz",
216
+ "tqdm",
217
+ "traits",
218
+ "tskit",
219
+ "typing-extensions",
220
+ "uncertainties",
221
+ "unyt",
222
+ "webencodings",
223
+ "wordcloud",
224
+ "wrapt",
225
+ "xarray",
226
+ "xgboost",
227
+ "xlrd",
228
+ "xyzservices",
229
+ "yarl",
230
+ "yt",
231
+ "zarr",
232
+ ].join(", ");
233
+ }
234
+ static async initialize(options) {
235
+ const instance = await loadPyodide(options);
236
+ return new this({ ...options, instance });
237
+ }
238
+ async _call(script) {
239
+ this.stdout = "";
240
+ this.stderr = "";
241
+ await this.pyodideInstance.runPythonAsync(script);
242
+ return JSON.stringify({ stdout: this.stdout, stderr: this.stderr });
243
+ }
244
+ }
@@ -59,6 +59,16 @@ class Neo4jGraph {
59
59
  writable: true,
60
60
  value: ""
61
61
  });
62
+ Object.defineProperty(this, "structuredSchema", {
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true,
66
+ value: {
67
+ nodeProps: {},
68
+ relProps: {},
69
+ relationships: [],
70
+ }
71
+ });
62
72
  try {
63
73
  this.driver = neo4j_driver_1.default.driver(url, neo4j_driver_1.default.auth.basic(username, password));
64
74
  this.database = database;
@@ -96,6 +106,9 @@ class Neo4jGraph {
96
106
  getSchema() {
97
107
  return this.schema;
98
108
  }
109
+ getStructuredSchema() {
110
+ return this.structuredSchema;
111
+ }
99
112
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
100
113
  async query(query, params = {}) {
101
114
  try {
@@ -138,21 +151,43 @@ class Neo4jGraph {
138
151
  YIELD label, other, elementType, type, property
139
152
  WHERE type = "RELATIONSHIP" AND elementType = "node"
140
153
  UNWIND other AS other_node
141
- RETURN "(:" + label + ")-[:" + property + "]->(:" + toString(other_node) + ")" AS output
142
- `;
143
- const nodeProperties = await this.query(nodePropertiesQuery);
144
- const relationshipsProperties = await this.query(relPropertiesQuery);
145
- const relationships = await this.query(relQuery);
146
- this.schema = `
147
- Node properties are the following:
148
- ${JSON.stringify(nodeProperties?.map((el) => el.output))}
149
-
150
- Relationship properties are the following:
151
- ${JSON.stringify(relationshipsProperties?.map((el) => el.output))}
152
-
153
- The relationships are the following:
154
- ${JSON.stringify(relationships?.map((el) => el.output))}
154
+ RETURN {start: label, type: property, end: toString(other_node)} AS output
155
155
  `;
156
+ // Assuming query method is defined and returns a Promise
157
+ const nodeProperties = (await this.query(nodePropertiesQuery))?.map((el) => el.output);
158
+ const relationshipsProperties = (await this.query(relPropertiesQuery))?.map((el) => el.output);
159
+ const relationships = (await this.query(relQuery))?.map((el) => el.output);
160
+ // Structured schema similar to Python's dictionary comprehension
161
+ this.structuredSchema = {
162
+ nodeProps: Object.fromEntries(nodeProperties?.map((el) => [el.labels, el.properties]) || []),
163
+ relProps: Object.fromEntries(relationshipsProperties?.map((el) => [el.type, el.properties]) || []),
164
+ relationships: relationships || [],
165
+ };
166
+ // Format node properties
167
+ const formattedNodeProps = nodeProperties?.map((el) => {
168
+ const propsStr = el.properties
169
+ .map((prop) => `${prop.property}: ${prop.type}`)
170
+ .join(", ");
171
+ return `${el.labels} {${propsStr}}`;
172
+ });
173
+ // Format relationship properties
174
+ const formattedRelProps = relationshipsProperties?.map((el) => {
175
+ const propsStr = el.properties
176
+ .map((prop) => `${prop.property}: ${prop.type}`)
177
+ .join(", ");
178
+ return `${el.type} {${propsStr}}`;
179
+ });
180
+ // Format relationships
181
+ const formattedRels = relationships?.map((el) => `(:${el.start})-[:${el.type}]->(:${el.end})`);
182
+ // Combine all formatted elements into a single string
183
+ this.schema = [
184
+ "Node properties are the following:",
185
+ formattedNodeProps?.join(", "),
186
+ "Relationship properties are the following:",
187
+ formattedRelProps?.join(", "),
188
+ "The relationships are the following:",
189
+ formattedRels?.join(", "),
190
+ ].join("\n");
156
191
  }
157
192
  async close() {
158
193
  await this.driver.close();
@@ -4,6 +4,34 @@ interface Neo4jGraphConfig {
4
4
  password: string;
5
5
  database?: string;
6
6
  }
7
+ interface StructuredSchema {
8
+ nodeProps: {
9
+ [key: NodeType["labels"]]: NodeType["properties"];
10
+ };
11
+ relProps: {
12
+ [key: RelType["type"]]: RelType["properties"];
13
+ };
14
+ relationships: PathType[];
15
+ }
16
+ type NodeType = {
17
+ labels: string;
18
+ properties: {
19
+ property: string;
20
+ type: string;
21
+ }[];
22
+ };
23
+ type RelType = {
24
+ type: string;
25
+ properties: {
26
+ property: string;
27
+ type: string;
28
+ }[];
29
+ };
30
+ type PathType = {
31
+ start: string;
32
+ type: string;
33
+ end: string;
34
+ };
7
35
  /**
8
36
  * @security *Security note*: Make sure that the database connection uses credentials
9
37
  * that are narrowly-scoped to only include necessary permissions.
@@ -22,9 +50,11 @@ export declare class Neo4jGraph {
22
50
  private driver;
23
51
  private database;
24
52
  private schema;
53
+ private structuredSchema;
25
54
  constructor({ url, username, password, database, }: Neo4jGraphConfig);
26
55
  static initialize(config: Neo4jGraphConfig): Promise<Neo4jGraph>;
27
56
  getSchema(): string;
57
+ getStructuredSchema(): StructuredSchema;
28
58
  query(query: string, params?: any): Promise<any[] | undefined>;
29
59
  verifyConnectivity(): Promise<void>;
30
60
  refreshSchema(): Promise<void>;
@@ -33,6 +33,16 @@ export class Neo4jGraph {
33
33
  writable: true,
34
34
  value: ""
35
35
  });
36
+ Object.defineProperty(this, "structuredSchema", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: {
41
+ nodeProps: {},
42
+ relProps: {},
43
+ relationships: [],
44
+ }
45
+ });
36
46
  try {
37
47
  this.driver = neo4j.driver(url, neo4j.auth.basic(username, password));
38
48
  this.database = database;
@@ -70,6 +80,9 @@ export class Neo4jGraph {
70
80
  getSchema() {
71
81
  return this.schema;
72
82
  }
83
+ getStructuredSchema() {
84
+ return this.structuredSchema;
85
+ }
73
86
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
87
  async query(query, params = {}) {
75
88
  try {
@@ -112,21 +125,43 @@ export class Neo4jGraph {
112
125
  YIELD label, other, elementType, type, property
113
126
  WHERE type = "RELATIONSHIP" AND elementType = "node"
114
127
  UNWIND other AS other_node
115
- RETURN "(:" + label + ")-[:" + property + "]->(:" + toString(other_node) + ")" AS output
116
- `;
117
- const nodeProperties = await this.query(nodePropertiesQuery);
118
- const relationshipsProperties = await this.query(relPropertiesQuery);
119
- const relationships = await this.query(relQuery);
120
- this.schema = `
121
- Node properties are the following:
122
- ${JSON.stringify(nodeProperties?.map((el) => el.output))}
123
-
124
- Relationship properties are the following:
125
- ${JSON.stringify(relationshipsProperties?.map((el) => el.output))}
126
-
127
- The relationships are the following:
128
- ${JSON.stringify(relationships?.map((el) => el.output))}
128
+ RETURN {start: label, type: property, end: toString(other_node)} AS output
129
129
  `;
130
+ // Assuming query method is defined and returns a Promise
131
+ const nodeProperties = (await this.query(nodePropertiesQuery))?.map((el) => el.output);
132
+ const relationshipsProperties = (await this.query(relPropertiesQuery))?.map((el) => el.output);
133
+ const relationships = (await this.query(relQuery))?.map((el) => el.output);
134
+ // Structured schema similar to Python's dictionary comprehension
135
+ this.structuredSchema = {
136
+ nodeProps: Object.fromEntries(nodeProperties?.map((el) => [el.labels, el.properties]) || []),
137
+ relProps: Object.fromEntries(relationshipsProperties?.map((el) => [el.type, el.properties]) || []),
138
+ relationships: relationships || [],
139
+ };
140
+ // Format node properties
141
+ const formattedNodeProps = nodeProperties?.map((el) => {
142
+ const propsStr = el.properties
143
+ .map((prop) => `${prop.property}: ${prop.type}`)
144
+ .join(", ");
145
+ return `${el.labels} {${propsStr}}`;
146
+ });
147
+ // Format relationship properties
148
+ const formattedRelProps = relationshipsProperties?.map((el) => {
149
+ const propsStr = el.properties
150
+ .map((prop) => `${prop.property}: ${prop.type}`)
151
+ .join(", ");
152
+ return `${el.type} {${propsStr}}`;
153
+ });
154
+ // Format relationships
155
+ const formattedRels = relationships?.map((el) => `(:${el.start})-[:${el.type}]->(:${el.end})`);
156
+ // Combine all formatted elements into a single string
157
+ this.schema = [
158
+ "Node properties are the following:",
159
+ formattedNodeProps?.join(", "),
160
+ "Relationship properties are the following:",
161
+ formattedRelProps?.join(", "),
162
+ "The relationships are the following:",
163
+ formattedRels?.join(", "),
164
+ ].join("\n");
130
165
  }
131
166
  async close() {
132
167
  await this.driver.close();
@@ -1,4 +1,4 @@
1
- import type { OpenAIClient } from "@langchain/openai";
1
+ import type { OpenAI as OpenAIClient } from "openai";
2
2
  import type { BaseLLMParams } from "./base.js";
3
3
  import type { OpenAICallOptions, OpenAIInput } from "./openai.js";
4
4
  import type { OpenAICoreRequestOptions } from "../types/openai-types.js";
package/dist/llms/hf.cjs CHANGED
@@ -76,6 +76,12 @@ class HuggingFaceInference extends base_js_1.LLM {
76
76
  writable: true,
77
77
  value: undefined
78
78
  });
79
+ Object.defineProperty(this, "includeCredentials", {
80
+ enumerable: true,
81
+ configurable: true,
82
+ writable: true,
83
+ value: undefined
84
+ });
79
85
  this.model = fields?.model ?? this.model;
80
86
  this.temperature = fields?.temperature ?? this.temperature;
81
87
  this.maxTokens = fields?.maxTokens ?? this.maxTokens;
@@ -85,6 +91,7 @@ class HuggingFaceInference extends base_js_1.LLM {
85
91
  this.apiKey =
86
92
  fields?.apiKey ?? (0, env_js_1.getEnvironmentVariable)("HUGGINGFACEHUB_API_KEY");
87
93
  this.endpointUrl = fields?.endpointUrl;
94
+ this.includeCredentials = fields?.includeCredentials;
88
95
  if (!this.apiKey) {
89
96
  throw new Error("Please set an API key for HuggingFace Hub in the environment variable HUGGINGFACEHUB_API_KEY or in the apiKey field of the HuggingFaceInference constructor.");
90
97
  }
@@ -96,8 +103,12 @@ class HuggingFaceInference extends base_js_1.LLM {
96
103
  async _call(prompt, options) {
97
104
  const { HfInference } = await HuggingFaceInference.imports();
98
105
  const hf = this.endpointUrl
99
- ? new HfInference(this.apiKey).endpoint(this.endpointUrl)
100
- : new HfInference(this.apiKey);
106
+ ? new HfInference(this.apiKey, {
107
+ includeCredentials: this.includeCredentials,
108
+ }).endpoint(this.endpointUrl)
109
+ : new HfInference(this.apiKey, {
110
+ includeCredentials: this.includeCredentials,
111
+ });
101
112
  const res = await this.caller.callWithOptions({ signal: options.signal }, hf.textGeneration.bind(hf), {
102
113
  model: this.model,
103
114
  parameters: {
package/dist/llms/hf.d.ts CHANGED
@@ -22,6 +22,10 @@ export interface HFInput {
22
22
  frequencyPenalty?: number;
23
23
  /** API key to use. */
24
24
  apiKey?: string;
25
+ /**
26
+ * Credentials to use for the request. If this is a string, it will be passed straight on. If it's a boolean, true will be "include" and false will not send credentials at all.
27
+ */
28
+ includeCredentials?: string | boolean;
25
29
  }
26
30
  /**
27
31
  * Class implementing the Large Language Model (LLM) interface using the
@@ -52,6 +56,7 @@ export declare class HuggingFaceInference extends LLM implements HFInput {
52
56
  frequencyPenalty: number | undefined;
53
57
  apiKey: string | undefined;
54
58
  endpointUrl: string | undefined;
59
+ includeCredentials: string | boolean | undefined;
55
60
  constructor(fields?: Partial<HFInput> & BaseLLMParams);
56
61
  _llmType(): string;
57
62
  /** @ignore */
package/dist/llms/hf.js CHANGED
@@ -73,6 +73,12 @@ export class HuggingFaceInference extends LLM {
73
73
  writable: true,
74
74
  value: undefined
75
75
  });
76
+ Object.defineProperty(this, "includeCredentials", {
77
+ enumerable: true,
78
+ configurable: true,
79
+ writable: true,
80
+ value: undefined
81
+ });
76
82
  this.model = fields?.model ?? this.model;
77
83
  this.temperature = fields?.temperature ?? this.temperature;
78
84
  this.maxTokens = fields?.maxTokens ?? this.maxTokens;
@@ -82,6 +88,7 @@ export class HuggingFaceInference extends LLM {
82
88
  this.apiKey =
83
89
  fields?.apiKey ?? getEnvironmentVariable("HUGGINGFACEHUB_API_KEY");
84
90
  this.endpointUrl = fields?.endpointUrl;
91
+ this.includeCredentials = fields?.includeCredentials;
85
92
  if (!this.apiKey) {
86
93
  throw new Error("Please set an API key for HuggingFace Hub in the environment variable HUGGINGFACEHUB_API_KEY or in the apiKey field of the HuggingFaceInference constructor.");
87
94
  }
@@ -93,8 +100,12 @@ export class HuggingFaceInference extends LLM {
93
100
  async _call(prompt, options) {
94
101
  const { HfInference } = await HuggingFaceInference.imports();
95
102
  const hf = this.endpointUrl
96
- ? new HfInference(this.apiKey).endpoint(this.endpointUrl)
97
- : new HfInference(this.apiKey);
103
+ ? new HfInference(this.apiKey, {
104
+ includeCredentials: this.includeCredentials,
105
+ }).endpoint(this.endpointUrl)
106
+ : new HfInference(this.apiKey, {
107
+ includeCredentials: this.includeCredentials,
108
+ });
98
109
  const res = await this.caller.callWithOptions({ signal: options.signal }, hf.textGeneration.bind(hf), {
99
110
  model: this.model,
100
111
  parameters: {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LlamaCpp = void 0;
4
4
  const llama_cpp_js_1 = require("../util/llama_cpp.cjs");
5
5
  const base_js_1 = require("./base.cjs");
6
+ const index_js_1 = require("../schema/index.cjs");
6
7
  /**
7
8
  * To use this model you need to have the `node-llama-cpp` module installed.
8
9
  * This can be installed using `npm install -S node-llama-cpp` and the minimum
@@ -76,9 +77,7 @@ class LlamaCpp extends base_js_1.LLM {
76
77
  return "llama2_cpp";
77
78
  }
78
79
  /** @ignore */
79
- async _call(prompt,
80
- // @ts-expect-error - TS6133: 'options' is declared but its value is never read.
81
- options) {
80
+ async _call(prompt, _options) {
82
81
  try {
83
82
  const promptOptions = {
84
83
  maxTokens: this?.maxTokens,
@@ -94,5 +93,20 @@ class LlamaCpp extends base_js_1.LLM {
94
93
  throw new Error("Error getting prompt completion.");
95
94
  }
96
95
  }
96
+ async *_streamResponseChunks(prompt, _options, runManager) {
97
+ const promptOptions = {
98
+ temperature: this?.temperature,
99
+ topK: this?.topK,
100
+ topP: this?.topP,
101
+ };
102
+ const stream = await this.caller.call(async () => this._context.evaluate(this._context.encode(prompt), promptOptions));
103
+ for await (const chunk of stream) {
104
+ yield new index_js_1.GenerationChunk({
105
+ text: this._context.decode([chunk]),
106
+ generationInfo: {},
107
+ });
108
+ await runManager?.handleLLMNewToken(this._context.decode([chunk]) ?? "");
109
+ }
110
+ }
97
111
  }
98
112
  exports.LlamaCpp = LlamaCpp;
@@ -1,6 +1,8 @@
1
1
  import { LlamaModel, LlamaContext, LlamaChatSession } from "node-llama-cpp";
2
2
  import { LlamaBaseCppInputs } from "../util/llama_cpp.js";
3
3
  import { LLM, BaseLLMCallOptions, BaseLLMParams } from "./base.js";
4
+ import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
5
+ import { GenerationChunk } from "../schema/index.js";
4
6
  /**
5
7
  * Note that the modelPath is the only required parameter. For testing you
6
8
  * can set this in the environment variable `LLAMA_PATH`.
@@ -34,5 +36,6 @@ export declare class LlamaCpp extends LLM<LlamaCppCallOptions> {
34
36
  constructor(inputs: LlamaCppInputs);
35
37
  _llmType(): string;
36
38
  /** @ignore */
37
- _call(prompt: string, options?: this["ParsedCallOptions"]): Promise<string>;
39
+ _call(prompt: string, _options?: this["ParsedCallOptions"]): Promise<string>;
40
+ _streamResponseChunks(prompt: string, _options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;
38
41
  }
@@ -1,5 +1,6 @@
1
1
  import { createLlamaModel, createLlamaContext, createLlamaSession, } from "../util/llama_cpp.js";
2
2
  import { LLM } from "./base.js";
3
+ import { GenerationChunk } from "../schema/index.js";
3
4
  /**
4
5
  * To use this model you need to have the `node-llama-cpp` module installed.
5
6
  * This can be installed using `npm install -S node-llama-cpp` and the minimum
@@ -73,9 +74,7 @@ export class LlamaCpp extends LLM {
73
74
  return "llama2_cpp";
74
75
  }
75
76
  /** @ignore */
76
- async _call(prompt,
77
- // @ts-expect-error - TS6133: 'options' is declared but its value is never read.
78
- options) {
77
+ async _call(prompt, _options) {
79
78
  try {
80
79
  const promptOptions = {
81
80
  maxTokens: this?.maxTokens,
@@ -91,4 +90,19 @@ export class LlamaCpp extends LLM {
91
90
  throw new Error("Error getting prompt completion.");
92
91
  }
93
92
  }
93
+ async *_streamResponseChunks(prompt, _options, runManager) {
94
+ const promptOptions = {
95
+ temperature: this?.temperature,
96
+ topK: this?.topK,
97
+ topP: this?.topP,
98
+ };
99
+ const stream = await this.caller.call(async () => this._context.evaluate(this._context.encode(prompt), promptOptions));
100
+ for await (const chunk of stream) {
101
+ yield new GenerationChunk({
102
+ text: this._context.decode([chunk]),
103
+ generationInfo: {},
104
+ });
105
+ await runManager?.handleLLMNewToken(this._context.decode([chunk]) ?? "");
106
+ }
107
+ }
94
108
  }