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
@@ -1 +1,35 @@
1
- export { formatToOpenAIFunction, formatToOpenAITool, formatToOpenAIAssistantTool, } from "@langchain/openai";
1
+ import { zodToJsonSchema } from "zod-to-json-schema";
2
+ /**
3
+ * Formats a `StructuredTool` instance into a format that is compatible
4
+ * with OpenAI's ChatCompletionFunctions. It uses the `zodToJsonSchema`
5
+ * function to convert the schema of the `StructuredTool` into a JSON
6
+ * schema, which is then used as the parameters for the OpenAI function.
7
+ */
8
+ export function formatToOpenAIFunction(tool) {
9
+ return {
10
+ name: tool.name,
11
+ description: tool.description,
12
+ parameters: zodToJsonSchema(tool.schema),
13
+ };
14
+ }
15
+ export function formatToOpenAITool(tool) {
16
+ const schema = zodToJsonSchema(tool.schema);
17
+ return {
18
+ type: "function",
19
+ function: {
20
+ name: tool.name,
21
+ description: tool.description,
22
+ parameters: schema,
23
+ },
24
+ };
25
+ }
26
+ export function formatToOpenAIAssistantTool(tool) {
27
+ return {
28
+ type: "function",
29
+ function: {
30
+ name: tool.name,
31
+ description: tool.description,
32
+ parameters: zodToJsonSchema(tool.schema),
33
+ },
34
+ };
35
+ }
@@ -1,3 +1,135 @@
1
+ import type { OpenAI as OpenAIClient } from "openai";
1
2
  import { TiktokenModel } from "js-tiktoken/lite";
3
+ import { BaseLanguageModelCallOptions } from "../base_language/index.js";
2
4
  export type { TiktokenModel };
3
- export type { OpenAIBaseInput, OpenAICoreRequestOptions, OpenAICallOptions, OpenAIInput, LegacyOpenAIInput, OpenAIChatInput, AzureOpenAIInput, } from "@langchain/openai";
5
+ export declare interface OpenAIBaseInput {
6
+ /** Sampling temperature to use */
7
+ temperature: number;
8
+ /**
9
+ * Maximum number of tokens to generate in the completion. -1 returns as many
10
+ * tokens as possible given the prompt and the model's maximum context size.
11
+ */
12
+ maxTokens?: number;
13
+ /** Total probability mass of tokens to consider at each step */
14
+ topP: number;
15
+ /** Penalizes repeated tokens according to frequency */
16
+ frequencyPenalty: number;
17
+ /** Penalizes repeated tokens */
18
+ presencePenalty: number;
19
+ /** Number of completions to generate for each prompt */
20
+ n: number;
21
+ /** Dictionary used to adjust the probability of specific tokens being generated */
22
+ logitBias?: Record<string, number>;
23
+ /** Unique string identifier representing your end-user, which can help OpenAI to monitor and detect abuse. */
24
+ user?: string;
25
+ /** Whether to stream the results or not. Enabling disables tokenUsage reporting */
26
+ streaming: boolean;
27
+ /** Model name to use */
28
+ modelName: string;
29
+ /** Holds any additional parameters that are valid to pass to {@link
30
+ * https://platform.openai.com/docs/api-reference/completions/create |
31
+ * `openai.createCompletion`} that are not explicitly specified on this class.
32
+ */
33
+ modelKwargs?: Record<string, any>;
34
+ /** List of stop words to use when generating */
35
+ stop?: string[];
36
+ /**
37
+ * Timeout to use when making requests to OpenAI.
38
+ */
39
+ timeout?: number;
40
+ /**
41
+ * API key to use when making requests to OpenAI. Defaults to the value of
42
+ * `OPENAI_API_KEY` environment variable.
43
+ */
44
+ openAIApiKey?: string;
45
+ }
46
+ export type OpenAICoreRequestOptions<Req extends object = Record<string, unknown>> = {
47
+ path?: string;
48
+ query?: Req | undefined;
49
+ body?: Req | undefined;
50
+ headers?: Record<string, string | null | undefined> | undefined;
51
+ maxRetries?: number;
52
+ stream?: boolean | undefined;
53
+ timeout?: number;
54
+ httpAgent?: any;
55
+ signal?: AbortSignal | undefined | null;
56
+ idempotencyKey?: string;
57
+ };
58
+ export interface OpenAICallOptions extends BaseLanguageModelCallOptions {
59
+ /**
60
+ * Additional options to pass to the underlying axios request.
61
+ */
62
+ options?: OpenAICoreRequestOptions;
63
+ }
64
+ /**
65
+ * Input to OpenAI class.
66
+ */
67
+ export declare interface OpenAIInput extends OpenAIBaseInput {
68
+ /** Generates `bestOf` completions server side and returns the "best" */
69
+ bestOf?: number;
70
+ /** Batch size to use when passing multiple documents to generate */
71
+ batchSize: number;
72
+ }
73
+ /**
74
+ * @deprecated Use "baseURL", "defaultHeaders", and "defaultParams" instead.
75
+ */
76
+ export interface LegacyOpenAIInput {
77
+ /** @deprecated Use baseURL instead */
78
+ basePath?: string;
79
+ /** @deprecated Use defaultHeaders and defaultQuery instead */
80
+ baseOptions?: {
81
+ headers?: Record<string, string>;
82
+ params?: Record<string, string>;
83
+ };
84
+ }
85
+ export interface OpenAIChatInput extends OpenAIBaseInput {
86
+ /** ChatGPT messages to pass as a prefix to the prompt */
87
+ prefixMessages?: OpenAIClient.Chat.CreateChatCompletionRequestMessage[];
88
+ }
89
+ export declare interface AzureOpenAIInput {
90
+ /**
91
+ * API version to use when making requests to Azure OpenAI.
92
+ */
93
+ azureOpenAIApiVersion?: string;
94
+ /**
95
+ * API key to use when making requests to Azure OpenAI.
96
+ */
97
+ azureOpenAIApiKey?: string;
98
+ /**
99
+ * Azure OpenAI API instance name to use when making requests to Azure OpenAI.
100
+ * this is the name of the instance you created in the Azure portal.
101
+ * e.g. "my-openai-instance"
102
+ * this will be used in the endpoint URL: https://my-openai-instance.openai.azure.com/openai/deployments/{DeploymentName}/
103
+ */
104
+ azureOpenAIApiInstanceName?: string;
105
+ /**
106
+ * Azure OpenAI API deployment name to use for completions when making requests to Azure OpenAI.
107
+ * This is the name of the deployment you created in the Azure portal.
108
+ * e.g. "my-openai-deployment"
109
+ * this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
110
+ */
111
+ azureOpenAIApiDeploymentName?: string;
112
+ /**
113
+ * Azure OpenAI API deployment name to use for embedding when making requests to Azure OpenAI.
114
+ * This is the name of the deployment you created in the Azure portal.
115
+ * This will fallback to azureOpenAIApiDeploymentName if not provided.
116
+ * e.g. "my-openai-deployment"
117
+ * this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
118
+ */
119
+ azureOpenAIApiEmbeddingsDeploymentName?: string;
120
+ /**
121
+ * Azure OpenAI API deployment name to use for completions when making requests to Azure OpenAI.
122
+ * Completions are only available for gpt-3.5-turbo and text-davinci-003 deployments.
123
+ * This is the name of the deployment you created in the Azure portal.
124
+ * This will fallback to azureOpenAIApiDeploymentName if not provided.
125
+ * e.g. "my-openai-deployment"
126
+ * this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
127
+ */
128
+ azureOpenAIApiCompletionsDeploymentName?: string;
129
+ /**
130
+ * Custom endpoint for Azure OpenAI API. This is useful in case you have a deployment in another region.
131
+ * e.g. setting this value to "https://westeurope.api.cognitive.microsoft.com/openai/deployments"
132
+ * will be result in the endpoint URL: https://westeurope.api.cognitive.microsoft.com/openai/deployments/{DeploymentName}/
133
+ */
134
+ azureOpenAIBasePath?: string;
135
+ }
package/dist/util/env.cjs CHANGED
@@ -1,73 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getEnvironmentVariable = exports.getRuntimeEnvironment = exports.getEnv = exports.isNode = exports.isDeno = exports.isJsDom = exports.isWebWorker = exports.isBrowser = void 0;
4
- const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
5
- exports.isBrowser = isBrowser;
6
- const isWebWorker = () => typeof globalThis === "object" &&
7
- globalThis.constructor &&
8
- globalThis.constructor.name === "DedicatedWorkerGlobalScope";
9
- exports.isWebWorker = isWebWorker;
10
- const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||
11
- (typeof navigator !== "undefined" &&
12
- (navigator.userAgent.includes("Node.js") ||
13
- navigator.userAgent.includes("jsdom")));
14
- exports.isJsDom = isJsDom;
15
- // Supabase Edge Function provides a `Deno` global object
16
- // without `version` property
17
- const isDeno = () => typeof Deno !== "undefined";
18
- exports.isDeno = isDeno;
19
- // Mark not-as-node if in Supabase Edge Function
20
- const isNode = () => typeof process !== "undefined" &&
21
- typeof process.versions !== "undefined" &&
22
- typeof process.versions.node !== "undefined" &&
23
- !(0, exports.isDeno)();
24
- exports.isNode = isNode;
25
- const getEnv = () => {
26
- let env;
27
- if ((0, exports.isBrowser)()) {
28
- env = "browser";
29
- }
30
- else if ((0, exports.isNode)()) {
31
- env = "node";
32
- }
33
- else if ((0, exports.isWebWorker)()) {
34
- env = "webworker";
35
- }
36
- else if ((0, exports.isJsDom)()) {
37
- env = "jsdom";
38
- }
39
- else if ((0, exports.isDeno)()) {
40
- env = "deno";
41
- }
42
- else {
43
- env = "other";
44
- }
45
- return env;
46
- };
47
- exports.getEnv = getEnv;
48
- let runtimeEnvironment;
49
- async function getRuntimeEnvironment() {
50
- if (runtimeEnvironment === undefined) {
51
- const env = (0, exports.getEnv)();
52
- runtimeEnvironment = {
53
- library: "langchain-js",
54
- runtime: env,
55
- };
56
- }
57
- return runtimeEnvironment;
58
- }
59
- exports.getRuntimeEnvironment = getRuntimeEnvironment;
60
- function getEnvironmentVariable(name) {
61
- // Certain Deno setups will throw an error if you try to access environment variables
62
- // https://github.com/langchain-ai/langchainjs/issues/1412
63
- try {
64
- return typeof process !== "undefined"
65
- ? // eslint-disable-next-line no-process-env
66
- process.env?.[name]
67
- : undefined;
68
- }
69
- catch (e) {
70
- return undefined;
71
- }
72
- }
73
- exports.getEnvironmentVariable = getEnvironmentVariable;
4
+ var env_1 = require("@langchain/core/utils/env");
5
+ Object.defineProperty(exports, "isBrowser", { enumerable: true, get: function () { return env_1.isBrowser; } });
6
+ Object.defineProperty(exports, "isWebWorker", { enumerable: true, get: function () { return env_1.isWebWorker; } });
7
+ Object.defineProperty(exports, "isJsDom", { enumerable: true, get: function () { return env_1.isJsDom; } });
8
+ Object.defineProperty(exports, "isDeno", { enumerable: true, get: function () { return env_1.isDeno; } });
9
+ Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return env_1.isNode; } });
10
+ Object.defineProperty(exports, "getEnv", { enumerable: true, get: function () { return env_1.getEnv; } });
11
+ Object.defineProperty(exports, "getRuntimeEnvironment", { enumerable: true, get: function () { return env_1.getRuntimeEnvironment; } });
12
+ Object.defineProperty(exports, "getEnvironmentVariable", { enumerable: true, get: function () { return env_1.getEnvironmentVariable; } });
@@ -1,21 +1 @@
1
- declare global {
2
- const Deno: {
3
- version: {
4
- deno: string;
5
- };
6
- } | undefined;
7
- }
8
- export declare const isBrowser: () => boolean;
9
- export declare const isWebWorker: () => boolean;
10
- export declare const isJsDom: () => boolean;
11
- export declare const isDeno: () => boolean;
12
- export declare const isNode: () => boolean;
13
- export declare const getEnv: () => string;
14
- export type RuntimeEnvironment = {
15
- library: string;
16
- libraryVersion?: string;
17
- runtime: string;
18
- runtimeVersion?: string;
19
- };
20
- export declare function getRuntimeEnvironment(): Promise<RuntimeEnvironment>;
21
- export declare function getEnvironmentVariable(name: string): string | undefined;
1
+ export { isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, type RuntimeEnvironment, getRuntimeEnvironment, getEnvironmentVariable, } from "@langchain/core/utils/env";
package/dist/util/env.js CHANGED
@@ -1,62 +1 @@
1
- export const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
2
- export const isWebWorker = () => typeof globalThis === "object" &&
3
- globalThis.constructor &&
4
- globalThis.constructor.name === "DedicatedWorkerGlobalScope";
5
- export const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||
6
- (typeof navigator !== "undefined" &&
7
- (navigator.userAgent.includes("Node.js") ||
8
- navigator.userAgent.includes("jsdom")));
9
- // Supabase Edge Function provides a `Deno` global object
10
- // without `version` property
11
- export const isDeno = () => typeof Deno !== "undefined";
12
- // Mark not-as-node if in Supabase Edge Function
13
- export const isNode = () => typeof process !== "undefined" &&
14
- typeof process.versions !== "undefined" &&
15
- typeof process.versions.node !== "undefined" &&
16
- !isDeno();
17
- export const getEnv = () => {
18
- let env;
19
- if (isBrowser()) {
20
- env = "browser";
21
- }
22
- else if (isNode()) {
23
- env = "node";
24
- }
25
- else if (isWebWorker()) {
26
- env = "webworker";
27
- }
28
- else if (isJsDom()) {
29
- env = "jsdom";
30
- }
31
- else if (isDeno()) {
32
- env = "deno";
33
- }
34
- else {
35
- env = "other";
36
- }
37
- return env;
38
- };
39
- let runtimeEnvironment;
40
- export async function getRuntimeEnvironment() {
41
- if (runtimeEnvironment === undefined) {
42
- const env = getEnv();
43
- runtimeEnvironment = {
44
- library: "langchain-js",
45
- runtime: env,
46
- };
47
- }
48
- return runtimeEnvironment;
49
- }
50
- export function getEnvironmentVariable(name) {
51
- // Certain Deno setups will throw an error if you try to access environment variables
52
- // https://github.com/langchain-ai/langchainjs/issues/1412
53
- try {
54
- return typeof process !== "undefined"
55
- ? // eslint-disable-next-line no-process-env
56
- process.env?.[name]
57
- : undefined;
58
- }
59
- catch (e) {
60
- return undefined;
61
- }
62
- }
1
+ export { isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, getRuntimeEnvironment, getEnvironmentVariable, } from "@langchain/core/utils/env";
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatFunctionDefinitions = void 0;
4
+ function isAnyOfProp(prop) {
5
+ return (prop.anyOf !== undefined &&
6
+ Array.isArray(prop.anyOf));
7
+ }
8
+ // When OpenAI use functions in the prompt, they format them as TypeScript definitions rather than OpenAPI JSON schemas.
9
+ // This function converts the JSON schemas into TypeScript definitions.
10
+ function formatFunctionDefinitions(functions) {
11
+ const lines = ["namespace functions {", ""];
12
+ for (const f of functions) {
13
+ if (f.description) {
14
+ lines.push(`// ${f.description}`);
15
+ }
16
+ if (Object.keys(f.parameters.properties ?? {}).length > 0) {
17
+ lines.push(`type ${f.name} = (_: {`);
18
+ lines.push(formatObjectProperties(f.parameters, 0));
19
+ lines.push("}) => any;");
20
+ }
21
+ else {
22
+ lines.push(`type ${f.name} = () => any;`);
23
+ }
24
+ lines.push("");
25
+ }
26
+ lines.push("} // namespace functions");
27
+ return lines.join("\n");
28
+ }
29
+ exports.formatFunctionDefinitions = formatFunctionDefinitions;
30
+ // Format just the properties of an object (not including the surrounding braces)
31
+ function formatObjectProperties(obj, indent) {
32
+ const lines = [];
33
+ for (const [name, param] of Object.entries(obj.properties ?? {})) {
34
+ if (param.description && indent < 2) {
35
+ lines.push(`// ${param.description}`);
36
+ }
37
+ if (obj.required?.includes(name)) {
38
+ lines.push(`${name}: ${formatType(param, indent)},`);
39
+ }
40
+ else {
41
+ lines.push(`${name}?: ${formatType(param, indent)},`);
42
+ }
43
+ }
44
+ return lines.map((line) => " ".repeat(indent) + line).join("\n");
45
+ }
46
+ // Format a single property type
47
+ function formatType(param, indent) {
48
+ if (isAnyOfProp(param)) {
49
+ return param.anyOf.map((v) => formatType(v, indent)).join(" | ");
50
+ }
51
+ switch (param.type) {
52
+ case "string":
53
+ if (param.enum) {
54
+ return param.enum.map((v) => `"${v}"`).join(" | ");
55
+ }
56
+ return "string";
57
+ case "number":
58
+ if (param.enum) {
59
+ return param.enum.map((v) => `${v}`).join(" | ");
60
+ }
61
+ return "number";
62
+ case "integer":
63
+ if (param.enum) {
64
+ return param.enum.map((v) => `${v}`).join(" | ");
65
+ }
66
+ return "number";
67
+ case "boolean":
68
+ return "boolean";
69
+ case "null":
70
+ return "null";
71
+ case "object":
72
+ return ["{", formatObjectProperties(param, indent + 2), "}"].join("\n");
73
+ case "array":
74
+ if (param.items) {
75
+ return `${formatType(param.items, indent)}[]`;
76
+ }
77
+ return "any[]";
78
+ default:
79
+ return "";
80
+ }
81
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Formatting function definitions for calculating openai function defination token usage.
3
+ *
4
+ * https://github.com/hmarr/openai-chat-tokens/blob/main/src/functions.ts
5
+ * (c) 2023 Harry Marr
6
+ * MIT license
7
+ */
8
+ import OpenAI from "openai";
9
+ type OpenAIFunction = OpenAI.Chat.ChatCompletionCreateParams.Function;
10
+ export interface FunctionDef extends Omit<OpenAIFunction, "parameters"> {
11
+ name: string;
12
+ description?: string;
13
+ parameters: ObjectProp;
14
+ }
15
+ interface ObjectProp {
16
+ type: "object";
17
+ properties?: {
18
+ [key: string]: Prop;
19
+ };
20
+ required?: string[];
21
+ }
22
+ interface AnyOfProp {
23
+ anyOf: Prop[];
24
+ }
25
+ type Prop = {
26
+ description?: string;
27
+ } & (AnyOfProp | ObjectProp | {
28
+ type: "string";
29
+ enum?: string[];
30
+ } | {
31
+ type: "number" | "integer";
32
+ minimum?: number;
33
+ maximum?: number;
34
+ enum?: number[];
35
+ } | {
36
+ type: "boolean";
37
+ } | {
38
+ type: "null";
39
+ } | {
40
+ type: "array";
41
+ items?: Prop;
42
+ });
43
+ export declare function formatFunctionDefinitions(functions: FunctionDef[]): string;
44
+ export {};
@@ -0,0 +1,77 @@
1
+ function isAnyOfProp(prop) {
2
+ return (prop.anyOf !== undefined &&
3
+ Array.isArray(prop.anyOf));
4
+ }
5
+ // When OpenAI use functions in the prompt, they format them as TypeScript definitions rather than OpenAPI JSON schemas.
6
+ // This function converts the JSON schemas into TypeScript definitions.
7
+ export function formatFunctionDefinitions(functions) {
8
+ const lines = ["namespace functions {", ""];
9
+ for (const f of functions) {
10
+ if (f.description) {
11
+ lines.push(`// ${f.description}`);
12
+ }
13
+ if (Object.keys(f.parameters.properties ?? {}).length > 0) {
14
+ lines.push(`type ${f.name} = (_: {`);
15
+ lines.push(formatObjectProperties(f.parameters, 0));
16
+ lines.push("}) => any;");
17
+ }
18
+ else {
19
+ lines.push(`type ${f.name} = () => any;`);
20
+ }
21
+ lines.push("");
22
+ }
23
+ lines.push("} // namespace functions");
24
+ return lines.join("\n");
25
+ }
26
+ // Format just the properties of an object (not including the surrounding braces)
27
+ function formatObjectProperties(obj, indent) {
28
+ const lines = [];
29
+ for (const [name, param] of Object.entries(obj.properties ?? {})) {
30
+ if (param.description && indent < 2) {
31
+ lines.push(`// ${param.description}`);
32
+ }
33
+ if (obj.required?.includes(name)) {
34
+ lines.push(`${name}: ${formatType(param, indent)},`);
35
+ }
36
+ else {
37
+ lines.push(`${name}?: ${formatType(param, indent)},`);
38
+ }
39
+ }
40
+ return lines.map((line) => " ".repeat(indent) + line).join("\n");
41
+ }
42
+ // Format a single property type
43
+ function formatType(param, indent) {
44
+ if (isAnyOfProp(param)) {
45
+ return param.anyOf.map((v) => formatType(v, indent)).join(" | ");
46
+ }
47
+ switch (param.type) {
48
+ case "string":
49
+ if (param.enum) {
50
+ return param.enum.map((v) => `"${v}"`).join(" | ");
51
+ }
52
+ return "string";
53
+ case "number":
54
+ if (param.enum) {
55
+ return param.enum.map((v) => `${v}`).join(" | ");
56
+ }
57
+ return "number";
58
+ case "integer":
59
+ if (param.enum) {
60
+ return param.enum.map((v) => `${v}`).join(" | ");
61
+ }
62
+ return "number";
63
+ case "boolean":
64
+ return "boolean";
65
+ case "null":
66
+ return "null";
67
+ case "object":
68
+ return ["{", formatObjectProperties(param, indent + 2), "}"].join("\n");
69
+ case "array":
70
+ if (param.items) {
71
+ return `${formatType(param.items, indent)}[]`;
72
+ }
73
+ return "any[]";
74
+ default:
75
+ return "";
76
+ }
77
+ }
@@ -1,5 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.wrapOpenAIClientError = void 0;
4
- var openai_1 = require("@langchain/openai");
5
- Object.defineProperty(exports, "wrapOpenAIClientError", { enumerable: true, get: function () { return openai_1.wrapOpenAIClientError; } });
4
+ const openai_1 = require("openai");
5
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
+ function wrapOpenAIClientError(e) {
7
+ let error;
8
+ if (e.constructor.name === openai_1.APIConnectionTimeoutError.name) {
9
+ error = new Error(e.message);
10
+ error.name = "TimeoutError";
11
+ }
12
+ else if (e.constructor.name === openai_1.APIUserAbortError.name) {
13
+ error = new Error(e.message);
14
+ error.name = "AbortError";
15
+ }
16
+ else {
17
+ error = e;
18
+ }
19
+ return error;
20
+ }
21
+ exports.wrapOpenAIClientError = wrapOpenAIClientError;
@@ -1 +1 @@
1
- export { wrapOpenAIClientError } from "@langchain/openai";
1
+ export declare function wrapOpenAIClientError(e: any): any;
@@ -1 +1,17 @@
1
- export { wrapOpenAIClientError } from "@langchain/openai";
1
+ import { APIConnectionTimeoutError, APIUserAbortError } from "openai";
2
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3
+ export function wrapOpenAIClientError(e) {
4
+ let error;
5
+ if (e.constructor.name === APIConnectionTimeoutError.name) {
6
+ error = new Error(e.message);
7
+ error.name = "TimeoutError";
8
+ }
9
+ else if (e.constructor.name === APIUserAbortError.name) {
10
+ error = new Error(e.message);
11
+ error.name = "AbortError";
12
+ }
13
+ else {
14
+ error = e;
15
+ }
16
+ return error;
17
+ }
@@ -7,7 +7,7 @@ export declare class OpenAPISpec {
7
7
  getParametersStrict(): Record<string, OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject>;
8
8
  getSchemasStrict(): Record<string, OpenAPIV3_1.SchemaObject>;
9
9
  getRequestBodiesStrict(): Record<string, OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject>;
10
- getPathStrict(path: string): Omit<OpenAPIV3.PathItemObject<{}>, "servers" | "parameters"> & {
10
+ getPathStrict(path: string): Omit<OpenAPIV3.PathItemObject<{}>, "parameters" | "servers"> & {
11
11
  servers?: OpenAPIV3_1.ServerObject[] | undefined;
12
12
  parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
13
13
  } & {
@@ -59,7 +59,7 @@ export declare class OpenAPISpec {
59
59
  deprecated?: boolean | undefined;
60
60
  security?: OpenAPIV3.SecurityRequirementObject[] | undefined;
61
61
  servers?: OpenAPIV3.ServerObject[] | undefined;
62
- }, "callbacks" | "servers" | "parameters" | "responses" | "requestBody"> & {
62
+ }, "callbacks" | "parameters" | "servers" | "responses" | "requestBody"> & {
63
63
  parameters?: (OpenAPIV3.ParameterObject | OpenAPIV3_1.ReferenceObject)[] | undefined;
64
64
  requestBody?: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.RequestBodyObject | undefined;
65
65
  responses?: OpenAPIV3_1.ResponsesObject | undefined;
@@ -1,3 +1,3 @@
1
- import type { OpenAIClient } from "@langchain/openai";
1
+ import type { OpenAI as OpenAIClient } from "openai";
2
2
  import { AsyncCaller } from "../util/async_caller.js";
3
3
  export declare const promptLayerTrackRequest: (callerFunc: AsyncCaller, functionName: string, kwargs: OpenAIClient.CompletionCreateParams | OpenAIClient.Chat.CompletionCreateParams, plTags: string[] | undefined, requestResponse: any, startTime: number, endTime: number, apiKey: string | undefined) => Promise<any>;