From bdf707e2d90508c7ca23d8825c59c449382e663c Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Tue, 19 Dec 2023 13:14:10 -0800 Subject: [PATCH] all[patch]: Fix typing across different core versions by using interfaces instead of abstract classes (#3709) * Make model reliant modules use BaseLanguageModelInterface instead of BaseLanguageModel * Fix import * Adds BaseRetrieverInterface * Adds prompt value interface * Format * Revert * Use document and embeddings interfaces * Use vectorstore interface * Adds tool and structured tool interfaces * Use type imports * Use type import --- .../chains/popular/chat_vector_db_legacy.mdx | 6 +- .../data_connection/vectorstores/index.mdx | 4 +- .../prompts/prompt_selectors/index.mdx | 4 +- examples/src/chains/advanced_subclass_call.ts | 6 +- langchain-core/src/callbacks/base.ts | 4 +- langchain-core/src/callbacks/manager.ts | 4 +- langchain-core/src/documents/document.ts | 11 +- langchain-core/src/documents/transformers.ts | 14 +- langchain-core/src/embeddings.ts | 21 ++- .../src/example_selectors/conditional.ts | 21 ++- .../example_selectors/semantic_similarity.ts | 14 +- langchain-core/src/language_models/base.ts | 56 ++++++- .../src/language_models/chat_models.ts | 6 +- langchain-core/src/language_models/llms.ts | 4 +- langchain-core/src/output_parsers/base.ts | 6 +- langchain-core/src/prompt_values.ts | 29 +++- langchain-core/src/prompts/base.ts | 8 +- langchain-core/src/prompts/chat.ts | 13 +- langchain-core/src/prompts/string.ts | 13 +- langchain-core/src/retrievers.ts | 26 +++- langchain-core/src/runnables/base.ts | 8 +- langchain-core/src/runnables/index.ts | 1 + .../tests/runnable_interface.test.ts | 2 + langchain-core/src/tools.ts | 49 +++++++ langchain-core/src/vectorstores.ts | 137 +++++++++++++++--- langchain/src/agents/agent.ts | 22 ++- langchain/src/agents/chat/index.ts | 16 +- langchain/src/agents/chat_convo/index.ts | 14 +- .../src/agents/chat_convo/outputParser.ts | 10 +- langchain/src/agents/executor.ts | 21 +-- langchain/src/agents/helpers.ts | 14 +- langchain/src/agents/initialize.ts | 43 ++++-- langchain/src/agents/load.ts | 8 +- langchain/src/agents/mrkl/index.ts | 23 +-- langchain/src/agents/openai/index.ts | 20 +-- langchain/src/agents/structured_chat/index.ts | 14 +- .../agents/structured_chat/outputParser.ts | 4 +- langchain/src/agents/toolkits/aws_sfn.ts | 4 +- .../openai_functions.ts | 4 +- .../toolkits/conversational_retrieval/tool.ts | 4 +- langchain/src/agents/toolkits/json/json.ts | 8 +- .../src/agents/toolkits/openapi/openapi.ts | 14 +- langchain/src/agents/toolkits/sql/sql.ts | 10 +- .../toolkits/vectorstore/vectorstore.ts | 30 ++-- .../src/agents/toolkits/zapier/zapier.ts | 4 +- langchain/src/agents/xml/index.ts | 12 +- langchain/src/base_language/index.ts | 1 + langchain/src/chains/api/api_chain.ts | 4 +- langchain/src/chains/chat_vector_db_chain.ts | 12 +- .../constitutional_ai/constitutional_chain.ts | 4 +- .../chains/conversational_retrieval_chain.ts | 18 +-- langchain/src/chains/graph_qa/cypher.ts | 12 +- langchain/src/chains/llm_chain.ts | 27 ++-- .../src/chains/query_constructor/index.ts | 4 +- .../src/chains/question_answering/load.ts | 14 +- langchain/src/chains/retrieval_qa.ts | 12 +- langchain/src/chains/router/llm_router.ts | 4 +- langchain/src/chains/router/multi_prompt.ts | 6 +- .../src/chains/router/multi_retrieval_qa.ts | 18 +-- .../router/tests/multi_retrieval_qa.test.ts | 2 +- langchain/src/chains/sql_db/sql_db_chain.ts | 6 +- langchain/src/chains/summarization/load.ts | 8 +- langchain/src/chains/vector_db_qa.ts | 12 +- langchain/src/embeddings/cache_backed.ts | 11 +- langchain/src/evaluation/agents/trajectory.ts | 8 +- langchain/src/evaluation/base.ts | 8 +- .../src/evaluation/comparison/pairwise.ts | 4 +- langchain/src/evaluation/criteria/criteria.ts | 4 +- .../src/evaluation/embedding_distance/base.ts | 8 +- langchain/src/evaluation/loader.ts | 8 +- langchain/src/evaluation/qa/eval_chain.ts | 4 +- langchain/src/experimental/autogpt/agent.ts | 6 +- langchain/src/experimental/autogpt/prompt.ts | 4 +- langchain/src/experimental/babyagi/agent.ts | 10 +- .../violation_of_expectations_chain.ts | 8 +- .../chat_models/anthropic_functions.ts | 4 +- .../generative_agents/generative_agent.ts | 6 +- .../generative_agent_memory.ts | 10 +- .../hubs/makersuite/googlemakersuitehub.ts | 2 +- .../plan_and_execute/agent_executor.ts | 8 +- langchain/src/llms/load.ts | 2 +- langchain/src/memory/buffer_token_memory.ts | 6 +- langchain/src/memory/entity_memory.ts | 6 +- langchain/src/memory/summary.ts | 6 +- langchain/src/memory/vector_store.ts | 6 +- langchain/src/output_parsers/fix.ts | 4 +- .../src/retrievers/contextual_compression.ts | 14 +- .../document_compressors/chain_extract.ts | 21 +-- .../document_compressors/embeddings_filter.ts | 12 +- .../retrievers/document_compressors/index.ts | 10 +- langchain/src/retrievers/hyde.ts | 6 +- langchain/src/retrievers/multi_query.ts | 14 +- langchain/src/retrievers/multi_vector.ts | 11 +- langchain/src/retrievers/parent_document.ts | 13 +- langchain/src/retrievers/remote/base.ts | 5 +- langchain/src/retrievers/self_query/index.ts | 5 +- langchain/src/retrievers/time_weighted.ts | 46 +++--- langchain/src/schema/index.ts | 1 - langchain/src/schema/runnable/base.ts | 1 + langchain/src/tools/convert_to_openai.ts | 9 +- langchain/src/tools/render.ts | 10 +- langchain/src/tools/sql.ts | 4 +- langchain/src/tools/vectorstore.ts | 12 +- langchain/src/tools/webbrowser.ts | 14 +- .../src/util/googlevertexai-connection.ts | 2 +- langchain/src/vectorstores/memory.ts | 10 +- langchain/src/vectorstores/mongo.ts | 8 +- .../template/src/vectorstores.ts | 9 +- .../src/agents/toolkits/aws_sfn.ts | 4 +- .../src/agents/toolkits/base.ts | 4 +- .../src/agents/toolkits/connery/index.ts | 4 +- .../src/chat_models/minimax.ts | 4 +- .../src/retrievers/supabase.ts | 6 +- .../src/vectorstores/analyticdb.ts | 10 +- .../src/vectorstores/cassandra.ts | 10 +- .../src/vectorstores/chroma.ts | 10 +- .../src/vectorstores/clickhouse.ts | 10 +- .../src/vectorstores/closevector/common.ts | 4 +- .../src/vectorstores/closevector/node.ts | 12 +- .../src/vectorstores/closevector/web.ts | 12 +- .../src/vectorstores/cloudflare_vectorize.ts | 10 +- .../src/vectorstores/convex.ts | 8 +- .../src/vectorstores/elasticsearch.ts | 10 +- .../src/vectorstores/faiss.ts | 17 ++- .../src/vectorstores/googlevertexai.ts | 8 +- .../src/vectorstores/hnswlib.ts | 10 +- .../src/vectorstores/lancedb.ts | 8 +- .../src/vectorstores/milvus.ts | 10 +- .../src/vectorstores/momento_vector_index.ts | 11 +- .../src/vectorstores/mongodb_atlas.ts | 11 +- .../src/vectorstores/myscale.ts | 10 +- .../src/vectorstores/neo4j_vector.ts | 14 +- .../src/vectorstores/opensearch.ts | 10 +- .../src/vectorstores/pgvector.ts | 13 +- .../src/vectorstores/pinecone.ts | 10 +- .../src/vectorstores/prisma.ts | 14 +- .../src/vectorstores/qdrant.ts | 10 +- .../src/vectorstores/redis.ts | 11 +- .../src/vectorstores/rockset.ts | 10 +- .../src/vectorstores/singlestore.ts | 11 +- .../src/vectorstores/supabase.ts | 10 +- .../tests/googlevertexai.int.test.ts | 4 +- .../vectorstores/tests/googlevertexai.test.ts | 4 +- .../src/vectorstores/tests/zep.test.ts | 6 +- .../src/vectorstores/tigris.ts | 10 +- .../src/vectorstores/typeorm.ts | 15 +- .../src/vectorstores/typesense.ts | 8 +- .../src/vectorstores/usearch.ts | 8 +- .../src/vectorstores/vectara.ts | 6 +- .../src/vectorstores/vercel_postgres.ts | 13 +- .../src/vectorstores/voy.ts | 8 +- .../src/vectorstores/weaviate.ts | 10 +- .../src/vectorstores/xata.ts | 7 +- .../src/vectorstores/zep.ts | 8 +- libs/langchain-openai/src/chat_models.ts | 8 +- libs/langchain-openai/src/utils/openai.ts | 8 +- 156 files changed, 1070 insertions(+), 679 deletions(-) diff --git a/docs/core_docs/docs/modules/chains/popular/chat_vector_db_legacy.mdx b/docs/core_docs/docs/modules/chains/popular/chat_vector_db_legacy.mdx index 0b3f378668be..f13f8da8cbd0 100644 --- a/docs/core_docs/docs/modules/chains/popular/chat_vector_db_legacy.mdx +++ b/docs/core_docs/docs/modules/chains/popular/chat_vector_db_legacy.mdx @@ -24,11 +24,11 @@ In the above code snippet, the fromLLM method of the `ConversationalRetrievalQAC ```typescript static fromLLM( - llm: BaseLanguageModel, - retriever: BaseRetriever, + llm: BaseLanguageModelInterface, + retriever: BaseRetrieverInterface, options?: { questionGeneratorChainOptions?: { - llm?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; template?: string; }; qaChainOptions?: QAChainParams; diff --git a/docs/core_docs/docs/modules/data_connection/vectorstores/index.mdx b/docs/core_docs/docs/modules/data_connection/vectorstores/index.mdx index d5bc789f7cdc..af6154bab102 100644 --- a/docs/core_docs/docs/modules/data_connection/vectorstores/index.mdx +++ b/docs/core_docs/docs/modules/data_connection/vectorstores/index.mdx @@ -109,13 +109,13 @@ abstract class BaseVectorStore implements VectorStore { static fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: Record ): Promise; static fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: Record ): Promise; } diff --git a/docs/core_docs/docs/modules/model_io/prompts/prompt_selectors/index.mdx b/docs/core_docs/docs/modules/model_io/prompts/prompt_selectors/index.mdx index 2373ee92b527..213e72e05dfc 100644 --- a/docs/core_docs/docs/modules/model_io/prompts/prompt_selectors/index.mdx +++ b/docs/core_docs/docs/modules/model_io/prompts/prompt_selectors/index.mdx @@ -11,7 +11,7 @@ The interface for prompt selectors is quite simple: ```typescript abstract class BasePromptSelector { - abstract getPrompt(llm: BaseLanguageModel): BasePromptTemplate; + abstract getPrompt(llm: BaseLanguageModelInterface): BasePromptTemplate; } ``` @@ -31,7 +31,7 @@ The example below shows how to use a prompt selector when loading a chain: ```typescript const loadQAStuffChain = ( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: StuffQAChainParams = {} ) => { const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm) } = params; diff --git a/examples/src/chains/advanced_subclass_call.ts b/examples/src/chains/advanced_subclass_call.ts index 91d66b3cf5c6..e963b54e2f6c 100644 --- a/examples/src/chains/advanced_subclass_call.ts +++ b/examples/src/chains/advanced_subclass_call.ts @@ -1,16 +1,16 @@ import { BasePromptTemplate, PromptTemplate } from "langchain/prompts"; -import { BaseLanguageModel } from "langchain/base_language"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { CallbackManagerForChainRun } from "langchain/callbacks"; import { BaseChain, ChainInputs } from "langchain/chains"; import { ChainValues } from "langchain/schema"; export interface MyCustomChainInputs extends ChainInputs { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; promptTemplate: string; } export class MyCustomChain extends BaseChain implements MyCustomChainInputs { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; promptTemplate: string; diff --git a/langchain-core/src/callbacks/base.ts b/langchain-core/src/callbacks/base.ts index fdc2a5670491..5907ce57c78a 100644 --- a/langchain-core/src/callbacks/base.ts +++ b/langchain-core/src/callbacks/base.ts @@ -14,7 +14,7 @@ import { get_lc_unique_name, } from "../load/serializable.js"; import type { SerializedFields } from "../load/map_keys.js"; -import { Document } from "../documents/document.js"; +import type { DocumentInterface } from "../documents/document.js"; // eslint-disable-next-line @typescript-eslint/no-explicit-any type Error = any; @@ -242,7 +242,7 @@ abstract class BaseCallbackHandlerMethodsClass { Promise | any; handleRetrieverEnd?( - documents: Document[], + documents: DocumentInterface[], runId: string, parentRunId?: string, tags?: string[] diff --git a/langchain-core/src/callbacks/manager.ts b/langchain-core/src/callbacks/manager.ts index baeccb445618..1a96fe1729c5 100644 --- a/langchain-core/src/callbacks/manager.ts +++ b/langchain-core/src/callbacks/manager.ts @@ -21,7 +21,7 @@ import { } from "../tracers/tracer_langchain.js"; import { consumeCallback } from "./promises.js"; import { Serialized } from "../load/serializable.js"; -import { Document } from "../documents/document.js"; +import type { DocumentInterface } from "../documents/document.js"; type BaseCallbackManagerMethods = { [K in keyof CallbackHandlerMethods]?: ( @@ -153,7 +153,7 @@ export class CallbackManagerForRetrieverRun return manager; } - async handleRetrieverEnd(documents: Document[]): Promise { + async handleRetrieverEnd(documents: DocumentInterface[]): Promise { await Promise.all( this.handlers.map((handler) => consumeCallback(async () => { diff --git a/langchain-core/src/documents/document.ts b/langchain-core/src/documents/document.ts index 3647d51609ff..5979bbf63756 100644 --- a/langchain-core/src/documents/document.ts +++ b/langchain-core/src/documents/document.ts @@ -7,13 +7,22 @@ export interface DocumentInput< metadata?: Metadata; } +export interface DocumentInterface< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Metadata extends Record = Record +> { + pageContent: string; + + metadata: Metadata; +} + /** * Interface for interacting with a document. */ export class Document< // eslint-disable-next-line @typescript-eslint/no-explicit-any Metadata extends Record = Record -> implements DocumentInput +> implements DocumentInput, DocumentInterface { pageContent: string; diff --git a/langchain-core/src/documents/transformers.ts b/langchain-core/src/documents/transformers.ts index 45b5a6a06607..87f9133ac7f0 100644 --- a/langchain-core/src/documents/transformers.ts +++ b/langchain-core/src/documents/transformers.ts @@ -1,6 +1,6 @@ import { Runnable } from "../runnables/base.js"; import type { BaseCallbackConfig } from "../callbacks/manager.js"; -import type { Document } from "./document.js"; +import type { DocumentInterface } from "./document.js"; /** * Abstract base class for document transformation systems. @@ -13,8 +13,8 @@ import type { Document } from "./document.js"; * many smaller documents. */ export abstract class BaseDocumentTransformer< - RunInput extends Document[] = Document[], - RunOutput extends Document[] = Document[] + RunInput extends DocumentInterface[] = DocumentInterface[], + RunOutput extends DocumentInterface[] = DocumentInterface[] > extends Runnable { lc_namespace = ["langchain_core", "documents", "transformers"]; @@ -42,7 +42,9 @@ export abstract class BaseDocumentTransformer< * for each input document. */ export abstract class MappingDocumentTransformer extends BaseDocumentTransformer { - async transformDocuments(documents: Document[]): Promise { + async transformDocuments( + documents: DocumentInterface[] + ): Promise { const newDocuments = []; for (const document of documents) { const transformedDocument = await this._transformDocument(document); @@ -51,5 +53,7 @@ export abstract class MappingDocumentTransformer extends BaseDocumentTransformer return newDocuments; } - abstract _transformDocument(document: Document): Promise; + abstract _transformDocument( + document: DocumentInterface + ): Promise; } diff --git a/langchain-core/src/embeddings.ts b/langchain-core/src/embeddings.ts index dbda06c6b82d..478a19aef486 100644 --- a/langchain-core/src/embeddings.ts +++ b/langchain-core/src/embeddings.ts @@ -6,11 +6,30 @@ import { AsyncCaller, AsyncCallerParams } from "./utils/async_caller.js"; */ export type EmbeddingsParams = AsyncCallerParams; +export interface EmbeddingsInterface { + /** + * An abstract method that takes an array of documents as input and + * returns a promise that resolves to an array of vectors for each + * document. + * @param documents An array of documents to be embedded. + * @returns A promise that resolves to an array of vectors for each document. + */ + embedDocuments(documents: string[]): Promise; + + /** + * An abstract method that takes a single document as input and returns a + * promise that resolves to a vector for the query document. + * @param document A single document to be embedded. + * @returns A promise that resolves to a vector for the query document. + */ + embedQuery(document: string): Promise; +} + /** * An abstract class that provides methods for embedding documents and * queries using LangChain. */ -export abstract class Embeddings { +export abstract class Embeddings implements EmbeddingsInterface { /** * The async caller should be used by subclasses to make any async calls, * which will thus benefit from the concurrency and retry logic. diff --git a/langchain-core/src/example_selectors/conditional.ts b/langchain-core/src/example_selectors/conditional.ts index 43f19dad8bff..db0367b808f3 100644 --- a/langchain-core/src/example_selectors/conditional.ts +++ b/langchain-core/src/example_selectors/conditional.ts @@ -1,6 +1,6 @@ import type { BaseChatModel } from "../language_models/chat_models.js"; import type { BasePromptTemplate } from "../prompts/base.js"; -import type { BaseLanguageModel } from "../language_models/base.js"; +import type { BaseLanguageModelInterface } from "../language_models/base.js"; import type { BaseLLM } from "../language_models/llms.js"; import type { PartialValues } from "../utils/types.js"; @@ -20,7 +20,7 @@ export abstract class BasePromptSelector { * @param llm The language model for which to get a prompt. * @returns A prompt template. */ - abstract getPrompt(llm: BaseLanguageModel): BasePromptTemplate; + abstract getPrompt(llm: BaseLanguageModelInterface): BasePromptTemplate; /** * Asynchronous version of `getPrompt` that also accepts an options object @@ -30,7 +30,7 @@ export abstract class BasePromptSelector { * @returns A Promise that resolves to a prompt template. */ async getPromptAsync( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, options?: BaseGetPromptAsyncOptions ): Promise { const prompt = this.getPrompt(llm); @@ -47,14 +47,17 @@ export class ConditionalPromptSelector extends BasePromptSelector { defaultPrompt: BasePromptTemplate; conditionals: Array< - [condition: (llm: BaseLanguageModel) => boolean, prompt: BasePromptTemplate] + [ + condition: (llm: BaseLanguageModelInterface) => boolean, + prompt: BasePromptTemplate + ] >; constructor( default_prompt: BasePromptTemplate, conditionals: Array< [ - condition: (llm: BaseLanguageModel) => boolean, + condition: (llm: BaseLanguageModelInterface) => boolean, prompt: BasePromptTemplate ] > = [] @@ -70,7 +73,7 @@ export class ConditionalPromptSelector extends BasePromptSelector { * @param llm The language model for which to get a prompt. * @returns A prompt template. */ - getPrompt(llm: BaseLanguageModel): BasePromptTemplate { + getPrompt(llm: BaseLanguageModelInterface): BasePromptTemplate { for (const [condition, prompt] of this.conditionals) { if (condition(llm)) { return prompt; @@ -84,7 +87,7 @@ export class ConditionalPromptSelector extends BasePromptSelector { * Type guard function that checks if a given language model is of type * `BaseLLM`. */ -export function isLLM(llm: BaseLanguageModel): llm is BaseLLM { +export function isLLM(llm: BaseLanguageModelInterface): llm is BaseLLM { return llm._modelType() === "base_llm"; } @@ -92,6 +95,8 @@ export function isLLM(llm: BaseLanguageModel): llm is BaseLLM { * Type guard function that checks if a given language model is of type * `BaseChatModel`. */ -export function isChatModel(llm: BaseLanguageModel): llm is BaseChatModel { +export function isChatModel( + llm: BaseLanguageModelInterface +): llm is BaseChatModel { return llm._modelType() === "base_chat_model"; } diff --git a/langchain-core/src/example_selectors/semantic_similarity.ts b/langchain-core/src/example_selectors/semantic_similarity.ts index dbedbae49228..f4c958f8b456 100644 --- a/langchain-core/src/example_selectors/semantic_similarity.ts +++ b/langchain-core/src/example_selectors/semantic_similarity.ts @@ -1,5 +1,9 @@ import type { Embeddings } from "../embeddings.js"; -import type { VectorStore, VectorStoreRetriever } from "../vectorstores.js"; +import type { + VectorStoreInterface, + VectorStoreRetrieverInterface, + VectorStore, +} from "../vectorstores.js"; import type { Example } from "../prompts/base.js"; import { Document } from "../documents/document.js"; import { BaseExampleSelector } from "./base.js"; @@ -15,7 +19,7 @@ function sortedValues(values: Record): T[] { * class. */ export type SemanticSimilarityExampleSelectorInput< - V extends VectorStore = VectorStore + V extends VectorStoreInterface = VectorStoreInterface > = | { vectorStore: V; @@ -26,7 +30,7 @@ export type SemanticSimilarityExampleSelectorInput< vectorStoreRetriever?: never; } | { - vectorStoreRetriever: VectorStoreRetriever; + vectorStoreRetriever: VectorStoreRetrieverInterface; exampleKeys?: string[]; inputKeys?: string[]; vectorStore?: never; @@ -64,9 +68,9 @@ export type SemanticSimilarityExampleSelectorInput< * ``` */ export class SemanticSimilarityExampleSelector< - V extends VectorStore = VectorStore + V extends VectorStoreInterface = VectorStoreInterface > extends BaseExampleSelector { - vectorStoreRetriever: VectorStoreRetriever; + vectorStoreRetriever: VectorStoreRetrieverInterface; exampleKeys?: string[]; diff --git a/langchain-core/src/language_models/base.ts b/langchain-core/src/language_models/base.ts index 419345f52523..fefdab50c707 100644 --- a/langchain-core/src/language_models/base.ts +++ b/langchain-core/src/language_models/base.ts @@ -2,7 +2,7 @@ import type { Tiktoken, TiktokenModel } from "js-tiktoken/lite"; import { type BaseCache, InMemoryCache } from "../caches.js"; import { - type BasePromptValue, + type BasePromptValueInterface, StringPromptValue, ChatPromptValue, } from "../prompt_values.js"; @@ -20,7 +20,7 @@ import { } from "../callbacks/manager.js"; import { AsyncCaller, AsyncCallerParams } from "../utils/async_caller.js"; import { encodingForModel } from "../utils/tiktoken.js"; -import { Runnable } from "../runnables/base.js"; +import { Runnable, type RunnableInterface } from "../runnables/base.js"; import { RunnableConfig } from "../runnables/config.js"; // https://www.npmjs.com/package/js-tiktoken @@ -235,10 +235,52 @@ export interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions { } export type BaseLanguageModelInput = - | BasePromptValue + | BasePromptValueInterface | string | BaseMessageLike[]; +export interface BaseLanguageModelInterface< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RunOutput = any, + CallOptions extends BaseLanguageModelCallOptions = BaseLanguageModelCallOptions +> extends RunnableInterface { + CallOptions: CallOptions; + + get callKeys(): string[]; + + generatePrompt( + promptValues: BasePromptValueInterface[], + options?: string[] | CallOptions, + callbacks?: Callbacks + ): Promise; + + predict( + text: string, + options?: string[] | CallOptions, + callbacks?: Callbacks + ): Promise; + + predictMessages( + messages: BaseMessage[], + options?: string[] | CallOptions, + callbacks?: Callbacks + ): Promise; + + _modelType(): string; + + _llmType(): string; + + getNumTokens(content: MessageContent): Promise; + + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams(): Record; + + serialize(): SerializedLLM; +} + /** * Base class for language models. */ @@ -248,7 +290,9 @@ export abstract class BaseLanguageModel< CallOptions extends BaseLanguageModelCallOptions = BaseLanguageModelCallOptions > extends BaseLangChain - implements BaseLanguageModelParams + implements + BaseLanguageModelParams, + BaseLanguageModelInterface { declare CallOptions: CallOptions; @@ -287,7 +331,7 @@ export abstract class BaseLanguageModel< } abstract generatePrompt( - promptValues: BasePromptValue[], + promptValues: BasePromptValueInterface[], options?: string[] | CallOptions, callbacks?: Callbacks ): Promise; @@ -349,7 +393,7 @@ export abstract class BaseLanguageModel< protected static _convertInputToPromptValue( input: BaseLanguageModelInput - ): BasePromptValue { + ): BasePromptValueInterface { if (typeof input === "string") { return new StringPromptValue(input); } else if (Array.isArray(input)) { diff --git a/langchain-core/src/language_models/chat_models.ts b/langchain-core/src/language_models/chat_models.ts index 7c8b44bf9e7b..2b4024a31669 100644 --- a/langchain-core/src/language_models/chat_models.ts +++ b/langchain-core/src/language_models/chat_models.ts @@ -6,7 +6,7 @@ import { HumanMessage, coerceMessageLikeToMessage, } from "../messages/index.js"; -import { BasePromptValue } from "../prompt_values.js"; +import type { BasePromptValueInterface } from "../prompt_values.js"; import { LLMResult, RUN_KEY, @@ -514,7 +514,7 @@ export abstract class BaseChatModel< * @returns A Promise that resolves to an LLMResult. */ async generatePrompt( - promptValues: BasePromptValue[], + promptValues: BasePromptValueInterface[], options?: string[] | CallOptions, callbacks?: Callbacks ): Promise { @@ -559,7 +559,7 @@ export abstract class BaseChatModel< * @returns A Promise that resolves to a BaseMessage. */ async callPrompt( - promptValue: BasePromptValue, + promptValue: BasePromptValueInterface, options?: string[] | CallOptions, callbacks?: Callbacks ): Promise { diff --git a/langchain-core/src/language_models/llms.ts b/langchain-core/src/language_models/llms.ts index 9332a7e84ee4..17035d5aebf1 100644 --- a/langchain-core/src/language_models/llms.ts +++ b/langchain-core/src/language_models/llms.ts @@ -3,7 +3,7 @@ import { type BaseMessage, getBufferString, } from "../messages/index.js"; -import type { BasePromptValue } from "../prompt_values.js"; +import type { BasePromptValueInterface } from "../prompt_values.js"; import { type LLMResult, RUN_KEY, @@ -192,7 +192,7 @@ export abstract class BaseLLM< * @returns An LLMResult based on the prompts. */ async generatePrompt( - promptValues: BasePromptValue[], + promptValues: BasePromptValueInterface[], options?: string[] | CallOptions, callbacks?: Callbacks ): Promise { diff --git a/langchain-core/src/output_parsers/base.ts b/langchain-core/src/output_parsers/base.ts index c475b3960be4..db98302e3283 100644 --- a/langchain-core/src/output_parsers/base.ts +++ b/langchain-core/src/output_parsers/base.ts @@ -1,6 +1,6 @@ import { Runnable } from "../runnables/index.js"; import type { RunnableConfig } from "../runnables/config.js"; -import type { BasePromptValue } from "../prompt_values.js"; +import type { BasePromptValueInterface } from "../prompt_values.js"; import type { BaseMessage } from "../messages/index.js"; import type { Callbacks } from "../callbacks/manager.js"; import type { Generation, ChatGeneration } from "../outputs.js"; @@ -42,7 +42,7 @@ export abstract class BaseLLMOutputParser extends Runnable< */ parseResultWithPrompt( generations: Generation[] | ChatGeneration[], - _prompt: BasePromptValue, + _prompt: BasePromptValueInterface, callbacks?: Callbacks ): Promise { return this.parseResult(generations, callbacks); @@ -111,7 +111,7 @@ export abstract class BaseOutputParser< async parseWithPrompt( text: string, - _prompt: BasePromptValue, + _prompt: BasePromptValueInterface, callbacks?: Callbacks ): Promise { return this.parse(text, callbacks); diff --git a/langchain-core/src/prompt_values.ts b/langchain-core/src/prompt_values.ts index 1295774b97d6..fa3f1c0648ad 100644 --- a/langchain-core/src/prompt_values.ts +++ b/langchain-core/src/prompt_values.ts @@ -5,10 +5,27 @@ import { getBufferString, } from "./messages/index.js"; +export interface BasePromptValueInterface extends Serializable { + toString(): string; + + toChatMessages(): BaseMessage[]; +} + +export interface StringPromptValueInterface extends BasePromptValueInterface { + value: string; +} + +export interface ChatPromptValueInterface extends BasePromptValueInterface { + messages: BaseMessage[]; +} + /** * Base PromptValue class. All prompt values should extend this class. */ -export abstract class BasePromptValue extends Serializable { +export abstract class BasePromptValue + extends Serializable + implements BasePromptValueInterface +{ abstract toString(): string; abstract toChatMessages(): BaseMessage[]; @@ -18,7 +35,10 @@ export abstract class BasePromptValue extends Serializable { * Represents a prompt value as a string. It extends the BasePromptValue * class and overrides the toString and toChatMessages methods. */ -export class StringPromptValue extends BasePromptValue { +export class StringPromptValue + extends BasePromptValue + implements StringPromptValueInterface +{ lc_namespace = ["langchain_core", "prompt_values"]; lc_serializable = true; @@ -50,7 +70,10 @@ export interface ChatPromptValueFields { * Class that represents a chat prompt value. It extends the * BasePromptValue and includes an array of BaseMessage instances. */ -export class ChatPromptValue extends BasePromptValue { +export class ChatPromptValue + extends BasePromptValue + implements ChatPromptValueInterface +{ lc_namespace = ["langchain_core", "prompt_values"]; lc_serializable = true; diff --git a/langchain-core/src/prompts/base.ts b/langchain-core/src/prompts/base.ts index a02a14367039..d7fab37924c8 100644 --- a/langchain-core/src/prompts/base.ts +++ b/langchain-core/src/prompts/base.ts @@ -6,7 +6,7 @@ import type { PartialValues, StringWithAutocomplete, } from "../utils/types.js"; -import { type BasePromptValue } from "../prompt_values.js"; +import { type BasePromptValueInterface } from "../prompt_values.js"; import { BaseOutputParser } from "../output_parsers/index.js"; import type { SerializedFields } from "../load/map_keys.js"; import { Runnable } from "../runnables/base.js"; @@ -49,7 +49,7 @@ export interface BasePromptTemplateInput< export abstract class BasePromptTemplate< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunInput extends InputValues = any, - RunOutput extends BasePromptValue = BasePromptValue, + RunOutput extends BasePromptValueInterface = BasePromptValueInterface, // eslint-disable-next-line @typescript-eslint/no-explicit-any PartialVariableName extends string = any > @@ -180,7 +180,9 @@ export abstract class BasePromptTemplate< */ static async deserialize( data: SerializedBasePromptTemplate - ): Promise> { + ): Promise< + BasePromptTemplate + > { switch (data._type) { case "prompt": { const { PromptTemplate } = await import("./prompt.js"); diff --git a/langchain-core/src/prompts/chat.ts b/langchain-core/src/prompts/chat.ts index 95fc18f4976e..8c3eae154cdf 100644 --- a/langchain-core/src/prompts/chat.ts +++ b/langchain-core/src/prompts/chat.ts @@ -12,7 +12,10 @@ import { coerceMessageLikeToMessage, isBaseMessage, } from "../messages/index.js"; -import { ChatPromptValue } from "../prompt_values.js"; +import { + type ChatPromptValueInterface, + ChatPromptValue, +} from "../prompt_values.js"; import type { InputValues, PartialValues } from "../utils/types.js"; import { Runnable } from "../runnables/base.js"; import { BaseStringPromptTemplate } from "./string.js"; @@ -225,7 +228,11 @@ export abstract class BaseChatPromptTemplate< RunInput extends InputValues = any, // eslint-disable-next-line @typescript-eslint/no-explicit-any PartialVariableName extends string = any -> extends BasePromptTemplate { +> extends BasePromptTemplate< + RunInput, + ChatPromptValueInterface, + PartialVariableName +> { constructor(input: BasePromptTemplateInput) { super(input); } @@ -240,7 +247,7 @@ export abstract class BaseChatPromptTemplate< async formatPromptValue( values: TypedPromptInputValues - ): Promise { + ): Promise { const resultMessages = await this.formatMessages(values); return new ChatPromptValue(resultMessages); } diff --git a/langchain-core/src/prompts/string.ts b/langchain-core/src/prompts/string.ts index 900dbd198f79..112a9e73c55b 100644 --- a/langchain-core/src/prompts/string.ts +++ b/langchain-core/src/prompts/string.ts @@ -2,7 +2,10 @@ // Replace with "string" when we are comfortable with a breaking change. import type { InputValues } from "../utils/types.js"; -import { StringPromptValue } from "../prompt_values.js"; +import { + type StringPromptValueInterface, + StringPromptValue, +} from "../prompt_values.js"; import { BasePromptTemplate, type TypedPromptInputValues } from "./base.js"; /** @@ -15,7 +18,11 @@ export abstract class BaseStringPromptTemplate< RunInput extends InputValues = any, // eslint-disable-next-line @typescript-eslint/no-explicit-any PartialVariableName extends string = any -> extends BasePromptTemplate { +> extends BasePromptTemplate< + RunInput, + StringPromptValueInterface, + PartialVariableName +> { /** * Formats the prompt given the input values and returns a formatted * prompt value. @@ -24,7 +31,7 @@ export abstract class BaseStringPromptTemplate< */ async formatPromptValue( values: TypedPromptInputValues - ): Promise { + ): Promise { const formattedPrompt = await this.format(values); return new StringPromptValue(formattedPrompt); } diff --git a/langchain-core/src/retrievers.ts b/langchain-core/src/retrievers.ts index d90607e6cf5c..4d5adf82cca6 100644 --- a/langchain-core/src/retrievers.ts +++ b/langchain-core/src/retrievers.ts @@ -5,8 +5,8 @@ import { Callbacks, parseCallbackConfigArg, } from "./callbacks/manager.js"; -import { Document } from "./documents/document.js"; -import { Runnable } from "./runnables/base.js"; +import type { DocumentInterface } from "./documents/document.js"; +import { Runnable, type RunnableInterface } from "./runnables/base.js"; import { RunnableConfig } from "./runnables/config.js"; /** @@ -19,12 +19,23 @@ export interface BaseRetrieverInput { verbose?: boolean; } +export interface BaseRetrieverInterface + extends RunnableInterface { + getRelevantDocuments( + query: string, + config?: Callbacks | BaseCallbackConfig + ): Promise; +} + /** * Abstract base class for a Document retrieval system. A retrieval system * is defined as something that can take string queries and return the * most 'relevant' Documents from some source. */ -export abstract class BaseRetriever extends Runnable { +export abstract class BaseRetriever + extends Runnable + implements BaseRetrieverInterface +{ callbacks?: Callbacks; tags?: string[]; @@ -49,11 +60,14 @@ export abstract class BaseRetriever extends Runnable { _getRelevantDocuments( _query: string, _callbacks?: CallbackManagerForRetrieverRun - ): Promise { + ): Promise { throw new Error("Not implemented!"); } - async invoke(input: string, options?: RunnableConfig): Promise { + async invoke( + input: string, + options?: RunnableConfig + ): Promise { return this.getRelevantDocuments(input, options); } @@ -70,7 +84,7 @@ export abstract class BaseRetriever extends Runnable { async getRelevantDocuments( query: string, config?: Callbacks | BaseCallbackConfig - ): Promise { + ): Promise { const parsedConfig = parseCallbackConfigArg(config); const callbackManager_ = await CallbackManager.configure( parsedConfig.callbacks, diff --git a/langchain-core/src/runnables/base.ts b/langchain-core/src/runnables/base.ts index e1a1c4c0d815..d08a25da62a5 100644 --- a/langchain-core/src/runnables/base.ts +++ b/langchain-core/src/runnables/base.ts @@ -31,10 +31,14 @@ import { RootListenersTracer } from "../tracers/root_listener.js"; * Should not change on patch releases. */ export interface RunnableInterface< - RunInput, - RunOutput, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RunInput = any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig > { + lc_serializable: boolean; + invoke(input: RunInput, options?: Partial): Promise; batch( diff --git a/langchain-core/src/runnables/index.ts b/langchain-core/src/runnables/index.ts index dd8dce77c3e6..c7e40ef098b9 100644 --- a/langchain-core/src/runnables/index.ts +++ b/langchain-core/src/runnables/index.ts @@ -4,6 +4,7 @@ export { type RunnableBatchOptions, type RunnableRetryFailedAttemptHandler, Runnable, + type RunnableInterface, type RunnableBindingArgs, RunnableBinding, RunnableEach, diff --git a/langchain-core/src/runnables/tests/runnable_interface.test.ts b/langchain-core/src/runnables/tests/runnable_interface.test.ts index d8c20e3bbe71..09cdd8ed1da9 100644 --- a/langchain-core/src/runnables/tests/runnable_interface.test.ts +++ b/langchain-core/src/runnables/tests/runnable_interface.test.ts @@ -176,6 +176,8 @@ class StringPromptValueV0 { class RunnableV0 implements RunnableInterfaceV0 { + lc_serializable = true; + protected lc_runnable = true; async invoke( diff --git a/langchain-core/src/tools.ts b/langchain-core/src/tools.ts index 84b5311eac39..8f93db1988c7 100644 --- a/langchain-core/src/tools.ts +++ b/langchain-core/src/tools.ts @@ -10,6 +10,7 @@ import { type BaseLangChainParams, } from "./language_models/base.js"; import type { RunnableConfig } from "./runnables/config.js"; +import type { RunnableInterface } from "./runnables/base.js"; /** * Parameters for the Tool classes. @@ -30,6 +31,40 @@ export class ToolInputParsingException extends Error { } } +export interface StructuredToolInterface< + // eslint-disable-next-line @typescript-eslint/no-explicit-any + T extends z.ZodObject = z.ZodObject +> extends RunnableInterface< + (z.output extends string ? string : never) | z.input, + string + > { + lc_namespace: string[]; + + schema: T | z.ZodEffects; + + /** + * Calls the tool with the provided argument, configuration, and tags. It + * parses the input according to the schema, handles any errors, and + * manages callbacks. + * @param arg The input argument for the tool. + * @param configArg Optional configuration or callbacks for the tool. + * @param tags Optional tags for the tool. + * @returns A Promise that resolves with a string. + */ + call( + arg: (z.output extends string ? string : never) | z.input, + configArg?: Callbacks | RunnableConfig, + /** @deprecated */ + tags?: string[] + ): Promise; + + name: string; + + description: string; + + returnDirect: boolean; +} + /** * Base class for Tools that accept input of any shape defined by a Zod schema. */ @@ -129,6 +164,20 @@ export abstract class StructuredTool< returnDirect = false; } +export interface ToolInterface extends StructuredToolInterface { + /** + * Calls the tool with the provided argument and callbacks. It handles + * string inputs specifically. + * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema. + * @param callbacks Optional callbacks for the tool. + * @returns A Promise that resolves with a string. + */ + call( + arg: string | undefined | z.input, + callbacks?: Callbacks | RunnableConfig + ): Promise; +} + /** * Base class for Tools that accept input as a string. */ diff --git a/langchain-core/src/vectorstores.ts b/langchain-core/src/vectorstores.ts index 81f120bfbb66..1c31905b98fa 100644 --- a/langchain-core/src/vectorstores.ts +++ b/langchain-core/src/vectorstores.ts @@ -1,6 +1,10 @@ -import type { Embeddings } from "./embeddings.js"; -import type { Document } from "./documents/document.js"; -import { BaseRetriever, BaseRetrieverInput } from "./retrievers.js"; +import type { EmbeddingsInterface } from "./embeddings.js"; +import type { DocumentInterface } from "./documents/document.js"; +import { + BaseRetriever, + BaseRetrieverInterface, + type BaseRetrieverInput, +} from "./retrievers.js"; import { Serializable } from "./load/serializable.js"; import { CallbackManagerForRetrieverRun, @@ -35,7 +39,7 @@ export type VectorStoreRetrieverMMRSearchKwargs = { /** * Type for input when creating a VectorStoreRetriever instance. */ -export type VectorStoreRetrieverInput = +export type VectorStoreRetrieverInput = BaseRetrieverInput & ( | { @@ -53,13 +57,27 @@ export type VectorStoreRetrieverInput = } ); +export interface VectorStoreRetrieverInterface< + V extends VectorStoreInterface = VectorStoreInterface +> extends BaseRetrieverInterface { + vectorStore: V; + + addDocuments( + documents: DocumentInterface[], + options?: AddDocumentOptions + ): Promise; +} + /** * Class for performing document retrieval from a VectorStore. Can perform * similarity search or maximal marginal relevance search. */ export class VectorStoreRetriever< - V extends VectorStore = VectorStore -> extends BaseRetriever { + V extends VectorStoreInterface = VectorStoreInterface + > + extends BaseRetriever + implements VectorStoreRetrieverInterface +{ static lc_name() { return "VectorStoreRetriever"; } @@ -96,7 +114,7 @@ export class VectorStoreRetriever< async _getRelevantDocuments( query: string, runManager?: CallbackManagerForRetrieverRun - ): Promise { + ): Promise { if (this.searchType === "mmr") { if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") { throw new Error( @@ -122,28 +140,103 @@ export class VectorStoreRetriever< } async addDocuments( - documents: Document[], + documents: DocumentInterface[], options?: AddDocumentOptions ): Promise { return this.vectorStore.addDocuments(documents, options); } } +export interface VectorStoreInterface extends Serializable { + FilterType: object | string; + + embeddings: EmbeddingsInterface; + + _vectorstoreType(): string; + + addVectors( + vectors: number[][], + documents: DocumentInterface[], + options?: AddDocumentOptions + ): Promise; + + addDocuments( + documents: DocumentInterface[], + options?: AddDocumentOptions + ): Promise; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete(_params?: Record): Promise; + + similaritySearchVectorWithScore( + query: number[], + k: number, + filter?: this["FilterType"] + ): Promise<[DocumentInterface, number][]>; + + similaritySearch( + query: string, + k?: number, + filter?: this["FilterType"], + callbacks?: Callbacks + ): Promise; + + similaritySearchWithScore( + query: string, + k?: number, + filter?: this["FilterType"], + callbacks?: Callbacks + ): Promise<[DocumentInterface, number][]>; + + /** + * Return documents selected using the maximal marginal relevance. + * Maximal marginal relevance optimizes for similarity to the query AND diversity + * among selected documents. + * + * @param {string} query - Text to look up documents similar to. + * @param {number} options.k - Number of documents to return. + * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm. + * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results, + * where 0 corresponds to maximum diversity and 1 to minimum diversity. + * @param {this["FilterType"]} options.filter - Optional filter + * @param _callbacks + * + * @returns {Promise} - List of documents selected by maximal marginal relevance. + */ + maxMarginalRelevanceSearch?( + query: string, + options: MaxMarginalRelevanceSearchOptions, + callbacks: Callbacks | undefined + ): Promise; + + asRetriever( + kOrFields?: number | Partial>, + filter?: this["FilterType"], + callbacks?: Callbacks, + tags?: string[], + metadata?: Record, + verbose?: boolean + ): VectorStoreRetriever; +} + /** * Abstract class representing a store of vectors. Provides methods for * adding vectors and documents, deleting from the store, and searching * the store. */ -export abstract class VectorStore extends Serializable { +export abstract class VectorStore + extends Serializable + implements VectorStoreInterface +{ declare FilterType: object | string; // Only ever instantiated in main LangChain lc_namespace = ["langchain", "vectorstores", this._vectorstoreType()]; - embeddings: Embeddings; + embeddings: EmbeddingsInterface; // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor(embeddings: Embeddings, dbConfig: Record) { + constructor(embeddings: EmbeddingsInterface, dbConfig: Record) { super(dbConfig); this.embeddings = embeddings; } @@ -152,12 +245,12 @@ export abstract class VectorStore extends Serializable { abstract addVectors( vectors: number[][], - documents: Document[], + documents: DocumentInterface[], options?: AddDocumentOptions ): Promise; abstract addDocuments( - documents: Document[], + documents: DocumentInterface[], options?: AddDocumentOptions ): Promise; @@ -170,14 +263,14 @@ export abstract class VectorStore extends Serializable { query: number[], k: number, filter?: this["FilterType"] - ): Promise<[Document, number][]>; + ): Promise<[DocumentInterface, number][]>; async similaritySearch( query: string, k = 4, filter: this["FilterType"] | undefined = undefined, _callbacks: Callbacks | undefined = undefined // implement passing to embedQuery later - ): Promise { + ): Promise { const results = await this.similaritySearchVectorWithScore( await this.embeddings.embedQuery(query), k, @@ -192,7 +285,7 @@ export abstract class VectorStore extends Serializable { k = 4, filter: this["FilterType"] | undefined = undefined, _callbacks: Callbacks | undefined = undefined // implement passing to embedQuery later - ): Promise<[Document, number][]> { + ): Promise<[DocumentInterface, number][]> { return this.similaritySearchVectorWithScore( await this.embeddings.embedQuery(query), k, @@ -213,18 +306,18 @@ export abstract class VectorStore extends Serializable { * @param {this["FilterType"]} options.filter - Optional filter * @param _callbacks * - * @returns {Promise} - List of documents selected by maximal marginal relevance. + * @returns {Promise} - List of documents selected by maximal marginal relevance. */ async maxMarginalRelevanceSearch?( query: string, options: MaxMarginalRelevanceSearchOptions, _callbacks: Callbacks | undefined // implement passing to embedQuery later - ): Promise; + ): Promise; static fromTexts( _texts: string[], _metadatas: object[] | object, - _embeddings: Embeddings, + _embeddings: EmbeddingsInterface, // eslint-disable-next-line @typescript-eslint/no-explicit-any _dbConfig: Record ): Promise { @@ -234,8 +327,8 @@ export abstract class VectorStore extends Serializable { } static fromDocuments( - _docs: Document[], - _embeddings: Embeddings, + _docs: DocumentInterface[], + _embeddings: EmbeddingsInterface, // eslint-disable-next-line @typescript-eslint/no-explicit-any _dbConfig: Record ): Promise { @@ -293,7 +386,7 @@ export abstract class SaveableVectorStore extends VectorStore { static load( _directory: string, - _embeddings: Embeddings + _embeddings: EmbeddingsInterface ): Promise { throw new Error("Not implemented"); } diff --git a/langchain/src/agents/agent.ts b/langchain/src/agents/agent.ts index 3faf3b700638..e9ebc69ffa3e 100644 --- a/langchain/src/agents/agent.ts +++ b/langchain/src/agents/agent.ts @@ -1,4 +1,8 @@ -import { BaseLanguageModel } from "../base_language/index.js"; +import type { + StructuredToolInterface, + ToolInterface, +} from "@langchain/core/tools"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { CallbackManager, Callbacks } from "../callbacks/manager.js"; import { LLMChain } from "../chains/llm_chain.js"; import { BasePromptTemplate } from "../prompts/base.js"; @@ -10,7 +14,6 @@ import { ChainValues, } from "../schema/index.js"; import { Serializable } from "../load/serializable.js"; -import { StructuredTool, Tool } from "../tools/base.js"; import { AgentActionOutputParser, AgentInput, @@ -44,7 +47,7 @@ class ParseError extends Error { * functionality for agents, such as handling inputs and outputs. */ export abstract class BaseAgent extends Serializable { - declare ToolType: StructuredTool; + declare ToolType: StructuredToolInterface; abstract get inputKeys(): string[]; @@ -365,7 +368,7 @@ export abstract class Agent extends BaseSingleActionAgent { * @returns A PromptTemplate assembled from the given tools and fields. * */ static createPrompt( - _tools: StructuredTool[], + _tools: StructuredToolInterface[], // eslint-disable-next-line @typescript-eslint/no-explicit-any _fields?: Record ): BasePromptTemplate { @@ -374,8 +377,8 @@ export abstract class Agent extends BaseSingleActionAgent { /** Construct an agent from an LLM and a list of tools */ static fromLLMAndTools( - _llm: BaseLanguageModel, - _tools: StructuredTool[], + _llm: BaseLanguageModelInterface, + _tools: StructuredToolInterface[], // eslint-disable-next-line @typescript-eslint/no-explicit-any _args?: AgentArgs ): Agent { @@ -385,7 +388,7 @@ export abstract class Agent extends BaseSingleActionAgent { /** * Validate that appropriate tools are passed in */ - static validateTools(_tools: StructuredTool[]): void {} + static validateTools(_tools: StructuredToolInterface[]): void {} _stop(): string[] { return [`\n${this.observationPrefix()}`]; @@ -502,7 +505,10 @@ export abstract class Agent extends BaseSingleActionAgent { * Load an agent from a json-like object describing it. */ static async deserialize( - data: SerializedAgent & { llm?: BaseLanguageModel; tools?: Tool[] } + data: SerializedAgent & { + llm?: BaseLanguageModelInterface; + tools?: ToolInterface[]; + } ): Promise { switch (data._type) { case "zero-shot-react-description": { diff --git a/langchain/src/agents/chat/index.ts b/langchain/src/agents/chat/index.ts index 1acf732f1f58..526c848e644c 100644 --- a/langchain/src/agents/chat/index.ts +++ b/langchain/src/agents/chat/index.ts @@ -1,4 +1,5 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { LLMChain } from "../../chains/llm_chain.js"; import { ChatPromptTemplate, @@ -6,7 +7,6 @@ import { SystemMessagePromptTemplate, } from "../../prompts/chat.js"; import { AgentStep } from "../../schema/index.js"; -import { Tool } from "../../tools/base.js"; import { Optional } from "../../types/type-utils.js"; import { Agent, AgentArgs, OutputParserArgs } from "../agent.js"; import { AgentInput } from "../types.js"; @@ -48,7 +48,7 @@ export class ChatAgent extends Agent { lc_namespace = ["langchain", "agents", "chat"]; - declare ToolType: Tool; + declare ToolType: ToolInterface; constructor(input: ChatAgentInput) { const outputParser = @@ -78,7 +78,7 @@ export class ChatAgent extends Agent { * @param tools Array of Tool instances to validate. * @returns void */ - static validateTools(tools: Tool[]) { + static validateTools(tools: ToolInterface[]) { const descriptionlessTool = tools.find((tool) => !tool.description); if (descriptionlessTool) { const msg = @@ -121,7 +121,7 @@ export class ChatAgent extends Agent { * @param args.humanMessageTemplate - String to use directly as the human message template * @param args.formatInstructions - Formattable string to use as the instructions template */ - static createPrompt(tools: Tool[], args?: ChatCreatePromptArgs) { + static createPrompt(tools: ToolInterface[], args?: ChatCreatePromptArgs) { const { prefix = PREFIX, suffix = SUFFIX, @@ -144,14 +144,14 @@ export class ChatAgent extends Agent { /** * Creates a ChatAgent instance using a language model, tools, and * optional arguments. - * @param llm BaseLanguageModel instance to use in the agent. + * @param llm BaseLanguageModelInterface instance to use in the agent. * @param tools Array of Tool instances to include in the agent. * @param args Optional arguments to customize the agent and prompt. * @returns ChatAgent instance */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: Tool[], + llm: BaseLanguageModelInterface, + tools: ToolInterface[], args?: ChatCreatePromptArgs & AgentArgs ) { ChatAgent.validateTools(tools); diff --git a/langchain/src/agents/chat_convo/index.ts b/langchain/src/agents/chat_convo/index.ts index 898c1557d59c..391de78d5678 100644 --- a/langchain/src/agents/chat_convo/index.ts +++ b/langchain/src/agents/chat_convo/index.ts @@ -1,4 +1,5 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { LLMChain } from "../../chains/llm_chain.js"; import { ChatPromptTemplate, @@ -13,7 +14,6 @@ import { BaseMessage, HumanMessage, } from "../../schema/index.js"; -import { Tool } from "../../tools/base.js"; import { Optional } from "../../types/type-utils.js"; import { Agent, AgentArgs, OutputParserArgs } from "../agent.js"; import { AgentActionOutputParser, AgentInput } from "../types.js"; @@ -58,7 +58,7 @@ export class ChatConversationalAgent extends Agent { lc_namespace = ["langchain", "agents", "chat_convo"]; - declare ToolType: Tool; + declare ToolType: ToolInterface; constructor(input: ChatConversationalAgentInput) { const outputParser = @@ -82,7 +82,7 @@ export class ChatConversationalAgent extends Agent { return ["Observation:"]; } - static validateTools(tools: Tool[]) { + static validateTools(tools: ToolInterface[]) { const descriptionlessTool = tools.find((tool) => !tool.description); if (descriptionlessTool) { const msg = @@ -148,7 +148,7 @@ export class ChatConversationalAgent extends Agent { * @param args.outputParser - Output parser to use for formatting. */ static createPrompt( - tools: Tool[], + tools: ToolInterface[], args?: ChatConversationalCreatePromptArgs ) { const systemMessage = (args?.systemMessage ?? DEFAULT_PREFIX) + PREFIX_END; @@ -186,8 +186,8 @@ export class ChatConversationalAgent extends Agent { * @returns An instance of the ChatConversationalAgent class. */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: Tool[], + llm: BaseLanguageModelInterface, + tools: ToolInterface[], args?: ChatConversationalCreatePromptArgs & AgentArgs ) { ChatConversationalAgent.validateTools(tools); diff --git a/langchain/src/agents/chat_convo/outputParser.ts b/langchain/src/agents/chat_convo/outputParser.ts index 8706bfae3e12..3c5c632b8f93 100644 --- a/langchain/src/agents/chat_convo/outputParser.ts +++ b/langchain/src/agents/chat_convo/outputParser.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { FormatInstructionsOptions, OutputParserException, @@ -7,7 +8,6 @@ import { AgentActionOutputParser } from "../types.js"; import { FORMAT_INSTRUCTIONS } from "./prompt.js"; import { AgentAction, AgentFinish } from "../../schema/index.js"; import { OutputFixingParser } from "../../output_parsers/fix.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; export type ChatConversationalAgentOutputParserFormatInstructionsOptions = FormatInstructionsOptions & { @@ -141,16 +141,16 @@ export class ChatConversationalAgentOutputParserWithRetries extends AgentActionO /** * Static method to create a new - * ChatConversationalAgentOutputParserWithRetries from a BaseLanguageModel + * ChatConversationalAgentOutputParserWithRetries from a BaseLanguageModelInterface * and options. If no base parser is provided in the options, a new * ChatConversationalAgentOutputParser is created. An OutputFixingParser - * is also created from the BaseLanguageModel and the base parser. - * @param llm BaseLanguageModel instance used to create the OutputFixingParser. + * is also created from the BaseLanguageModelInterface and the base parser. + * @param llm BaseLanguageModelInterface instance used to create the OutputFixingParser. * @param options Options for creating the ChatConversationalAgentOutputParserWithRetries instance. * @returns A new instance of ChatConversationalAgentOutputParserWithRetries. */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, options: Omit ): ChatConversationalAgentOutputParserWithRetries { const baseParser = diff --git a/langchain/src/agents/executor.ts b/langchain/src/agents/executor.ts index bc2191a4b6e7..a38647da4f89 100644 --- a/langchain/src/agents/executor.ts +++ b/langchain/src/agents/executor.ts @@ -1,3 +1,9 @@ +import { + type StructuredToolInterface, + type ToolInterface, + ToolInputParsingException, + Tool, +} from "@langchain/core/tools"; import { BaseChain, ChainInputs } from "../chains/base.js"; import { BaseMultiActionAgent, @@ -18,11 +24,6 @@ import { Callbacks, } from "../callbacks/manager.js"; import { OutputParserException } from "../schema/output_parser.js"; -import { - StructuredTool, - ToolInputParsingException, - Tool, -} from "../tools/base.js"; import { Runnable } from "../schema/runnable/base.js"; import { Serializable } from "../load/serializable.js"; @@ -76,7 +77,7 @@ export class AgentExecutorIterator iterations = 0; - get nameToToolMap(): Record { + get nameToToolMap(): Record { const toolMap = this.agentExecutor.tools.map((tool) => ({ [tool.name]: tool, })); @@ -267,9 +268,9 @@ export class AgentExecutorIterator } } -type ExtractToolType = T extends { ToolType: infer Tool } - ? Tool - : StructuredTool; +type ExtractToolType = T extends { ToolType: infer ToolInterface } + ? ToolInterface + : StructuredToolInterface; /** * Interface defining the structure of input data for creating an @@ -550,7 +551,7 @@ export class AgentExecutor extends BaseChain { } async _takeNextStep( - nameToolMap: Record, + nameToolMap: Record, inputs: ChainValues, intermediateSteps: AgentStep[], runManager?: CallbackManagerForChainRun diff --git a/langchain/src/agents/helpers.ts b/langchain/src/agents/helpers.ts index 3311a34a2d1c..9bb54070a019 100644 --- a/langchain/src/agents/helpers.ts +++ b/langchain/src/agents/helpers.ts @@ -1,7 +1,7 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import type { SerializedAgentT, AgentInput } from "./types.js"; -import { Tool } from "../tools/base.js"; import { LLMChain } from "../chains/llm_chain.js"; -import { BaseLanguageModel } from "../base_language/index.js"; export const deserializeHelper = async < T extends string, @@ -9,10 +9,14 @@ export const deserializeHelper = async < V extends AgentInput, Z >( - llm: BaseLanguageModel | undefined, - tools: Tool[] | undefined, + llm: BaseLanguageModelInterface | undefined, + tools: ToolInterface[] | undefined, data: SerializedAgentT, - fromLLMAndTools: (llm: BaseLanguageModel, tools: Tool[], args: U) => Z, + fromLLMAndTools: ( + llm: BaseLanguageModelInterface, + tools: ToolInterface[], + args: U + ) => Z, fromConstructor: (args: V) => Z ): Promise => { if (data.load_from_llm_and_tools) { diff --git a/langchain/src/agents/initialize.ts b/langchain/src/agents/initialize.ts index 6ade238175c8..c0e8c19db3b9 100644 --- a/langchain/src/agents/initialize.ts +++ b/langchain/src/agents/initialize.ts @@ -1,7 +1,10 @@ -import { BaseLanguageModel } from "../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { + StructuredToolInterface, + ToolInterface, +} from "@langchain/core/tools"; import { CallbackManager } from "../callbacks/manager.js"; import { BufferMemory } from "../memory/buffer_memory.js"; -import { StructuredTool, Tool } from "../tools/base.js"; import { ChatAgent } from "./chat/index.js"; import { ChatConversationalAgent } from "./chat_convo/index.js"; import { StructuredChatAgent } from "./structured_chat/index.js"; @@ -24,8 +27,8 @@ type AgentType = * @deprecated use initializeAgentExecutorWithOptions instead */ export const initializeAgentExecutor = async ( - tools: Tool[], - llm: BaseLanguageModel, + tools: ToolInterface[], + llm: BaseLanguageModelInterface, _agentType?: AgentType, _verbose?: boolean, _callbackManager?: CallbackManager @@ -106,18 +109,18 @@ export type InitializeAgentExecutorOptionsStructured = * @returns AgentExecutor */ export async function initializeAgentExecutorWithOptions( - tools: StructuredTool[], - llm: BaseLanguageModel, + tools: StructuredToolInterface[], + llm: BaseLanguageModelInterface, options: InitializeAgentExecutorOptionsStructured ): Promise; export async function initializeAgentExecutorWithOptions( - tools: Tool[], - llm: BaseLanguageModel, + tools: ToolInterface[], + llm: BaseLanguageModelInterface, options?: InitializeAgentExecutorOptions ): Promise; export async function initializeAgentExecutorWithOptions( - tools: StructuredTool[] | Tool[], - llm: BaseLanguageModel, + tools: StructuredToolInterface[] | ToolInterface[], + llm: BaseLanguageModelInterface, options: | InitializeAgentExecutorOptions | InitializeAgentExecutorOptionsStructured = { @@ -135,7 +138,11 @@ export async function initializeAgentExecutorWithOptions( const { agentArgs, tags, ...rest } = options; return AgentExecutor.fromAgentAndTools({ tags: [...(tags ?? []), "zero-shot-react-description"], - agent: ZeroShotAgent.fromLLMAndTools(llm, tools as Tool[], agentArgs), + agent: ZeroShotAgent.fromLLMAndTools( + llm, + tools as ToolInterface[], + agentArgs + ), tools, ...rest, }); @@ -144,7 +151,11 @@ export async function initializeAgentExecutorWithOptions( const { agentArgs, tags, ...rest } = options; return AgentExecutor.fromAgentAndTools({ tags: [...(tags ?? []), "chat-zero-shot-react-description"], - agent: ChatAgent.fromLLMAndTools(llm, tools as Tool[], agentArgs), + agent: ChatAgent.fromLLMAndTools( + llm, + tools as ToolInterface[], + agentArgs + ), tools, ...rest, }); @@ -155,7 +166,7 @@ export async function initializeAgentExecutorWithOptions( tags: [...(tags ?? []), "chat-conversational-react-description"], agent: ChatConversationalAgent.fromLLMAndTools( llm, - tools as Tool[], + tools as ToolInterface[], agentArgs ), tools, @@ -175,7 +186,11 @@ export async function initializeAgentExecutorWithOptions( const { agentArgs, tags, ...rest } = options; const executor = AgentExecutor.fromAgentAndTools({ tags: [...(tags ?? []), "xml"], - agent: XMLAgent.fromLLMAndTools(llm, tools as Tool[], agentArgs), + agent: XMLAgent.fromLLMAndTools( + llm, + tools as ToolInterface[], + agentArgs + ), tools, ...rest, }); diff --git a/langchain/src/agents/load.ts b/langchain/src/agents/load.ts index a7e00a367b12..7d8e649649f2 100644 --- a/langchain/src/agents/load.ts +++ b/langchain/src/agents/load.ts @@ -1,6 +1,6 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { Agent } from "./agent.js"; -import { Tool } from "../tools/base.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { loadFromHub } from "../util/hub.js"; import { FileLoader, loadFromFile } from "../util/load.js"; import { parseFileConfig } from "../util/parse.js"; @@ -8,7 +8,7 @@ import { parseFileConfig } from "../util/parse.js"; const loadAgentFromFile: FileLoader = async ( file: string, path: string, - llmAndTools?: { llm?: BaseLanguageModel; tools?: Tool[] } + llmAndTools?: { llm?: BaseLanguageModelInterface; tools?: ToolInterface[] } ) => { const serialized = parseFileConfig(file, path); return Agent.deserialize({ ...serialized, ...llmAndTools }); @@ -16,7 +16,7 @@ const loadAgentFromFile: FileLoader = async ( export const loadAgent = async ( uri: string, - llmAndTools?: { llm?: BaseLanguageModel; tools?: Tool[] } + llmAndTools?: { llm?: BaseLanguageModelInterface; tools?: ToolInterface[] } ): Promise => { const hubResult = await loadFromHub( uri, diff --git a/langchain/src/agents/mrkl/index.ts b/langchain/src/agents/mrkl/index.ts index 3e3dceb96711..eefd1d932de8 100644 --- a/langchain/src/agents/mrkl/index.ts +++ b/langchain/src/agents/mrkl/index.ts @@ -1,8 +1,8 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import { ToolInterface } from "@langchain/core/tools"; import { LLMChain } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/prompt.js"; import { renderTemplate } from "../../prompts/template.js"; -import { Tool } from "../../tools/base.js"; import { Optional } from "../../types/type-utils.js"; import { Agent, AgentArgs, OutputParserArgs } from "../agent.js"; import { deserializeHelper } from "../helpers.js"; @@ -64,7 +64,7 @@ export class ZeroShotAgent extends Agent { lc_namespace = ["langchain", "agents", "mrkl"]; - declare ToolType: Tool; + declare ToolType: ToolInterface; constructor(input: ZeroShotAgentInput) { const outputParser = @@ -98,7 +98,7 @@ export class ZeroShotAgent extends Agent { * does not have a description. * @param tools List of tools to validate. */ - static validateTools(tools: Tool[]) { + static validateTools(tools: ToolInterface[]) { const descriptionlessTool = tools.find((tool) => !tool.description); if (descriptionlessTool) { const msg = @@ -117,7 +117,7 @@ export class ZeroShotAgent extends Agent { * @param args.prefix - String to put before the list of tools. * @param args.inputVariables - List of input variables the final prompt will expect. */ - static createPrompt(tools: Tool[], args?: ZeroShotCreatePromptArgs) { + static createPrompt(tools: ToolInterface[], args?: ZeroShotCreatePromptArgs) { const { prefix = PREFIX, suffix = SUFFIX, @@ -151,8 +151,8 @@ export class ZeroShotAgent extends Agent { * @returns A new instance of ZeroShotAgent. */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: Tool[], + llm: BaseLanguageModelInterface, + tools: ToolInterface[], args?: ZeroShotCreatePromptArgs & AgentArgs ) { ZeroShotAgent.validateTools(tools); @@ -173,7 +173,10 @@ export class ZeroShotAgent extends Agent { } static async deserialize( - data: SerializedZeroShotAgent & { llm?: BaseLanguageModel; tools?: Tool[] } + data: SerializedZeroShotAgent & { + llm?: BaseLanguageModelInterface; + tools?: ToolInterface[]; + } ): Promise { const { llm, tools, ...rest } = data; return deserializeHelper( @@ -181,8 +184,8 @@ export class ZeroShotAgent extends Agent { tools, rest, ( - llm: BaseLanguageModel, - tools: Tool[], + llm: BaseLanguageModelInterface, + tools: ToolInterface[], args: SerializedFromLLMAndTools ) => ZeroShotAgent.fromLLMAndTools(llm, tools, { diff --git a/langchain/src/agents/openai/index.ts b/langchain/src/agents/openai/index.ts index 7cc3be08b417..8ae5a58b9d50 100644 --- a/langchain/src/agents/openai/index.ts +++ b/langchain/src/agents/openai/index.ts @@ -1,3 +1,8 @@ +import type { + BaseLanguageModelInterface, + BaseLanguageModelInput, +} from "@langchain/core/language_models/base"; +import type { StructuredToolInterface } from "@langchain/core/tools"; import { CallbackManager } from "../../callbacks/manager.js"; import { ChatOpenAI, ChatOpenAICallOptions } from "../../chat_models/openai.js"; import { BasePromptTemplate } from "../../prompts/base.js"; @@ -12,7 +17,6 @@ import { SystemMessage, BaseMessageChunk, } from "../../schema/index.js"; -import { StructuredTool } from "../../tools/base.js"; import { Agent, AgentArgs } from "../agent.js"; import { AgentInput } from "../types.js"; import { PREFIX } from "./prompt.js"; @@ -22,10 +26,6 @@ import { MessagesPlaceholder, SystemMessagePromptTemplate, } from "../../prompts/chat.js"; -import { - BaseLanguageModel, - BaseLanguageModelInput, -} from "../../base_language/index.js"; import { LLMChain } from "../../chains/llm_chain.js"; import { FunctionsAgentAction, @@ -73,7 +73,7 @@ export function _formatIntermediateSteps( * Interface for the input data required to create an OpenAIAgent. */ export interface OpenAIAgentInput extends AgentInput { - tools: StructuredTool[]; + tools: StructuredToolInterface[]; } /** @@ -113,7 +113,7 @@ export class OpenAIAgent extends Agent { return ["Observation:"]; } - tools: StructuredTool[]; + tools: StructuredToolInterface[]; outputParser: OpenAIFunctionsAgentOutputParser = new OpenAIFunctionsAgentOutputParser(); @@ -131,7 +131,7 @@ export class OpenAIAgent extends Agent { * @returns A BasePromptTemplate object representing the created prompt. */ static createPrompt( - _tools: StructuredTool[], + _tools: StructuredToolInterface[], fields?: OpenAIAgentCreatePromptArgs ): BasePromptTemplate { const { prefix = PREFIX } = fields || {}; @@ -151,8 +151,8 @@ export class OpenAIAgent extends Agent { * @returns An instance of OpenAIAgent. */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: StructuredTool[], + llm: BaseLanguageModelInterface, + tools: StructuredToolInterface[], args?: OpenAIAgentCreatePromptArgs & Pick ) { OpenAIAgent.validateTools(tools); diff --git a/langchain/src/agents/structured_chat/index.ts b/langchain/src/agents/structured_chat/index.ts index 61e1ae0df800..bb2adeec80f9 100644 --- a/langchain/src/agents/structured_chat/index.ts +++ b/langchain/src/agents/structured_chat/index.ts @@ -1,7 +1,8 @@ import { zodToJsonSchema } from "zod-to-json-schema"; import { JsonSchema7ObjectType } from "zod-to-json-schema/src/parsers/object.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { StructuredToolInterface } from "@langchain/core/tools"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/prompt.js"; import { @@ -11,7 +12,6 @@ import { SystemMessagePromptTemplate, } from "../../prompts/chat.js"; import { AgentStep } from "../../schema/index.js"; -import { StructuredTool } from "../../tools/base.js"; import { Optional } from "../../types/type-utils.js"; import { Agent, AgentArgs, OutputParserArgs } from "../agent.js"; import { AgentInput } from "../types.js"; @@ -79,7 +79,7 @@ export class StructuredChatAgent extends Agent { * if any tool lacks a description. * @param tools Array of StructuredTool instances to validate. */ - static validateTools(tools: StructuredTool[]) { + static validateTools(tools: StructuredToolInterface[]) { const descriptionlessTool = tools.find((tool) => !tool.description); if (descriptionlessTool) { const msg = @@ -130,7 +130,7 @@ export class StructuredChatAgent extends Agent { * @param tools Array of StructuredTool instances to create the schemas string from. * @returns A string representing the schemas of the provided tools. */ - static createToolSchemasString(tools: StructuredTool[]) { + static createToolSchemasString(tools: StructuredToolInterface[]) { return tools .map( (tool) => @@ -152,7 +152,7 @@ export class StructuredChatAgent extends Agent { * @param args.memoryPrompts List of historical prompts from memory. */ static createPrompt( - tools: StructuredTool[], + tools: StructuredToolInterface[], args?: StructuredChatCreatePromptArgs ) { const { @@ -195,8 +195,8 @@ export class StructuredChatAgent extends Agent { * @returns A new instance of StructuredChatAgent. */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: StructuredTool[], + llm: BaseLanguageModelInterface, + tools: StructuredToolInterface[], args?: StructuredChatCreatePromptArgs & AgentArgs ) { StructuredChatAgent.validateTools(tools); diff --git a/langchain/src/agents/structured_chat/outputParser.ts b/langchain/src/agents/structured_chat/outputParser.ts index b27ffd5206c8..d8aa458d4118 100644 --- a/langchain/src/agents/structured_chat/outputParser.ts +++ b/langchain/src/agents/structured_chat/outputParser.ts @@ -1,10 +1,10 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { AgentActionOutputParser } from "../types.js"; import { AGENT_ACTION_FORMAT_INSTRUCTIONS, FORMAT_INSTRUCTIONS, } from "./prompt.js"; import { OutputFixingParser } from "../../output_parsers/fix.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { AgentAction, AgentFinish } from "../../schema/index.js"; import { OutputParserException } from "../../schema/output_parser.js"; import { renderTemplate } from "../../prompts/index.js"; @@ -151,7 +151,7 @@ export class StructuredChatOutputParserWithRetries extends AgentActionOutputPars * @returns A new `StructuredChatOutputParserWithRetries` instance. */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, options: Omit ): StructuredChatOutputParserWithRetries { const baseParser = diff --git a/langchain/src/agents/toolkits/aws_sfn.ts b/langchain/src/agents/toolkits/aws_sfn.ts index b0438dd37624..7779fe14d885 100644 --- a/langchain/src/agents/toolkits/aws_sfn.ts +++ b/langchain/src/agents/toolkits/aws_sfn.ts @@ -1,8 +1,8 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { type AWSSfnToolkitArgs, AWSSfnToolkit, } from "@langchain/community/agents/toolkits/aws_sfn"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { renderTemplate } from "../../prompts/template.js"; import { LLMChain } from "../../chains/llm_chain.js"; import { ZeroShotAgent, ZeroShotCreatePromptArgs } from "../mrkl/index.js"; @@ -27,7 +27,7 @@ Thought: I should look at state machines within AWS Step Functions to see what a export interface AWSSfnCreatePromptArgs extends ZeroShotCreatePromptArgs {} export function createAWSSfnAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, toolkit: AWSSfnToolkit, args?: AWSSfnCreatePromptArgs ) { diff --git a/langchain/src/agents/toolkits/conversational_retrieval/openai_functions.ts b/langchain/src/agents/toolkits/conversational_retrieval/openai_functions.ts index 2a044e54420d..0ba452ddf39d 100644 --- a/langchain/src/agents/toolkits/conversational_retrieval/openai_functions.ts +++ b/langchain/src/agents/toolkits/conversational_retrieval/openai_functions.ts @@ -1,6 +1,6 @@ +import { StructuredToolInterface } from "@langchain/core/tools"; import { ChatOpenAI } from "../../../chat_models/openai.js"; import { ConversationSummaryBufferMemory } from "../../../memory/summary_buffer.js"; -import { StructuredTool } from "../../../tools/base.js"; import { initializeAgentExecutorWithOptions } from "../../initialize.js"; import { OpenAIAgentTokenBufferMemory } from "./token_buffer_memory.js"; @@ -24,7 +24,7 @@ export type ConversationalRetrievalAgentOptions = { */ export async function createConversationalRetrievalAgent( llm: ChatOpenAI, - tools: StructuredTool[], + tools: StructuredToolInterface[], options?: ConversationalRetrievalAgentOptions ) { const { diff --git a/langchain/src/agents/toolkits/conversational_retrieval/tool.ts b/langchain/src/agents/toolkits/conversational_retrieval/tool.ts index 36a15e2ef9a1..ce784fe938a1 100644 --- a/langchain/src/agents/toolkits/conversational_retrieval/tool.ts +++ b/langchain/src/agents/toolkits/conversational_retrieval/tool.ts @@ -1,6 +1,6 @@ +import type { BaseRetrieverInterface } from "@langchain/core/retrievers"; import { z } from "zod"; import { CallbackManagerForToolRun } from "../../../callbacks/manager.js"; -import { BaseRetriever } from "../../../schema/retriever.js"; import { DynamicStructuredTool, DynamicStructuredToolInput, @@ -8,7 +8,7 @@ import { import { formatDocumentsAsString } from "../../../util/document.js"; export function createRetrieverTool( - retriever: BaseRetriever, + retriever: BaseRetrieverInterface, input: Omit ) { const func = async ( diff --git a/langchain/src/agents/toolkits/json/json.ts b/langchain/src/agents/toolkits/json/json.ts index bbf9e8c742f3..cb1e392fe9a0 100644 --- a/langchain/src/agents/toolkits/json/json.ts +++ b/langchain/src/agents/toolkits/json/json.ts @@ -1,5 +1,5 @@ -import { BaseLanguageModel } from "../../../base_language/index.js"; -import { Tool } from "../../../tools/base.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { JsonGetValueTool, JsonListKeysTool, @@ -24,7 +24,7 @@ import { AgentExecutor } from "../../executor.js"; * ``` */ export class JsonToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; constructor(public jsonSpec: JsonSpec) { super(); @@ -47,7 +47,7 @@ export class JsonToolkit extends Toolkit { * @returns An AgentExecutor for executing the created JSON agent with the tools. */ export function createJsonAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, toolkit: JsonToolkit, args?: ZeroShotCreatePromptArgs ) { diff --git a/langchain/src/agents/toolkits/openapi/openapi.ts b/langchain/src/agents/toolkits/openapi/openapi.ts index e21b17f72402..e3764cbac0ed 100644 --- a/langchain/src/agents/toolkits/openapi/openapi.ts +++ b/langchain/src/agents/toolkits/openapi/openapi.ts @@ -1,5 +1,5 @@ -import { BaseLanguageModel } from "../../../base_language/index.js"; -import { Tool } from "../../../tools/base.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { DynamicTool } from "../../../tools/dynamic.js"; import { JsonSpec } from "../../../tools/json.js"; import { AgentExecutor } from "../../executor.js"; @@ -23,7 +23,7 @@ import { createJsonAgent, JsonToolkit } from "../json/json.js"; * request tools based on the provided headers. */ export class RequestsToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; constructor(headers?: Headers) { super(); @@ -56,7 +56,11 @@ export class RequestsToolkit extends Toolkit { * ``` */ export class OpenApiToolkit extends RequestsToolkit { - constructor(jsonSpec: JsonSpec, llm: BaseLanguageModel, headers?: Headers) { + constructor( + jsonSpec: JsonSpec, + llm: BaseLanguageModelInterface, + headers?: Headers + ) { super(headers); const jsonAgent = createJsonAgent(llm, new JsonToolkit(jsonSpec)); this.tools = [ @@ -93,7 +97,7 @@ export class OpenApiToolkit extends RequestsToolkit { * @link See https://js.langchain.com/docs/security for more information. */ export function createOpenApiAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, openApiToolkit: OpenApiToolkit, args?: ZeroShotCreatePromptArgs ) { diff --git a/langchain/src/agents/toolkits/sql/sql.ts b/langchain/src/agents/toolkits/sql/sql.ts index d11711dde28d..23ff252e7ac6 100644 --- a/langchain/src/agents/toolkits/sql/sql.ts +++ b/langchain/src/agents/toolkits/sql/sql.ts @@ -1,4 +1,5 @@ -import { Tool } from "../../../tools/base.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { InfoSqlTool, ListTablesSqlTool, @@ -6,7 +7,6 @@ import { QuerySqlTool, } from "../../../tools/sql.js"; import { Toolkit } from "../base.js"; -import { BaseLanguageModel } from "../../../base_language/index.js"; import { SQL_PREFIX, SQL_SUFFIX } from "./prompt.js"; import { renderTemplate } from "../../../prompts/template.js"; import { LLMChain } from "../../../chains/llm_chain.js"; @@ -36,13 +36,13 @@ export interface SqlCreatePromptArgs extends ZeroShotCreatePromptArgs { * ``` */ export class SqlToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; db: SqlDatabase; dialect = "sqlite"; - constructor(db: SqlDatabase, llm?: BaseLanguageModel) { + constructor(db: SqlDatabase, llm?: BaseLanguageModelInterface) { super(); this.db = db; this.tools = [ @@ -55,7 +55,7 @@ export class SqlToolkit extends Toolkit { } export function createSqlAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, toolkit: SqlToolkit, args?: SqlCreatePromptArgs ) { diff --git a/langchain/src/agents/toolkits/vectorstore/vectorstore.ts b/langchain/src/agents/toolkits/vectorstore/vectorstore.ts index 5b7eaf3042f0..b5c46d9ae2f8 100644 --- a/langchain/src/agents/toolkits/vectorstore/vectorstore.ts +++ b/langchain/src/agents/toolkits/vectorstore/vectorstore.ts @@ -1,8 +1,8 @@ -import { Tool } from "../../../tools/base.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; +import { ToolInterface } from "@langchain/core/tools"; import { VectorStoreQATool } from "../../../tools/vectorstore.js"; -import { VectorStore } from "../../../vectorstores/base.js"; import { Toolkit } from "../base.js"; -import { BaseLanguageModel } from "../../../base_language/index.js"; import { ZeroShotCreatePromptArgs, ZeroShotAgent } from "../../mrkl/index.js"; import { VECTOR_PREFIX, VECTOR_ROUTER_PREFIX } from "./prompt.js"; import { SUFFIX } from "../../mrkl/prompt.js"; @@ -14,7 +14,7 @@ import { AgentExecutor } from "../../executor.js"; * the vector store itself, its name, and description. */ export interface VectorStoreInfo { - vectorStore: VectorStore; + vectorStore: VectorStoreInterface; name: string; description: string; } @@ -41,11 +41,14 @@ export interface VectorStoreInfo { * ``` */ export class VectorStoreToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; - constructor(vectorStoreInfo: VectorStoreInfo, llm: BaseLanguageModel) { + constructor( + vectorStoreInfo: VectorStoreInfo, + llm: BaseLanguageModelInterface + ) { super(); const description = VectorStoreQATool.getDescription( vectorStoreInfo.name, @@ -67,13 +70,16 @@ export class VectorStoreToolkit extends Toolkit { * vector store information and language model. */ export class VectorStoreRouterToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; vectorStoreInfos: VectorStoreInfo[]; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; - constructor(vectorStoreInfos: VectorStoreInfo[], llm: BaseLanguageModel) { + constructor( + vectorStoreInfos: VectorStoreInfo[], + llm: BaseLanguageModelInterface + ) { super(); this.llm = llm; this.vectorStoreInfos = vectorStoreInfos; @@ -91,7 +97,7 @@ export class VectorStoreRouterToolkit extends Toolkit { } export function createVectorStoreAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, toolkit: VectorStoreToolkit, args?: ZeroShotCreatePromptArgs ) { @@ -119,7 +125,7 @@ export function createVectorStoreAgent( } export function createVectorStoreRouterAgent( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, toolkit: VectorStoreRouterToolkit, args?: ZeroShotCreatePromptArgs ) { diff --git a/langchain/src/agents/toolkits/zapier/zapier.ts b/langchain/src/agents/toolkits/zapier/zapier.ts index c192149b4abe..94b2226d83d7 100644 --- a/langchain/src/agents/toolkits/zapier/zapier.ts +++ b/langchain/src/agents/toolkits/zapier/zapier.ts @@ -1,5 +1,5 @@ +import { ToolInterface } from "@langchain/core/tools"; import { Toolkit } from "../base.js"; -import { Tool } from "../../../tools/base.js"; import { ZapierNLARunAction, ZapierNLAWrapper } from "../../../tools/zapier.js"; /** @@ -17,7 +17,7 @@ import { ZapierNLARunAction, ZapierNLAWrapper } from "../../../tools/zapier.js"; * ``` */ export class ZapierToolKit extends Toolkit { - tools: Tool[] = []; + tools: ToolInterface[] = []; /** * Creates a ZapierToolKit instance based on a ZapierNLAWrapper instance. diff --git a/langchain/src/agents/xml/index.ts b/langchain/src/agents/xml/index.ts index 45d134ef6a53..d478a4763611 100644 --- a/langchain/src/agents/xml/index.ts +++ b/langchain/src/agents/xml/index.ts @@ -1,4 +1,5 @@ -import { Tool } from "../../tools/base.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { ToolInterface } from "@langchain/core/tools"; import { LLMChain } from "../../chains/llm_chain.js"; import { AgentStep, @@ -14,14 +15,13 @@ import { import { AgentArgs, BaseSingleActionAgent } from "../agent.js"; import { AGENT_INSTRUCTIONS } from "./prompt.js"; import { CallbackManager } from "../../callbacks/manager.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { XMLAgentOutputParser } from "./output_parser.js"; /** * Interface for the input to the XMLAgent class. */ export interface XMLAgentInput { - tools: Tool[]; + tools: ToolInterface[]; llmChain: LLMChain; } @@ -35,7 +35,7 @@ export class XMLAgent extends BaseSingleActionAgent implements XMLAgentInput { lc_namespace = ["langchain", "agents", "xml"]; - tools: Tool[]; + tools: ToolInterface[]; llmChain: LLMChain; @@ -101,8 +101,8 @@ export class XMLAgent extends BaseSingleActionAgent implements XMLAgentInput { * @returns An instance of XMLAgent. */ static fromLLMAndTools( - llm: BaseLanguageModel, - tools: Tool[], + llm: BaseLanguageModelInterface, + tools: ToolInterface[], args?: XMLAgentInput & Pick ) { const prompt = XMLAgent.createPrompt(); diff --git a/langchain/src/base_language/index.ts b/langchain/src/base_language/index.ts index cf3ff9707d14..ff0f51c7359c 100644 --- a/langchain/src/base_language/index.ts +++ b/langchain/src/base_language/index.ts @@ -6,6 +6,7 @@ export { type BaseLanguageModelCallOptions, type BaseFunctionCallOptions, type BaseLanguageModelInput, + type BaseLanguageModelInterface, BaseLanguageModel, } from "@langchain/core/language_models/base"; diff --git a/langchain/src/chains/api/api_chain.ts b/langchain/src/chains/api/api_chain.ts index 6d1b38a9a8f7..77c73032e8f0 100644 --- a/langchain/src/chains/api/api_chain.ts +++ b/langchain/src/chains/api/api_chain.ts @@ -1,7 +1,7 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseChain, ChainInputs } from "../base.js"; import { SerializedAPIChain } from "../serde.js"; import { LLMChain } from "../llm_chain.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { ChainValues } from "../../schema/index.js"; import { @@ -134,7 +134,7 @@ export class APIChain extends BaseChain implements APIChainInput { * @returns New APIChain instance. */ static fromLLMAndAPIDocs( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, apiDocs: string, options: APIChainOptions & Omit = {} diff --git a/langchain/src/chains/chat_vector_db_chain.ts b/langchain/src/chains/chat_vector_db_chain.ts index cd64c6ec68ff..7fb6c9d0cd50 100644 --- a/langchain/src/chains/chat_vector_db_chain.ts +++ b/langchain/src/chains/chat_vector_db_chain.ts @@ -1,6 +1,6 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { PromptTemplate } from "../prompts/prompt.js"; -import { BaseLanguageModel } from "../base_language/index.js"; -import { VectorStore } from "../vectorstores/base.js"; import { SerializedChatVectorDBQAChain } from "./serde.js"; import { ChainValues } from "../schema/index.js"; import { BaseChain, ChainInputs } from "./base.js"; @@ -29,7 +29,7 @@ Helpful Answer:`; * Interface for the input parameters of the ChatVectorDBQAChain class. */ export interface ChatVectorDBQAChainInput extends ChainInputs { - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; combineDocumentsChain: BaseChain; questionGeneratorChain: LLMChain; returnSourceDocuments?: boolean; @@ -59,7 +59,7 @@ export class ChatVectorDBQAChain return [this.outputKey]; } - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; combineDocumentsChain: BaseChain; @@ -180,8 +180,8 @@ export class ChatVectorDBQAChain * @returns New instance of ChatVectorDBQAChain. */ static fromLLM( - llm: BaseLanguageModel, - vectorstore: VectorStore, + llm: BaseLanguageModelInterface, + vectorstore: VectorStoreInterface, options: { inputKey?: string; outputKey?: string; diff --git a/langchain/src/chains/constitutional_ai/constitutional_chain.ts b/langchain/src/chains/constitutional_ai/constitutional_chain.ts index 00857ce0e6c0..fd94637b2167 100644 --- a/langchain/src/chains/constitutional_ai/constitutional_chain.ts +++ b/langchain/src/chains/constitutional_ai/constitutional_chain.ts @@ -1,4 +1,4 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { ChainValues } from "../../schema/index.js"; import { BaseChain, ChainInputs } from "../base.js"; @@ -140,7 +140,7 @@ export class ConstitutionalChain * @returns New instance of ConstitutionalChain */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, options: Omit< ConstitutionalChainInput, "critiqueChain" | "revisionChain" diff --git a/langchain/src/chains/conversational_retrieval_chain.ts b/langchain/src/chains/conversational_retrieval_chain.ts index 2033273ae79f..985c1bfdbd3c 100644 --- a/langchain/src/chains/conversational_retrieval_chain.ts +++ b/langchain/src/chains/conversational_retrieval_chain.ts @@ -1,5 +1,6 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { BaseRetrieverInterface } from "@langchain/core/retrievers"; import { PromptTemplate } from "../prompts/prompt.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { SerializedChatVectorDBQAChain } from "./serde.js"; import { ChainValues, @@ -7,7 +8,6 @@ import { HumanMessage, AIMessage, } from "../schema/index.js"; -import { BaseRetriever } from "../schema/retriever.js"; import { BaseChain, ChainInputs } from "./base.js"; import { LLMChain } from "./llm_chain.js"; import { QAChainParams, loadQAChain } from "./question_answering/load.js"; @@ -28,7 +28,7 @@ Standalone question:`; * ConversationalRetrievalQAChain class. */ export interface ConversationalRetrievalQAChainInput extends ChainInputs { - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; combineDocumentsChain: BaseChain; questionGeneratorChain: LLMChain; returnSourceDocuments?: boolean; @@ -92,7 +92,7 @@ export class ConversationalRetrievalQAChain ); } - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; combineDocumentsChain: BaseChain; @@ -238,16 +238,16 @@ export class ConversationalRetrievalQAChain /** * Static method to create a new ConversationalRetrievalQAChain from a * BaseLanguageModel and a BaseRetriever. - * @param llm {@link BaseLanguageModel} instance used to generate a new question. - * @param retriever {@link BaseRetriever} instance used to retrieve relevant documents. + * @param llm {@link BaseLanguageModelInterface} instance used to generate a new question. + * @param retriever {@link BaseRetrieverInterface} instance used to retrieve relevant documents. * @param options.returnSourceDocuments Whether to return source documents in the final output * @param options.questionGeneratorChainOptions Options to initialize the standalone question generation chain used as the first internal step * @param options.qaChainOptions {@link QAChainParams} used to initialize the QA chain used as the second internal step * @returns A new instance of ConversationalRetrievalQAChain. */ static fromLLM( - llm: BaseLanguageModel, - retriever: BaseRetriever, + llm: BaseLanguageModelInterface, + retriever: BaseRetrieverInterface, options: { outputKey?: string; // not used returnSourceDocuments?: boolean; @@ -256,7 +256,7 @@ export class ConversationalRetrievalQAChain /** @deprecated Pass in qaChainOptions.prompt instead */ qaTemplate?: string; questionGeneratorChainOptions?: { - llm?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; template?: string; }; qaChainOptions?: QAChainParams; diff --git a/langchain/src/chains/graph_qa/cypher.ts b/langchain/src/chains/graph_qa/cypher.ts index bd7743e4dada..b5de38f52cab 100644 --- a/langchain/src/chains/graph_qa/cypher.ts +++ b/langchain/src/chains/graph_qa/cypher.ts @@ -1,8 +1,8 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../../chains/llm_chain.js"; import { ChainValues } from "../../schema/index.js"; import { BasePromptTemplate } from "../../prompts/base.js"; import { BaseChain, ChainInputs } from "../base.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { Neo4jGraph } from "../../graphs/neo4j_graph.js"; import { CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT } from "./prompts.js"; @@ -22,9 +22,9 @@ export interface GraphCypherQAChainInput extends ChainInputs { export interface FromLLMInput { graph: Neo4jGraph; - llm?: BaseLanguageModel; - cypherLLM?: BaseLanguageModel; - qaLLM?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; + cypherLLM?: BaseLanguageModelInterface; + qaLLM?: BaseLanguageModelInterface; qaPrompt?: BasePromptTemplate; cypherPrompt?: BasePromptTemplate; returnIntermediateSteps?: boolean; @@ -133,12 +133,12 @@ export class GraphCypherQAChain extends BaseChain { } const qaChain = new LLMChain({ - llm: (qaLLM || llm) as BaseLanguageModel, + llm: (qaLLM || llm) as BaseLanguageModelInterface, prompt: qaPrompt, }); const cypherGenerationChain = new LLMChain({ - llm: (cypherLLM || llm) as BaseLanguageModel, + llm: (cypherLLM || llm) as BaseLanguageModelInterface, prompt: cypherPrompt, }); diff --git a/langchain/src/chains/llm_chain.ts b/langchain/src/chains/llm_chain.ts index 6702805d443d..05b00205c746 100644 --- a/langchain/src/chains/llm_chain.ts +++ b/langchain/src/chains/llm_chain.ts @@ -1,15 +1,14 @@ -import { BaseChain, ChainInputs } from "./base.js"; -import { BasePromptTemplate } from "../prompts/base.js"; import { BaseLanguageModel, + BaseLanguageModelInterface, BaseLanguageModelInput, -} from "../base_language/index.js"; -import { - ChainValues, - Generation, - BasePromptValue, - BaseMessage, -} from "../schema/index.js"; +} from "@langchain/core/language_models/base"; +import type { ChainValues } from "@langchain/core/utils/types"; +import type { Generation } from "@langchain/core/outputs"; +import type { BaseMessage } from "@langchain/core/messages"; +import type { BasePromptValueInterface } from "@langchain/core/prompt_values"; +import { BaseChain, ChainInputs } from "./base.js"; +import { BasePromptTemplate } from "../prompts/base.js"; import { BaseLLMOutputParser, BaseOutputParser, @@ -22,10 +21,10 @@ import { Callbacks, } from "../callbacks/manager.js"; import { NoOpOutputParser } from "../output_parsers/noop.js"; -import { Runnable } from "../schema/runnable/base.js"; +import { Runnable, type RunnableInterface } from "../schema/runnable/base.js"; type LLMType = - | BaseLanguageModel + | BaseLanguageModelInterface | Runnable | Runnable; @@ -51,10 +50,10 @@ export interface LLMChainInput< } function isBaseLanguageModel(llmLike: unknown): llmLike is BaseLanguageModel { - return typeof (llmLike as BaseLanguageModel)._llmType === "function"; + return typeof (llmLike as BaseLanguageModelInterface)._llmType === "function"; } -function _getLanguageModel(llmLike: Runnable): BaseLanguageModel { +function _getLanguageModel(llmLike: RunnableInterface): BaseLanguageModel { if (isBaseLanguageModel(llmLike)) { return llmLike; } else if ("bound" in llmLike && Runnable.isRunnable(llmLike.bound)) { @@ -152,7 +151,7 @@ export class LLMChain< /** @ignore */ async _getFinalOutput( generations: Generation[], - promptValue: BasePromptValue, + promptValue: BasePromptValueInterface, runManager?: CallbackManagerForChainRun ): Promise { let finalCompletion: unknown; diff --git a/langchain/src/chains/query_constructor/index.ts b/langchain/src/chains/query_constructor/index.ts index c915f0ca88ce..b0758811b9ea 100644 --- a/langchain/src/chains/query_constructor/index.ts +++ b/langchain/src/chains/query_constructor/index.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { z } from "zod"; import { QueryTransformer, TraverseType } from "./parser.js"; import { @@ -18,7 +19,6 @@ import { import { interpolateFString } from "../../prompts/template.js"; import { LLMChain } from "../llm_chain.js"; import { FewShotPromptTemplate } from "../../prompts/few_shot.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { AsymmetricStructuredOutputParser } from "../../output_parsers/structured.js"; import { AttributeInfo } from "../../schema/query_constructor.js"; @@ -166,7 +166,7 @@ function _getPrompt( * A type that represents options for the query constructor chain. */ export type QueryConstructorChainOptions = { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; documentContents: string; attributeInfo: AttributeInfo[]; examples?: InputValues[]; diff --git a/langchain/src/chains/question_answering/load.ts b/langchain/src/chains/question_answering/load.ts index 03fd8a1c0e15..7c85fb5a16fb 100644 --- a/langchain/src/chains/question_answering/load.ts +++ b/langchain/src/chains/question_answering/load.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../llm_chain.js"; import { BasePromptTemplate } from "../../prompts/base.js"; import { @@ -11,7 +12,6 @@ import { COMBINE_PROMPT_SELECTOR, COMBINE_QA_PROMPT_SELECTOR, } from "./map_reduce_prompts.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { QUESTION_PROMPT_SELECTOR, REFINE_PROMPT_SELECTOR, @@ -33,7 +33,7 @@ export type QAChainParams = } & RefineQAChainParams); export const loadQAChain = ( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: QAChainParams = { type: "stuff" } ) => { const { type } = params; @@ -65,7 +65,7 @@ export interface StuffQAChainParams { * @returns A StuffQAChain instance. */ export function loadQAStuffChain( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: StuffQAChainParams = {} ) { const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; @@ -81,7 +81,7 @@ export interface MapReduceQAChainParams { returnIntermediateSteps?: MapReduceDocumentsChainInput["returnIntermediateSteps"]; combineMapPrompt?: BasePromptTemplate; combinePrompt?: BasePromptTemplate; - combineLLM?: BaseLanguageModel; + combineLLM?: BaseLanguageModelInterface; verbose?: boolean; } @@ -93,7 +93,7 @@ export interface MapReduceQAChainParams { * @returns A MapReduceQAChain instance. */ export function loadQAMapReduceChain( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: MapReduceQAChainParams = {} ) { const { @@ -129,7 +129,7 @@ export function loadQAMapReduceChain( export interface RefineQAChainParams { questionPrompt?: BasePromptTemplate; refinePrompt?: BasePromptTemplate; - refineLLM?: BaseLanguageModel; + refineLLM?: BaseLanguageModelInterface; verbose?: boolean; } @@ -141,7 +141,7 @@ export interface RefineQAChainParams { * @returns A RefineQAChain instance. */ export function loadQARefineChain( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: RefineQAChainParams = {} ) { const { diff --git a/langchain/src/chains/retrieval_qa.ts b/langchain/src/chains/retrieval_qa.ts index cb3b3fa04d8e..78f52e600d14 100644 --- a/langchain/src/chains/retrieval_qa.ts +++ b/langchain/src/chains/retrieval_qa.ts @@ -1,8 +1,8 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { BaseRetrieverInterface } from "@langchain/core/retrievers"; import { BaseChain, ChainInputs } from "./base.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { SerializedVectorDBQAChain } from "./serde.js"; import { ChainValues } from "../schema/index.js"; -import { BaseRetriever } from "../schema/retriever.js"; import { StuffQAChainParams, loadQAStuffChain, @@ -16,7 +16,7 @@ export type LoadValues = Record; * Interface for the input parameters of the RetrievalQAChain class. */ export interface RetrievalQAChainInput extends Omit { - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; combineDocumentsChain: BaseChain; inputKey?: string; returnSourceDocuments?: boolean; @@ -67,7 +67,7 @@ export class RetrievalQAChain ); } - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; combineDocumentsChain: BaseChain; @@ -133,8 +133,8 @@ export class RetrievalQAChain * @returns A new instance of RetrievalQAChain. */ static fromLLM( - llm: BaseLanguageModel, - retriever: BaseRetriever, + llm: BaseLanguageModelInterface, + retriever: BaseRetrieverInterface, options?: Partial< Omit< RetrievalQAChainInput, diff --git a/langchain/src/chains/router/llm_router.ts b/langchain/src/chains/router/llm_router.ts index e02924e07ad1..602b958fd3c3 100644 --- a/langchain/src/chains/router/llm_router.ts +++ b/langchain/src/chains/router/llm_router.ts @@ -1,9 +1,9 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BasePromptTemplate } from "../../prompts/base.js"; import { LLMChain } from "../../chains/llm_chain.js"; import { RouterChain } from "./multi_route.js"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { ChainValues } from "../../schema/index.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { ChainInputs } from "../../chains/base.js"; /** @@ -63,7 +63,7 @@ export class LLMRouterChain extends RouterChain implements LLMRouterChainInput { * @returns An instance of LLMRouterChain. */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, prompt: BasePromptTemplate, options?: Omit ) { diff --git a/langchain/src/chains/router/multi_prompt.ts b/langchain/src/chains/router/multi_prompt.ts index a6c71c33e1e0..fcdca6e0feaf 100644 --- a/langchain/src/chains/router/multi_prompt.ts +++ b/langchain/src/chains/router/multi_prompt.ts @@ -1,5 +1,5 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { z } from "zod"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { MultiRouteChain, MultiRouteChainInput } from "./multi_route.js"; import { STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE } from "./multi_prompt_prompt.js"; import { BaseChain } from "../../chains/base.js"; @@ -40,7 +40,7 @@ export class MultiPromptChain extends MultiRouteChain { * @deprecated Use `fromLLMAndPrompts` instead */ static fromPrompts( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, promptNames: string[], promptDescriptions: string[], promptTemplates: string[] | PromptTemplate[], @@ -71,7 +71,7 @@ export class MultiPromptChain extends MultiRouteChain { * @returns An instance of MultiPromptChain. */ static fromLLMAndPrompts( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, { promptNames, promptDescriptions, diff --git a/langchain/src/chains/router/multi_retrieval_qa.ts b/langchain/src/chains/router/multi_retrieval_qa.ts index 5a84183b2b10..21358c8fd8b1 100644 --- a/langchain/src/chains/router/multi_retrieval_qa.ts +++ b/langchain/src/chains/router/multi_retrieval_qa.ts @@ -1,5 +1,6 @@ import { z } from "zod"; -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { BaseRetrieverInterface } from "@langchain/core/retrievers"; import { MultiRouteChain, MultiRouteChainInput } from "./multi_route.js"; import { BaseChain } from "../../chains/base.js"; import { interpolateFString } from "../../prompts/template.js"; @@ -9,7 +10,6 @@ import { ConversationChain, DEFAULT_TEMPLATE, } from "../../chains/conversation.js"; -import { BaseRetriever } from "../../schema/retriever.js"; import { STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE } from "./multi_retrieval_prompt.js"; import { zipEntries } from "./utils.js"; import { @@ -24,7 +24,7 @@ import { RouterOutputParser } from "../../output_parsers/router.js"; * default prompt, and default chain. */ export type MultiRetrievalDefaults = { - defaultRetriever?: BaseRetriever; + defaultRetriever?: BaseRetrieverInterface; defaultPrompt?: PromptTemplate; defaultChain?: BaseChain; }; @@ -73,10 +73,10 @@ export class MultiRetrievalQAChain extends MultiRouteChain { * @deprecated Use `fromRetrieversAndPrompts` instead */ static fromRetrievers( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, retrieverNames: string[], retrieverDescriptions: string[], - retrievers: BaseRetriever[], + retrievers: BaseRetrieverInterface[], retrieverPrompts?: PromptTemplate[], defaults?: MultiRetrievalDefaults, options?: Omit @@ -100,7 +100,7 @@ export class MultiRetrievalQAChain extends MultiRouteChain { * @param llm A BaseLanguageModel instance. * @param retrieverNames An array of retriever names. * @param retrieverDescriptions An array of retriever descriptions. - * @param retrievers An array of BaseRetriever instances. + * @param retrievers An array of BaseRetrieverInterface instances. * @param retrieverPrompts An optional array of PromptTemplate instances for the retrievers. * @param defaults An optional MultiRetrievalDefaults instance. * @param multiRetrievalChainOpts Additional optional parameters for the multi-retrieval chain. @@ -108,7 +108,7 @@ export class MultiRetrievalQAChain extends MultiRouteChain { * @returns A new instance of MultiRetrievalQAChain. */ static fromLLMAndRetrievers( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, { retrieverNames, retrieverDescriptions, @@ -120,7 +120,7 @@ export class MultiRetrievalQAChain extends MultiRouteChain { }: { retrieverNames: string[]; retrieverDescriptions: string[]; - retrievers: BaseRetriever[]; + retrievers: BaseRetrieverInterface[]; retrieverPrompts?: PromptTemplate[]; defaults?: MultiRetrievalDefaults; multiRetrievalChainOpts?: Omit; @@ -178,7 +178,7 @@ export class MultiRetrievalQAChain extends MultiRouteChain { const routerChain = LLMRouterChain.fromLLM(llm, routerPrompt); const prompts = retrieverPrompts ?? retrievers.map(() => null); const destinationChains = zipEntries< - [string, BaseRetriever, PromptTemplate | null] + [string, BaseRetrieverInterface, PromptTemplate | null] >(retrieverNames, retrievers, prompts).reduce( (acc, [name, retriever, prompt]) => { const opt: Partial & { diff --git a/langchain/src/chains/router/tests/multi_retrieval_qa.test.ts b/langchain/src/chains/router/tests/multi_retrieval_qa.test.ts index 3ece1946cd0b..23249e2b7089 100644 --- a/langchain/src/chains/router/tests/multi_retrieval_qa.test.ts +++ b/langchain/src/chains/router/tests/multi_retrieval_qa.test.ts @@ -1,8 +1,8 @@ import { test, expect } from "@jest/globals"; +import { BaseRetriever } from "@langchain/core/retrievers"; import { MultiRetrievalQAChain } from "../multi_retrieval_qa.js"; import { BaseLLM } from "../../../llms/base.js"; import { LLMResult } from "../../../schema/index.js"; -import { BaseRetriever } from "../../../schema/retriever.js"; import { Document } from "../../../document.js"; import { PromptTemplate } from "../../../prompts/prompt.js"; diff --git a/langchain/src/chains/sql_db/sql_db_chain.ts b/langchain/src/chains/sql_db/sql_db_chain.ts index bb95d6b089b8..de9cec36c8f8 100644 --- a/langchain/src/chains/sql_db/sql_db_chain.ts +++ b/langchain/src/chains/sql_db/sql_db_chain.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import type { TiktokenModel } from "js-tiktoken/lite"; import { DEFAULT_SQL_DATABASE_PROMPT } from "./sql_db_prompt.js"; import { BaseChain, ChainInputs } from "../base.js"; @@ -5,7 +6,6 @@ import type { OpenAI } from "../../llms/openai.js"; import { LLMChain } from "../llm_chain.js"; import type { SqlDatabase } from "../../sql_db.js"; import { ChainValues } from "../../schema/index.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { calculateMaxTokens, getModelContextSize, @@ -20,7 +20,7 @@ import { PromptTemplate } from "../../prompts/index.js"; * for a SQL database chain. */ export interface SqlDatabaseChainInput extends ChainInputs { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; database: SqlDatabase; topK?: number; inputKey?: string; @@ -60,7 +60,7 @@ export class SqlDatabaseChain extends BaseChain { } // LLM wrapper to use - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; // SQL Database to connect to. database: SqlDatabase; diff --git a/langchain/src/chains/summarization/load.ts b/langchain/src/chains/summarization/load.ts index 76492fb84e6c..b903a4ab9a3f 100644 --- a/langchain/src/chains/summarization/load.ts +++ b/langchain/src/chains/summarization/load.ts @@ -1,4 +1,4 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../llm_chain.js"; import { BasePromptTemplate } from "../../prompts/base.js"; import { @@ -29,18 +29,18 @@ export type SummarizationChainParams = BaseParams & type?: "map_reduce"; combineMapPrompt?: BasePromptTemplate; combinePrompt?: BasePromptTemplate; - combineLLM?: BaseLanguageModel; + combineLLM?: BaseLanguageModelInterface; } & Pick) | { type?: "refine"; refinePrompt?: BasePromptTemplate; - refineLLM?: BaseLanguageModel; + refineLLM?: BaseLanguageModelInterface; questionPrompt?: BasePromptTemplate; } ); export const loadSummarizationChain = ( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, params: SummarizationChainParams = { type: "map_reduce" } ) => { const { verbose } = params; diff --git a/langchain/src/chains/vector_db_qa.ts b/langchain/src/chains/vector_db_qa.ts index c1d50f174028..d6d0c8343c74 100644 --- a/langchain/src/chains/vector_db_qa.ts +++ b/langchain/src/chains/vector_db_qa.ts @@ -1,7 +1,7 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { BaseChain, ChainInputs } from "./base.js"; -import { VectorStore } from "../vectorstores/base.js"; import { SerializedVectorDBQAChain } from "./serde.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { CallbackManagerForChainRun } from "../callbacks/manager.js"; import { ChainValues } from "../schema/index.js"; import { loadQAStuffChain } from "./question_answering/load.js"; @@ -16,7 +16,7 @@ export type LoadValues = Record; * `returnSourceDocuments`, `k`, and `inputKey`. */ export interface VectorDBQAChainInput extends Omit { - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; combineDocumentsChain: BaseChain; returnSourceDocuments?: boolean; k?: number; @@ -48,7 +48,7 @@ export class VectorDBQAChain extends BaseChain implements VectorDBQAChainInput { ); } - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; combineDocumentsChain: BaseChain; @@ -140,8 +140,8 @@ export class VectorDBQAChain extends BaseChain implements VectorDBQAChainInput { * @returns A new instance of VectorDBQAChain. */ static fromLLM( - llm: BaseLanguageModel, - vectorstore: VectorStore, + llm: BaseLanguageModelInterface, + vectorstore: VectorStoreInterface, options?: Partial< Omit > diff --git a/langchain/src/embeddings/cache_backed.ts b/langchain/src/embeddings/cache_backed.ts index 0069a29e92ae..22e3d46013d3 100644 --- a/langchain/src/embeddings/cache_backed.ts +++ b/langchain/src/embeddings/cache_backed.ts @@ -1,16 +1,19 @@ import { insecureHash } from "@langchain/core/utils/hash"; +import { + type EmbeddingsInterface, + Embeddings, +} from "@langchain/core/embeddings"; import { BaseStore } from "../schema/storage.js"; import { EncoderBackedStore } from "../storage/encoder_backed.js"; import { AsyncCallerParams } from "../util/async_caller.js"; -import { Embeddings } from "./base.js"; /** * Interface for the fields required to initialize an instance of the * CacheBackedEmbeddings class. */ export interface CacheBackedEmbeddingsFields extends AsyncCallerParams { - underlyingEmbeddings: Embeddings; + underlyingEmbeddings: EmbeddingsInterface; documentEmbeddingStore: BaseStore; } @@ -62,7 +65,7 @@ export interface CacheBackedEmbeddingsFields extends AsyncCallerParams { * ``` */ export class CacheBackedEmbeddings extends Embeddings { - protected underlyingEmbeddings: Embeddings; + protected underlyingEmbeddings: EmbeddingsInterface; protected documentEmbeddingStore: BaseStore; @@ -135,7 +138,7 @@ export class CacheBackedEmbeddings extends Embeddings { * @returns A new CacheBackedEmbeddings instance. */ static fromBytesStore( - underlyingEmbeddings: Embeddings, + underlyingEmbeddings: EmbeddingsInterface, documentEmbeddingStore: BaseStore, options?: { namespace?: string; diff --git a/langchain/src/evaluation/agents/trajectory.ts b/langchain/src/evaluation/agents/trajectory.ts index ce74746a1e60..4cf78413ee32 100644 --- a/langchain/src/evaluation/agents/trajectory.ts +++ b/langchain/src/evaluation/agents/trajectory.ts @@ -1,3 +1,4 @@ +import type { StructuredToolInterface } from "@langchain/core/tools"; import { BaseLLMOutputParser } from "../../schema/output_parser.js"; import { AgentTrajectoryEvaluator, @@ -16,7 +17,6 @@ import { import { Callbacks } from "../../callbacks/index.js"; import { BaseCallbackConfig } from "../../callbacks/manager.js"; import { BasePromptTemplate } from "../../prompts/index.js"; -import { StructuredTool } from "../../tools/index.js"; import { EVAL_CHAT_PROMPT, TOOL_FREE_EVAL_CHAT_PROMPT } from "./prompt.js"; import { BaseChatModel } from "../../chat_models/base.js"; @@ -94,7 +94,7 @@ export class TrajectoryEvalChain extends AgentTrajectoryEvaluator { static resolveTrajectoryPrompt( prompt?: BasePromptTemplate | undefined, - agentTools?: StructuredTool[] + agentTools?: StructuredToolInterface[] ) { let _prompt; if (prompt) { @@ -113,7 +113,7 @@ export class TrajectoryEvalChain extends AgentTrajectoryEvaluator { * * @returns The description of the agent tools. */ - static toolsDescription(agentTools: StructuredTool[]): string { + static toolsDescription(agentTools: StructuredToolInterface[]): string { return agentTools .map( (tool, i) => @@ -130,7 +130,7 @@ export class TrajectoryEvalChain extends AgentTrajectoryEvaluator { */ static async fromLLM( llm: BaseChatModel, - agentTools?: StructuredTool[], + agentTools?: StructuredToolInterface[], chainOptions?: Partial> ) { let prompt = this.resolveTrajectoryPrompt(chainOptions?.prompt, agentTools); diff --git a/langchain/src/evaluation/base.ts b/langchain/src/evaluation/base.ts index 8b29097d1ba4..f9d1c7c91c31 100644 --- a/langchain/src/evaluation/base.ts +++ b/langchain/src/evaluation/base.ts @@ -1,6 +1,6 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseChain, LLMChain, LLMChainInput } from "../chains/index.js"; import { AgentStep, ChainValues } from "../schema/index.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { Callbacks } from "../callbacks/index.js"; import { BaseCallbackConfig } from "../callbacks/manager.js"; @@ -9,7 +9,7 @@ import { BaseCallbackConfig } from "../callbacks/manager.js"; */ export interface LLMEvalChainInput< T extends EvalOutputType = EvalOutputType, - L extends BaseLanguageModel = BaseLanguageModel + L extends BaseLanguageModelInterface = BaseLanguageModelInterface > extends LLMChainInput {} /** @@ -31,7 +31,7 @@ export type EvalOutputType = Record; */ export abstract class LLMEvalChain< T extends EvalOutputType = EvalOutputType, - L extends BaseLanguageModel = BaseLanguageModel + L extends BaseLanguageModelInterface = BaseLanguageModelInterface > extends LLMChain { requiresInput?: boolean = false; @@ -149,7 +149,7 @@ export interface LLMTrajectoryEvaluatorArgs { */ export abstract class LLMStringEvaluator< T extends EvalOutputType = EvalOutputType, - L extends BaseLanguageModel = BaseLanguageModel + L extends BaseLanguageModelInterface = BaseLanguageModelInterface > extends LLMEvalChain { /** * The name of the evaluation. diff --git a/langchain/src/evaluation/comparison/pairwise.ts b/langchain/src/evaluation/comparison/pairwise.ts index 56ee922db6ca..db19fa7a4782 100644 --- a/langchain/src/evaluation/comparison/pairwise.ts +++ b/langchain/src/evaluation/comparison/pairwise.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseLLMOutputParser } from "../../schema/output_parser.js"; import { eqSet, @@ -14,7 +15,6 @@ import { RUN_KEY, } from "../../schema/index.js"; import { PROMPT, PROMPT_WITH_REFERENCES } from "./prompt.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { Callbacks } from "../../callbacks/index.js"; import { BaseCallbackConfig } from "../../callbacks/manager.js"; import { BasePromptTemplate } from "../../prompts/index.js"; @@ -184,7 +184,7 @@ To use references, use the LabeledPairwiseStringEvalChain instead.`; * @param chainOptions Options to pass to the chain. */ static async fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, criteria?: CriteriaLike, chainOptions?: Partial> ) { diff --git a/langchain/src/evaluation/criteria/criteria.ts b/langchain/src/evaluation/criteria/criteria.ts index d9b608ab2334..54524d4833bf 100644 --- a/langchain/src/evaluation/criteria/criteria.ts +++ b/langchain/src/evaluation/criteria/criteria.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseLLMOutputParser } from "../../schema/output_parser.js"; import { eqSet, @@ -14,7 +15,6 @@ import { RUN_KEY, } from "../../schema/index.js"; import { CRITERIA_PROMPT, PROMPT_WITH_REFERENCES } from "./prompt.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { Callbacks } from "../../callbacks/index.js"; import { BaseCallbackConfig } from "../../callbacks/manager.js"; import { BasePromptTemplate } from "../../prompts/index.js"; @@ -208,7 +208,7 @@ export class CriteriaEvalChain extends LLMStringEvaluator { * @param chainOptions Options to pass to the constructor of the LLMChain. */ static async fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, criteria?: CriteriaLike, chainOptions?: Partial> ) { diff --git a/langchain/src/evaluation/embedding_distance/base.ts b/langchain/src/evaluation/embedding_distance/base.ts index 2f6c07553e88..7df433c9ea3e 100644 --- a/langchain/src/evaluation/embedding_distance/base.ts +++ b/langchain/src/evaluation/embedding_distance/base.ts @@ -1,4 +1,5 @@ import { distance, similarity } from "ml-distance"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { PairwiseStringEvaluator, PairwiseStringEvaluatorArgs, @@ -12,7 +13,6 @@ import { Callbacks, } from "../../callbacks/index.js"; import { BaseCallbackConfig } from "../../callbacks/manager.js"; -import { Embeddings } from "../../embeddings/base.js"; /** * @@ -37,7 +37,7 @@ export interface EmbeddingDistanceEvalChainInput { /** * The embedding objects to vectorize the outputs. */ - embedding?: Embeddings; + embedding?: EmbeddingsInterface; /** * The distance metric to use @@ -95,7 +95,7 @@ export class EmbeddingDistanceEvalChain outputKey = "score"; - embedding?: Embeddings; + embedding?: EmbeddingsInterface; distanceMetric: EmbeddingDistanceType = "cosine"; @@ -158,7 +158,7 @@ export class PairwiseEmbeddingDistanceEvalChain outputKey = "score"; - embedding?: Embeddings; + embedding?: EmbeddingsInterface; distanceMetric: EmbeddingDistanceType = "cosine"; diff --git a/langchain/src/evaluation/loader.ts b/langchain/src/evaluation/loader.ts index 0b9f452903eb..09d5d55fce83 100644 --- a/langchain/src/evaluation/loader.ts +++ b/langchain/src/evaluation/loader.ts @@ -1,4 +1,5 @@ -import { BaseLanguageModel } from "../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { StructuredToolInterface } from "@langchain/core/tools"; import { CriteriaLike, CriteriaEvalChain, @@ -6,7 +7,6 @@ import { } from "./criteria/index.js"; import { ChatOpenAI } from "../chat_models/openai.js"; import type { EvaluatorType } from "./types.js"; -import { StructuredTool } from "../tools/index.js"; import { LLMEvalChainInput } from "./base.js"; import { LabeledPairwiseStringEvalChain, @@ -21,7 +21,7 @@ import { TrajectoryEvalChain } from "./agents/index.js"; import { BaseChatModel } from "../chat_models/base.js"; export type LoadEvaluatorOptions = EmbeddingDistanceEvalChainInput & { - llm?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; chainOptions?: Partial>; /** @@ -32,7 +32,7 @@ export type LoadEvaluatorOptions = EmbeddingDistanceEvalChainInput & { /** * A list of tools available to the agent, for TrajectoryEvalChain. */ - agentTools?: StructuredTool[]; + agentTools?: StructuredToolInterface[]; }; /** diff --git a/langchain/src/evaluation/qa/eval_chain.ts b/langchain/src/evaluation/qa/eval_chain.ts index c895004cf1b4..339df93320e6 100644 --- a/langchain/src/evaluation/qa/eval_chain.ts +++ b/langchain/src/evaluation/qa/eval_chain.ts @@ -1,7 +1,7 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { QA_PROMPT } from "./prompt.js"; import { LLMChain, LLMChainInput } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/prompt.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { ChainValues } from "../../schema/index.js"; export interface EvaluateArgs { @@ -19,7 +19,7 @@ export class QAEvalChain extends LLMChain { } static fromLlm( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, options: { prompt?: PromptTemplate; chainInput?: Omit; diff --git a/langchain/src/experimental/autogpt/agent.ts b/langchain/src/experimental/autogpt/agent.ts index 701485f93aff..b78acec5becc 100644 --- a/langchain/src/experimental/autogpt/agent.ts +++ b/langchain/src/experimental/autogpt/agent.ts @@ -1,6 +1,6 @@ +import type { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores"; import { LLMChain } from "../../chains/llm_chain.js"; import { BaseChatModel } from "../../chat_models/base.js"; -import { VectorStoreRetriever } from "../../vectorstores/base.js"; import { Tool } from "../../tools/base.js"; import { AutoGPTOutputParser } from "./output_parser.js"; @@ -25,7 +25,7 @@ import { export interface AutoGPTInput { aiName: string; aiRole: string; - memory: VectorStoreRetriever; + memory: VectorStoreRetrieverInterface; humanInTheLoop?: boolean; outputParser?: AutoGPTOutputParser; maxIterations?: number; @@ -60,7 +60,7 @@ export interface AutoGPTInput { export class AutoGPT { aiName: string; - memory: VectorStoreRetriever; + memory: VectorStoreRetrieverInterface; fullMessageHistory: BaseMessage[]; diff --git a/langchain/src/experimental/autogpt/prompt.ts b/langchain/src/experimental/autogpt/prompt.ts index 8a6581ecc6e3..c0acf66911a3 100644 --- a/langchain/src/experimental/autogpt/prompt.ts +++ b/langchain/src/experimental/autogpt/prompt.ts @@ -1,3 +1,4 @@ +import type { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores"; import { BaseChatPromptTemplate } from "../../prompts/chat.js"; import { BaseMessage, @@ -5,7 +6,6 @@ import { PartialValues, SystemMessage, } from "../../schema/index.js"; -import { VectorStoreRetriever } from "../../vectorstores/base.js"; import { ObjectTool } from "./schema.js"; import { getPrompt } from "./prompt_generator.js"; import { SerializedBasePromptTemplate } from "../../prompts/serde.js"; @@ -90,7 +90,7 @@ export class AutoGPTPrompt user_input, }: { goals: string[]; - memory: VectorStoreRetriever; + memory: VectorStoreRetrieverInterface; messages: BaseMessage[]; user_input: string; }) { diff --git a/langchain/src/experimental/babyagi/agent.ts b/langchain/src/experimental/babyagi/agent.ts index a7258786807a..91e8b5393052 100644 --- a/langchain/src/experimental/babyagi/agent.ts +++ b/langchain/src/experimental/babyagi/agent.ts @@ -1,11 +1,11 @@ -import { BaseLanguageModel } from "../../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { BaseChain, ChainInputs } from "../../chains/base.js"; import { SerializedBaseChain } from "../../chains/serde.js"; import { Document } from "../../document.js"; import { ChainValues } from "../../schema/index.js"; import { Optional } from "../../types/type-utils.js"; -import { VectorStore } from "../../vectorstores/base.js"; import { TaskCreationChain } from "./task_creation.js"; import { TaskExecutionChain } from "./task_execution.js"; import { TaskPrioritizationChain } from "./task_prioritization.js"; @@ -30,7 +30,7 @@ export interface BabyAGIInputs creationChain: BaseChain; prioritizationChain: BaseChain; executionChain: BaseChain; - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; maxIterations?: number; } @@ -67,7 +67,7 @@ export class BabyAGI extends BaseChain implements BabyAGIInputs { taskIDCounter: number; - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; maxIterations: number; @@ -328,7 +328,7 @@ export class BabyAGI extends BaseChain implements BabyAGIInputs { }: Optional< BabyAGIInputs, "executionChain" | "creationChain" | "prioritizationChain" - > & { llm: BaseLanguageModel }) { + > & { llm: BaseLanguageModelInterface }) { const creationChain = TaskCreationChain.fromLLM({ llm, verbose, diff --git a/langchain/src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts b/langchain/src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts index b7a3382bac8f..d45215ccc3e7 100644 --- a/langchain/src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts +++ b/langchain/src/experimental/chains/violation_of_expectations/violation_of_expectations_chain.ts @@ -1,3 +1,4 @@ +import type { BaseRetrieverInterface } from "@langchain/core/retrievers"; import { CallbackManagerForChainRun } from "../../../callbacks/manager.js"; import { ChatOpenAI } from "../../../chat_models/openai.js"; import { JsonOutputFunctionsParser } from "../../../output_parsers/openai_functions.js"; @@ -8,7 +9,6 @@ import { isBaseMessage, } from "../../../schema/index.js"; import { StringOutputParser } from "../../../schema/output_parser.js"; -import { BaseRetriever } from "../../../schema/retriever.js"; import { BaseChain, ChainInputs } from "../../../chains/base.js"; import { GetPredictionViolationsResponse, @@ -32,7 +32,7 @@ export interface ViolationOfExpectationsChainInput extends ChainInputs { * The retriever to use for retrieving stored * thoughts and insights. */ - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; /** * The LLM to use */ @@ -67,7 +67,7 @@ export class ViolationOfExpectationsChain return [this.thoughtsKey]; } - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; llm: ChatOpenAI; @@ -467,7 +467,7 @@ export class ViolationOfExpectationsChain */ static fromLLM( llm: ChatOpenAI, - retriever: BaseRetriever, + retriever: BaseRetrieverInterface, options?: Partial< Omit > diff --git a/langchain/src/experimental/chat_models/anthropic_functions.ts b/langchain/src/experimental/chat_models/anthropic_functions.ts index 76e60736d175..1ea405ae8f11 100644 --- a/langchain/src/experimental/chat_models/anthropic_functions.ts +++ b/langchain/src/experimental/chat_models/anthropic_functions.ts @@ -1,4 +1,5 @@ import { XMLParser } from "fast-xml-parser"; +import type { StructuredToolInterface } from "@langchain/core/tools"; import { BaseChatModel, BaseChatModelParams } from "../../chat_models/base.js"; import { CallbackManagerForLLMRun } from "../../callbacks/manager.js"; @@ -15,7 +16,6 @@ import { type AnthropicInput, } from "../../chat_models/anthropic.js"; import { BaseFunctionCallOptions } from "../../base_language/index.js"; -import { StructuredTool } from "../../tools/base.js"; import { PromptTemplate } from "../../prompts/prompt.js"; import { formatToOpenAIFunction } from "../../tools/convert_to_openai.js"; @@ -42,7 +42,7 @@ for the weather in SF you would respond: export interface ChatAnthropicFunctionsCallOptions extends BaseFunctionCallOptions { - tools?: StructuredTool[]; + tools?: StructuredToolInterface[]; } export type AnthropicFunctionsInput = Partial & diff --git a/langchain/src/experimental/generative_agents/generative_agent.ts b/langchain/src/experimental/generative_agents/generative_agent.ts index 95dbd99502c4..45e1f82986da 100644 --- a/langchain/src/experimental/generative_agents/generative_agent.ts +++ b/langchain/src/experimental/generative_agents/generative_agent.ts @@ -1,6 +1,6 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/index.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { GenerativeAgentMemory } from "./generative_agent_memory.js"; import { ChainValues } from "../../schema/index.js"; import { BaseChain } from "../../chains/base.js"; @@ -75,7 +75,7 @@ export class GenerativeAgent extends BaseChain { longTermMemory: GenerativeAgentMemory; - llm: BaseLanguageModel; // the underlying language model + llm: BaseLanguageModelInterface; // the underlying language model verbose: boolean; // false @@ -101,7 +101,7 @@ export class GenerativeAgent extends BaseChain { } constructor( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, longTermMemory: GenerativeAgentMemory, config: GenerativeAgentConfig ) { diff --git a/langchain/src/experimental/generative_agents/generative_agent_memory.ts b/langchain/src/experimental/generative_agents/generative_agent_memory.ts index c3a6cfed3c02..e55fc136ca97 100644 --- a/langchain/src/experimental/generative_agents/generative_agent_memory.ts +++ b/langchain/src/experimental/generative_agents/generative_agent_memory.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/index.js"; import { BaseChain } from "../../chains/base.js"; @@ -8,7 +9,6 @@ import { CallbackManagerForChainRun, Callbacks, } from "../../callbacks/manager.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { ChainValues } from "../../schema/index.js"; export type GenerativeAgentMemoryConfig = { @@ -38,14 +38,14 @@ class GenerativeAgentMemoryChain extends BaseChain { memoryRetriever: TimeWeightedVectorStoreRetriever; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; verbose = false; private aggregateImportance = 0.0; constructor( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, memoryRetriever: TimeWeightedVectorStoreRetriever, config: Omit ) { @@ -313,7 +313,7 @@ class GenerativeAgentMemoryChain extends BaseChain { * ``` */ export class GenerativeAgentMemory extends BaseMemory { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; memoryRetriever: TimeWeightedVectorStoreRetriever; @@ -340,7 +340,7 @@ export class GenerativeAgentMemory extends BaseMemory { memoryChain: GenerativeAgentMemoryChain; constructor( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, memoryRetriever: TimeWeightedVectorStoreRetriever, config?: GenerativeAgentMemoryConfig ) { diff --git a/langchain/src/experimental/hubs/makersuite/googlemakersuitehub.ts b/langchain/src/experimental/hubs/makersuite/googlemakersuitehub.ts index a9a5e83bc5b3..13348ca7513c 100644 --- a/langchain/src/experimental/hubs/makersuite/googlemakersuitehub.ts +++ b/langchain/src/experimental/hubs/makersuite/googlemakersuitehub.ts @@ -1,11 +1,11 @@ import type { protos } from "@google-ai/generativelanguage"; import type { google } from "@google-ai/generativelanguage/build/protos/protos.js"; import { GoogleAuth, GoogleAuthOptions } from "google-auth-library"; +import type { BaseLanguageModel } from "@langchain/core/language_models/base"; import { GooglePaLM } from "../../../llms/googlepalm.js"; import { ChatGooglePaLM } from "../../../chat_models/googlepalm.js"; import { PromptTemplate } from "../../../prompts/index.js"; -import { BaseLanguageModel } from "../../../base_language/index.js"; import { Runnable } from "../../../schema/runnable/index.js"; import { AsyncCaller, diff --git a/langchain/src/experimental/plan_and_execute/agent_executor.ts b/langchain/src/experimental/plan_and_execute/agent_executor.ts index 32e44e539131..440bd55d9ad7 100644 --- a/langchain/src/experimental/plan_and_execute/agent_executor.ts +++ b/langchain/src/experimental/plan_and_execute/agent_executor.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseChain, ChainInputs } from "../../chains/base.js"; import { BasePlanner, @@ -13,7 +14,6 @@ import { getPlannerChatPrompt, } from "./prompt.js"; import { ChainValues } from "../../schema/index.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { CallbackManagerForChainRun } from "../../callbacks/manager.js"; import { LLMChain } from "../../chains/llm_chain.js"; import { PlanOutputParser } from "./outputParser.js"; @@ -103,7 +103,7 @@ export class PlanAndExecuteAgentExecutor extends BaseChain { llm, tools, }: { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; tools: Tool[] | DynamicStructuredTool[]; }) { const plannerLlmChain = new LLMChain({ @@ -127,7 +127,7 @@ export class PlanAndExecuteAgentExecutor extends BaseChain { tools, humanMessageTemplate = DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE, }: { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; tools: Tool[] | DynamicStructuredTool[]; humanMessageTemplate?: string; }) { @@ -172,7 +172,7 @@ export class PlanAndExecuteAgentExecutor extends BaseChain { tools, humanMessageTemplate, }: { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; tools: Tool[] | DynamicStructuredTool[]; humanMessageTemplate?: string; } & Omit) { diff --git a/langchain/src/llms/load.ts b/langchain/src/llms/load.ts index be95ee9cf864..fe89cfdd4b84 100644 --- a/langchain/src/llms/load.ts +++ b/langchain/src/llms/load.ts @@ -1,5 +1,5 @@ +import { BaseLanguageModel } from "@langchain/core/language_models/base"; import { FileLoader, loadFromFile } from "../util/load.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { parseFileConfig } from "../util/parse.js"; /** diff --git a/langchain/src/memory/buffer_token_memory.ts b/langchain/src/memory/buffer_token_memory.ts index ad93c0903c0a..0cbb1cf08511 100644 --- a/langchain/src/memory/buffer_token_memory.ts +++ b/langchain/src/memory/buffer_token_memory.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { InputValues, MemoryVariables, @@ -6,7 +7,6 @@ import { } from "./base.js"; import { BaseChatMemory, BaseChatMemoryInput } from "./chat_memory.js"; -import { BaseLanguageModel } from "../base_language/index.js"; /** * Interface for the input parameters of the `BufferTokenMemory` class. @@ -21,7 +21,7 @@ export interface ConversationTokenBufferMemoryInput aiPrefix?: string; /* The LLM for this instance. */ - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; /* Memory key for buffer instance. */ memoryKey?: string; @@ -63,7 +63,7 @@ export class ConversationTokenBufferMemory maxTokenLimit = 2000; // Default max token limit of 2000 which can be overridden - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; constructor(fields: ConversationTokenBufferMemoryInput) { super(fields); diff --git a/langchain/src/memory/entity_memory.ts b/langchain/src/memory/entity_memory.ts index cb3b060419a6..9ec30ca41d35 100644 --- a/langchain/src/memory/entity_memory.ts +++ b/langchain/src/memory/entity_memory.ts @@ -1,4 +1,4 @@ -import { BaseLanguageModel } from "../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseEntityStore } from "../schema/index.js"; import { BaseChatMemory, BaseChatMemoryInput } from "./chat_memory.js"; @@ -21,7 +21,7 @@ import { InMemoryEntityStore } from "./stores/entity/in_memory.js"; * Interface for the input parameters required by the EntityMemory class. */ export interface EntityMemoryInput extends BaseChatMemoryInput { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; humanPrefix?: string; aiPrefix?: string; entityExtractionPrompt?: PromptTemplate; @@ -81,7 +81,7 @@ export class EntityMemory extends BaseChatMemory implements EntityMemoryInput { chatHistoryKey = "history"; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; entitiesKey = "entities"; diff --git a/langchain/src/memory/summary.ts b/langchain/src/memory/summary.ts index 0e299af7596d..8d07a5b5ddf0 100644 --- a/langchain/src/memory/summary.ts +++ b/langchain/src/memory/summary.ts @@ -1,4 +1,4 @@ -import { BaseLanguageModel } from "../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { LLMChain } from "../chains/llm_chain.js"; import { BasePromptTemplate } from "../prompts/base.js"; import { BaseMessage, SystemMessage } from "../schema/index.js"; @@ -24,7 +24,7 @@ export interface ConversationSummaryMemoryInput */ export interface BaseConversationSummaryMemoryInput extends BaseChatMemoryInput { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; memoryKey?: string; humanPrefix?: string; aiPrefix?: string; @@ -44,7 +44,7 @@ export abstract class BaseConversationSummaryMemory extends BaseChatMemory { aiPrefix = "AI"; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; prompt: BasePromptTemplate = SUMMARY_PROMPT; diff --git a/langchain/src/memory/vector_store.ts b/langchain/src/memory/vector_store.ts index a0ba15b781d3..d97dd72db67a 100644 --- a/langchain/src/memory/vector_store.ts +++ b/langchain/src/memory/vector_store.ts @@ -1,6 +1,6 @@ +import type { VectorStoreRetrieverInterface } from "@langchain/core/vectorstores"; import { Document } from "../document.js"; import { formatDocumentsAsString } from "../util/document.js"; -import { VectorStoreRetriever } from "../vectorstores/base.js"; import { BaseMemory, getInputValue, @@ -14,7 +14,7 @@ import { * VectorStoreRetrieverMemory instance. */ export interface VectorStoreRetrieverMemoryParams { - vectorStoreRetriever: VectorStoreRetriever; + vectorStoreRetriever: VectorStoreRetrieverInterface; inputKey?: string; outputKey?: string; memoryKey?: string; @@ -56,7 +56,7 @@ export class VectorStoreRetrieverMemory extends BaseMemory implements VectorStoreRetrieverMemoryParams { - vectorStoreRetriever: VectorStoreRetriever; + vectorStoreRetriever: VectorStoreRetrieverInterface; inputKey?: string; diff --git a/langchain/src/output_parsers/fix.ts b/langchain/src/output_parsers/fix.ts index 8972bdfaf43b..34918c3aea92 100644 --- a/langchain/src/output_parsers/fix.ts +++ b/langchain/src/output_parsers/fix.ts @@ -1,10 +1,10 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { BaseOutputParser, OutputParserException, } from "../schema/output_parser.js"; import { BasePromptTemplate } from "../prompts/base.js"; import { LLMChain } from "../chains/llm_chain.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { Callbacks } from "../callbacks/manager.js"; import { NAIVE_FIX_PROMPT } from "./prompts.js"; @@ -35,7 +35,7 @@ export class OutputFixingParser extends BaseOutputParser { * @returns A new instance of OutputFixingParser. */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, parser: BaseOutputParser, fields?: { prompt?: BasePromptTemplate; diff --git a/langchain/src/retrievers/contextual_compression.ts b/langchain/src/retrievers/contextual_compression.ts index 93fc8f0ebbef..744320e3111f 100644 --- a/langchain/src/retrievers/contextual_compression.ts +++ b/langchain/src/retrievers/contextual_compression.ts @@ -1,6 +1,10 @@ +import { + BaseRetriever, + type BaseRetrieverInput, + type BaseRetrieverInterface, +} from "@langchain/core/retrievers"; +import type { DocumentInterface } from "@langchain/core/documents"; import { BaseDocumentCompressor } from "./document_compressors/index.js"; -import { Document } from "../document.js"; -import { BaseRetriever, BaseRetrieverInput } from "../schema/retriever.js"; import { CallbackManagerForRetrieverRun } from "../callbacks/manager.js"; /** @@ -10,7 +14,7 @@ import { CallbackManagerForRetrieverRun } from "../callbacks/manager.js"; */ export interface ContextualCompressionRetrieverArgs extends BaseRetrieverInput { baseCompressor: BaseDocumentCompressor; - baseRetriever: BaseRetriever; + baseRetriever: BaseRetrieverInterface; } /** @@ -37,7 +41,7 @@ export class ContextualCompressionRetriever extends BaseRetriever { baseCompressor: BaseDocumentCompressor; - baseRetriever: BaseRetriever; + baseRetriever: BaseRetrieverInterface; constructor(fields: ContextualCompressionRetrieverArgs) { super(fields); @@ -49,7 +53,7 @@ export class ContextualCompressionRetriever extends BaseRetriever { async _getRelevantDocuments( query: string, runManager?: CallbackManagerForRetrieverRun - ): Promise { + ): Promise { const docs = await this.baseRetriever.getRelevantDocuments( query, runManager?.getChild("base_retriever") diff --git a/langchain/src/retrievers/document_compressors/chain_extract.ts b/langchain/src/retrievers/document_compressors/chain_extract.ts index e4074616963b..09d926283a17 100644 --- a/langchain/src/retrievers/document_compressors/chain_extract.ts +++ b/langchain/src/retrievers/document_compressors/chain_extract.ts @@ -1,14 +1,14 @@ -import { Document } from "../../document.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import { type DocumentInterface, Document } from "@langchain/core/documents"; import { LLMChain } from "../../chains/llm_chain.js"; import { PromptTemplate } from "../../prompts/index.js"; -import { BaseLanguageModel } from "../../base_language/index.js"; import { BaseOutputParser } from "../../schema/output_parser.js"; import { BaseDocumentCompressor } from "./index.js"; import { PROMPT_TEMPLATE } from "./chain_extract_prompt.js"; function defaultGetInput( query: string, - doc: Document + doc: DocumentInterface ): Record { return { question: query, context: doc.pageContent }; } @@ -52,7 +52,7 @@ function getDefaultChainPrompt(): PromptTemplate { */ export interface LLMChainExtractorArgs { llmChain: LLMChain; - getInput: (query: string, doc: Document) => Record; + getInput: (query: string, doc: DocumentInterface) => Record; } /** @@ -62,7 +62,7 @@ export interface LLMChainExtractorArgs { export class LLMChainExtractor extends BaseDocumentCompressor { llmChain: LLMChain; - getInput: (query: string, doc: Document) => Record = + getInput: (query: string, doc: DocumentInterface) => Record = defaultGetInput; constructor({ llmChain, getInput }: LLMChainExtractorArgs) { @@ -78,9 +78,9 @@ export class LLMChainExtractor extends BaseDocumentCompressor { * @returns A list of compressed documents. */ async compressDocuments( - documents: Document[], + documents: DocumentInterface[], query: string - ): Promise { + ): Promise { const compressedDocs = await Promise.all( documents.map(async (doc) => { const input = this.getInput(query, doc); @@ -105,9 +105,12 @@ export class LLMChainExtractor extends BaseDocumentCompressor { * @returns A new instance of LLMChainExtractor. */ static fromLLM( - llm: BaseLanguageModel, + llm: BaseLanguageModelInterface, prompt?: PromptTemplate, - getInput?: (query: string, doc: Document) => Record + getInput?: ( + query: string, + doc: DocumentInterface + ) => Record ): LLMChainExtractor { const _prompt = prompt || getDefaultChainPrompt(); const _getInput = getInput || defaultGetInput; diff --git a/langchain/src/retrievers/document_compressors/embeddings_filter.ts b/langchain/src/retrievers/document_compressors/embeddings_filter.ts index 223e5507fd28..f0eb442fd133 100644 --- a/langchain/src/retrievers/document_compressors/embeddings_filter.ts +++ b/langchain/src/retrievers/document_compressors/embeddings_filter.ts @@ -1,5 +1,5 @@ -import { Document } from "../../document.js"; -import { Embeddings } from "../../embeddings/base.js"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; +import type { DocumentInterface } from "@langchain/core/documents"; import { BaseDocumentCompressor } from "./index.js"; import { cosineSimilarity } from "../../util/math.js"; @@ -7,7 +7,7 @@ import { cosineSimilarity } from "../../util/math.js"; * Interface for the parameters of the `EmbeddingsFilter` class. */ export interface EmbeddingsFilterParams { - embeddings: Embeddings; + embeddings: EmbeddingsInterface; similarityFn?: (x: number[][], y: number[][]) => number[][]; similarityThreshold?: number; k?: number; @@ -34,7 +34,7 @@ export class EmbeddingsFilter extends BaseDocumentCompressor { /** * Embeddings to use for embedding document contents and queries. */ - embeddings: Embeddings; + embeddings: EmbeddingsInterface; /** * Similarity function for comparing documents. @@ -65,9 +65,9 @@ export class EmbeddingsFilter extends BaseDocumentCompressor { } async compressDocuments( - documents: Document[], + documents: DocumentInterface[], query: string - ): Promise { + ): Promise { const embeddedDocuments = await this.embeddings.embedDocuments( documents.map((doc) => doc.pageContent) ); diff --git a/langchain/src/retrievers/document_compressors/index.ts b/langchain/src/retrievers/document_compressors/index.ts index 11702d38b252..4b0bcde151ff 100644 --- a/langchain/src/retrievers/document_compressors/index.ts +++ b/langchain/src/retrievers/document_compressors/index.ts @@ -1,4 +1,4 @@ -import { Document } from "../../document.js"; +import type { DocumentInterface } from "@langchain/core/documents"; import { BaseDocumentTransformer } from "../../schema/document.js"; import { Callbacks } from "../../callbacks/manager.js"; @@ -16,10 +16,10 @@ export abstract class BaseDocumentCompressor { * @returns A Promise that resolves with an array of compressed `Document` objects. */ abstract compressDocuments( - documents: Document[], + documents: DocumentInterface[], query: string, callbacks?: Callbacks - ): Promise; + ): Promise; // eslint-disable-next-line @typescript-eslint/no-explicit-any static isBaseDocumentCompressor(x: any): x is BaseDocumentCompressor { @@ -67,10 +67,10 @@ export class DocumentCompressorPipeline extends BaseDocumentCompressor { } async compressDocuments( - documents: Document[], + documents: DocumentInterface[], query: string, callbacks?: Callbacks - ): Promise { + ): Promise { let transformedDocuments = documents; for (const transformer of this.transformers) { if (BaseDocumentCompressor.isBaseDocumentCompressor(transformer)) { diff --git a/langchain/src/retrievers/hyde.ts b/langchain/src/retrievers/hyde.ts index aca4db4546ad..7b5499c581bf 100644 --- a/langchain/src/retrievers/hyde.ts +++ b/langchain/src/retrievers/hyde.ts @@ -1,3 +1,4 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { Document } from "../document.js"; import { BasePromptTemplate, StringPromptValue } from "../prompts/base.js"; import { PromptTemplate } from "../prompts/prompt.js"; @@ -6,7 +7,6 @@ import { VectorStoreRetriever, VectorStoreRetrieverInput, } from "../vectorstores/base.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { BasePromptValue } from "../schema/index.js"; import { CallbackManagerForRetrieverRun } from "../callbacks/manager.js"; @@ -30,7 +30,7 @@ export type PromptKey = */ export type HydeRetrieverOptions = VectorStoreRetrieverInput & { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; promptTemplate?: BasePromptTemplate | PromptKey; }; @@ -70,7 +70,7 @@ export class HydeRetriever< return ["langchain", "retrievers", "hyde"]; } - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; promptTemplate?: BasePromptTemplate; diff --git a/langchain/src/retrievers/multi_query.ts b/langchain/src/retrievers/multi_query.ts index 09a7a3bdad0f..c08fb5aa1ccf 100644 --- a/langchain/src/retrievers/multi_query.ts +++ b/langchain/src/retrievers/multi_query.ts @@ -1,10 +1,14 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import { + BaseRetriever, + type BaseRetrieverInput, + type BaseRetrieverInterface, +} from "@langchain/core/retrievers"; import { LLMChain } from "../chains/llm_chain.js"; import { PromptTemplate } from "../prompts/prompt.js"; import { Document } from "../document.js"; import { BaseOutputParser } from "../schema/output_parser.js"; -import { BaseRetriever, BaseRetrieverInput } from "../schema/retriever.js"; import { CallbackManagerForRetrieverRun } from "../callbacks/index.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { BasePromptTemplate } from "../prompts/base.js"; interface LineList { @@ -59,7 +63,7 @@ Original question: {question}`, }); export interface MultiQueryRetrieverInput extends BaseRetrieverInput { - retriever: BaseRetriever; + retriever: BaseRetrieverInterface; llmChain: LLMChain; queryCount?: number; parserKey?: string; @@ -85,7 +89,7 @@ export class MultiQueryRetriever extends BaseRetriever { lc_namespace = ["langchain", "retrievers", "multiquery"]; - private retriever: BaseRetriever; + private retriever: BaseRetrieverInterface; private llmChain: LLMChain; @@ -103,7 +107,7 @@ export class MultiQueryRetriever extends BaseRetriever { static fromLLM( fields: Omit & { - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; prompt?: BasePromptTemplate; } ): MultiQueryRetriever { diff --git a/langchain/src/retrievers/multi_vector.ts b/langchain/src/retrievers/multi_vector.ts index 6c778d9f5a8e..7c945c9575c8 100644 --- a/langchain/src/retrievers/multi_vector.ts +++ b/langchain/src/retrievers/multi_vector.ts @@ -1,13 +1,16 @@ +import { + BaseRetriever, + type BaseRetrieverInput, +} from "@langchain/core/retrievers"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { BaseStoreInterface } from "../schema/storage.js"; import { Document } from "../document.js"; -import { BaseRetriever, BaseRetrieverInput } from "../schema/retriever.js"; -import { VectorStore } from "../vectorstores/base.js"; /** * Arguments for the MultiVectorRetriever class. */ export interface MultiVectorRetrieverInput extends BaseRetrieverInput { - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; docstore: BaseStoreInterface; idKey?: string; childK?: number; @@ -39,7 +42,7 @@ export class MultiVectorRetriever extends BaseRetriever { lc_namespace = ["langchain", "retrievers", "multi_vector"]; - public vectorstore: VectorStore; + public vectorstore: VectorStoreInterface; public docstore: BaseStoreInterface; diff --git a/langchain/src/retrievers/parent_document.ts b/langchain/src/retrievers/parent_document.ts index 3783d4bfdd27..4a94cfa92a29 100644 --- a/langchain/src/retrievers/parent_document.ts +++ b/langchain/src/retrievers/parent_document.ts @@ -1,7 +1,10 @@ import * as uuid from "uuid"; +import { + type VectorStoreInterface, + type VectorStoreRetrieverInterface, +} from "@langchain/core/vectorstores"; import { Document } from "../document.js"; -import { VectorStore, VectorStoreRetriever } from "../vectorstores/base.js"; import { TextSplitter } from "../text_splitter.js"; import { MultiVectorRetriever, @@ -19,7 +22,7 @@ export type ParentDocumentRetrieverFields = MultiVectorRetrieverInput & { * A custom retriever to use when retrieving instead of * the `.similaritySearch` method of the vectorstore. */ - childDocumentRetriever?: VectorStoreRetriever; + childDocumentRetriever?: VectorStoreRetrieverInterface; }; /** @@ -59,7 +62,7 @@ export class ParentDocumentRetriever extends MultiVectorRetriever { lc_namespace = ["langchain", "retrievers", "parent_document"]; - vectorstore: VectorStore; + vectorstore: VectorStoreInterface; protected childSplitter: TextSplitter; @@ -71,7 +74,9 @@ export class ParentDocumentRetriever extends MultiVectorRetriever { protected parentK?: number; - childDocumentRetriever: VectorStoreRetriever | undefined; + childDocumentRetriever: + | VectorStoreRetrieverInterface + | undefined; constructor(fields: ParentDocumentRetrieverFields) { super(fields); diff --git a/langchain/src/retrievers/remote/base.ts b/langchain/src/retrievers/remote/base.ts index e32e3bcf7e2b..54ab7a8855ec 100644 --- a/langchain/src/retrievers/remote/base.ts +++ b/langchain/src/retrievers/remote/base.ts @@ -1,4 +1,7 @@ -import { BaseRetriever, BaseRetrieverInput } from "../../schema/retriever.js"; +import { + BaseRetriever, + type BaseRetrieverInput, +} from "@langchain/core/retrievers"; import { AsyncCaller, AsyncCallerParams } from "../../util/async_caller.js"; import { Document } from "../../document.js"; diff --git a/langchain/src/retrievers/self_query/index.ts b/langchain/src/retrievers/self_query/index.ts index 27bd464ad96a..b9299bec4a01 100644 --- a/langchain/src/retrievers/self_query/index.ts +++ b/langchain/src/retrievers/self_query/index.ts @@ -1,3 +1,7 @@ +import { + BaseRetriever, + type BaseRetrieverInput, +} from "@langchain/core/retrievers"; import { LLMChain } from "../../chains/llm_chain.js"; import { QueryConstructorChainOptions, @@ -5,7 +9,6 @@ import { } from "../../chains/query_constructor/index.js"; import { StructuredQuery } from "../../chains/query_constructor/ir.js"; import { Document } from "../../document.js"; -import { BaseRetriever, BaseRetrieverInput } from "../../schema/retriever.js"; import { VectorStore } from "../../vectorstores/base.js"; import { FunctionalTranslator } from "./functional.js"; import { BaseTranslator, BasicTranslator } from "./base.js"; diff --git a/langchain/src/retrievers/time_weighted.ts b/langchain/src/retrievers/time_weighted.ts index 29c3ac51546a..8a9b68b68169 100644 --- a/langchain/src/retrievers/time_weighted.ts +++ b/langchain/src/retrievers/time_weighted.ts @@ -1,6 +1,6 @@ -import { VectorStore } from "../vectorstores/base.js"; -import { Document } from "../document.js"; -import { BaseRetriever, BaseRetrieverInput } from "../schema/retriever.js"; +import { BaseRetriever, BaseRetrieverInput } from "@langchain/core/retrievers"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; +import type { DocumentInterface } from "@langchain/core/documents"; import { CallbackManagerForRetrieverRun } from "../callbacks/manager.js"; /** @@ -9,9 +9,9 @@ import { CallbackManagerForRetrieverRun } from "../callbacks/manager.js"; */ export interface TimeWeightedVectorStoreRetrieverFields extends BaseRetrieverInput { - vectorStore: VectorStore; + vectorStore: VectorStoreInterface; searchKwargs?: number; - memoryStream?: Document[]; + memoryStream?: DocumentInterface[]; decayRate?: number; k?: number; otherScoreKeys?: string[]; @@ -53,7 +53,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { /** * The vectorstore to store documents and determine salience. */ - private vectorStore: VectorStore; + private vectorStore: VectorStoreInterface; /** * The number of top K most relevant documents to consider when searching. @@ -63,7 +63,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { /** * The memory_stream of documents to search through. */ - private memoryStream: Document[]; + private memoryStream: DocumentInterface[]; /** * The exponential decay factor used as (1.0-decay_rate)**(hrs_passed). @@ -104,7 +104,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * Get the memory stream of documents. * @returns The memory stream of documents. */ - getMemoryStream(): Document[] { + getMemoryStream(): DocumentInterface[] { return this.memoryStream; } @@ -112,7 +112,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * Set the memory stream of documents. * @param memoryStream The new memory stream of documents. */ - setMemoryStream(memoryStream: Document[]) { + setMemoryStream(memoryStream: DocumentInterface[]) { this.memoryStream = memoryStream; } @@ -124,7 +124,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { async _getRelevantDocuments( query: string, runManager?: CallbackManagerForRetrieverRun - ): Promise { + ): Promise { const now = Math.floor(Date.now() / 1000); const memoryDocsAndScores = this.getMemoryDocsAndScores(); @@ -145,7 +145,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * * @param docs - The documents to add to vector store in the retriever */ - async addDocuments(docs: Document[]): Promise { + async addDocuments(docs: DocumentInterface[]): Promise { const now = Math.floor(Date.now() / 1000); const savedDocs = this.prepareDocuments(docs, now); @@ -159,11 +159,11 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { */ private getMemoryDocsAndScores(): Record< number, - { doc: Document; score: number } + { doc: DocumentInterface; score: number } > { const memoryDocsAndScores: Record< number, - { doc: Document; score: number } + { doc: DocumentInterface; score: number } > = {}; for (const doc of this.memoryStream.slice(-this.k)) { const bufferIdx = doc.metadata[BUFFER_IDX]; @@ -188,15 +188,16 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { private async getSalientDocuments( query: string, runManager?: CallbackManagerForRetrieverRun - ): Promise> { - const docAndScores: [Document, number][] = + ): Promise> { + const docAndScores: [DocumentInterface, number][] = await this.vectorStore.similaritySearchWithScore( query, this.searchKwargs, undefined, runManager?.getChild() ); - const results: Record = {}; + const results: Record = + {}; for (const [fetchedDoc, score] of docAndScores) { const bufferIdx = fetchedDoc.metadata[BUFFER_IDX]; if (bufferIdx === undefined) { @@ -217,9 +218,9 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * @returns The final set of documents */ private computeResults( - docsAndScores: Record, + docsAndScores: Record, now: number - ): Document[] { + ): DocumentInterface[] { const recordedDocs = Object.values(docsAndScores) .map(({ doc, score }) => ({ doc, @@ -227,7 +228,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { })) .sort((a, b) => b.score - a.score); - const results: Document[] = []; + const results: DocumentInterface[] = []; for (const { doc } of recordedDocs) { const bufferedDoc = this.memoryStream[doc.metadata[BUFFER_IDX]]; bufferedDoc.metadata[LAST_ACCESSED_AT_KEY] = now; @@ -245,7 +246,10 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * @param now - The current timestamp * @returns The prepared documents */ - private prepareDocuments(docs: Document[], now: number): Document[] { + private prepareDocuments( + docs: DocumentInterface[], + now: number + ): DocumentInterface[] { return docs.map((doc, i) => ({ ...doc, metadata: { @@ -265,7 +269,7 @@ export class TimeWeightedVectorStoreRetriever extends BaseRetriever { * @returns The combined score for the document */ private getCombinedScore( - doc: Document, + doc: DocumentInterface, vectorRelevance: number | null, nowMsec: number ): number { diff --git a/langchain/src/schema/index.ts b/langchain/src/schema/index.ts index 1fa111c7e7fa..322261a64560 100644 --- a/langchain/src/schema/index.ts +++ b/langchain/src/schema/index.ts @@ -87,7 +87,6 @@ export { export { BasePromptValue } from "@langchain/core/prompt_values"; -// eslint-disable-next-line @typescript-eslint/no-explicit-any export { type InputValues, type PartialValues, diff --git a/langchain/src/schema/runnable/base.ts b/langchain/src/schema/runnable/base.ts index e4d45ce37c5a..e44c6cc5160b 100644 --- a/langchain/src/schema/runnable/base.ts +++ b/langchain/src/schema/runnable/base.ts @@ -4,6 +4,7 @@ export { type RunnableBatchOptions, type RunnableRetryFailedAttemptHandler, Runnable, + type RunnableInterface, type RunnableBindingArgs, RunnableBinding, RunnableEach, diff --git a/langchain/src/tools/convert_to_openai.ts b/langchain/src/tools/convert_to_openai.ts index b5a875324ec8..a552945eda78 100644 --- a/langchain/src/tools/convert_to_openai.ts +++ b/langchain/src/tools/convert_to_openai.ts @@ -1,7 +1,6 @@ import { zodToJsonSchema } from "zod-to-json-schema"; import type { OpenAIClient } from "@langchain/openai"; - -import { StructuredTool } from "./base.js"; +import type { StructuredToolInterface } from "@langchain/core/tools"; /** * Formats a `StructuredTool` instance into a format that is compatible @@ -10,7 +9,7 @@ import { StructuredTool } from "./base.js"; * schema, which is then used as the parameters for the OpenAI function. */ export function formatToOpenAIFunction( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Chat.ChatCompletionCreateParams.Function { return { name: tool.name, @@ -20,7 +19,7 @@ export function formatToOpenAIFunction( } export function formatToOpenAITool( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Chat.ChatCompletionTool { const schema = zodToJsonSchema(tool.schema); return { @@ -34,7 +33,7 @@ export function formatToOpenAITool( } export function formatToOpenAIAssistantTool( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction { return { type: "function", diff --git a/langchain/src/tools/render.ts b/langchain/src/tools/render.ts index 6f66734756e1..bd3fd2b3f623 100644 --- a/langchain/src/tools/render.ts +++ b/langchain/src/tools/render.ts @@ -1,6 +1,6 @@ import { zodToJsonSchema } from "zod-to-json-schema"; import { JsonSchema7ObjectType } from "zod-to-json-schema/src/parsers/object.js"; -import { StructuredTool } from "./base.js"; +import { StructuredToolInterface } from "@langchain/core/tools"; /** * Render the tool name and description in plain text. @@ -13,7 +13,9 @@ import { StructuredTool } from "./base.js"; * @param tools * @returns a string of all tools and their descriptions */ -export function renderTextDescription(tools: StructuredTool[]): string { +export function renderTextDescription( + tools: StructuredToolInterface[] +): string { return tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n"); } @@ -28,7 +30,9 @@ export function renderTextDescription(tools: StructuredTool[]): string { * @param tools * @returns a string of all tools, their descriptions and a stringified version of their schemas */ -export function renderTextDescriptionAndArgs(tools: StructuredTool[]): string { +export function renderTextDescriptionAndArgs( + tools: StructuredToolInterface[] +): string { return tools .map( (tool) => diff --git a/langchain/src/tools/sql.ts b/langchain/src/tools/sql.ts index 89ae712c15d3..cd8317213c9e 100644 --- a/langchain/src/tools/sql.ts +++ b/langchain/src/tools/sql.ts @@ -1,10 +1,10 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { Tool } from "./base.js"; import { OpenAI } from "../llms/openai.js"; import { LLMChain } from "../chains/llm_chain.js"; import { PromptTemplate } from "../prompts/prompt.js"; import type { SqlDatabase } from "../sql_db.js"; import { SqlTable } from "../util/sql_utils.js"; -import { BaseLanguageModel } from "../base_language/index.js"; /** * Interface for SQL tools. It has a `db` property which is a SQL @@ -137,7 +137,7 @@ export class ListTablesSqlTool extends Tool implements SqlTool { */ type QueryCheckerToolArgs = { llmChain?: LLMChain; - llm?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; _chainType?: never; }; diff --git a/langchain/src/tools/vectorstore.ts b/langchain/src/tools/vectorstore.ts index a3489ca30162..f98aae8fec4c 100644 --- a/langchain/src/tools/vectorstore.ts +++ b/langchain/src/tools/vectorstore.ts @@ -1,5 +1,5 @@ -import { VectorStore } from "../vectorstores/base.js"; -import { BaseLanguageModel } from "../base_language/index.js"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { VectorDBQAChain } from "../chains/vector_db_qa.js"; import { Tool } from "./base.js"; @@ -7,8 +7,8 @@ import { Tool } from "./base.js"; * Interface for tools that interact with a Vector Store. */ interface VectorStoreTool { - vectorStore: VectorStore; - llm: BaseLanguageModel; + vectorStore: VectorStoreInterface; + llm: BaseLanguageModelInterface; } /** @@ -21,9 +21,9 @@ export class VectorStoreQATool extends Tool implements VectorStoreTool { return "VectorStoreQATool"; } - vectorStore: VectorStore; + vectorStore: VectorStoreInterface; - llm: BaseLanguageModel; + llm: BaseLanguageModelInterface; name: string; diff --git a/langchain/src/tools/webbrowser.ts b/langchain/src/tools/webbrowser.ts index 55ec8249d8a1..92b9a5de4b27 100644 --- a/langchain/src/tools/webbrowser.ts +++ b/langchain/src/tools/webbrowser.ts @@ -1,19 +1,19 @@ +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; +import { Document } from "@langchain/core/documents"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import axiosMod, { AxiosRequestConfig, AxiosStatic } from "axios"; import * as cheerio from "cheerio"; import { isNode } from "../util/env.js"; -import { BaseLanguageModel } from "../base_language/index.js"; import { RecursiveCharacterTextSplitter, TextSplitter, } from "../text_splitter.js"; import { MemoryVectorStore } from "../vectorstores/memory.js"; -import { Document } from "../document.js"; import { Tool, ToolParams } from "./base.js"; import { CallbackManager, CallbackManagerForToolRun, } from "../callbacks/manager.js"; -import { Embeddings } from "../embeddings/base.js"; import fetchAdapter from "../util/axios-fetch-adapter.js"; import { formatDocumentsAsString } from "../util/document.js"; @@ -152,9 +152,9 @@ type Headers = Record; * callback manager, and a text splitter. */ export interface WebBrowserArgs extends ToolParams { - model: BaseLanguageModel; + model: BaseLanguageModelInterface; - embeddings: Embeddings; + embeddings: EmbeddingsInterface; headers?: Headers; @@ -189,9 +189,9 @@ export class WebBrowser extends Tool { return [...super.lc_namespace, "webbrowser"]; } - private model: BaseLanguageModel; + private model: BaseLanguageModelInterface; - private embeddings: Embeddings; + private embeddings: EmbeddingsInterface; private headers: Headers; diff --git a/langchain/src/util/googlevertexai-connection.ts b/langchain/src/util/googlevertexai-connection.ts index ee4f83de7e59..75c5ed70aff7 100644 --- a/langchain/src/util/googlevertexai-connection.ts +++ b/langchain/src/util/googlevertexai-connection.ts @@ -1,4 +1,4 @@ -import { BaseLanguageModelCallOptions } from "../base_language/index.js"; +import { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base"; import { AsyncCaller, AsyncCallerCallOptions } from "./async_caller.js"; import type { GoogleVertexAIBaseLLMInput, diff --git a/langchain/src/vectorstores/memory.ts b/langchain/src/vectorstores/memory.ts index 9ea9e4aeeeb4..a584aa5b4333 100644 --- a/langchain/src/vectorstores/memory.ts +++ b/langchain/src/vectorstores/memory.ts @@ -1,6 +1,6 @@ import { similarity as ml_distance_similarity } from "ml-distance"; import { VectorStore } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; /** @@ -41,7 +41,7 @@ export class MemoryVectorStore extends VectorStore { } constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, { similarity, ...rest }: MemoryVectorStoreArgs = {} ) { super(embeddings, rest); @@ -141,7 +141,7 @@ export class MemoryVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: MemoryVectorStoreArgs ): Promise { const docs: Document[] = []; @@ -166,7 +166,7 @@ export class MemoryVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: MemoryVectorStoreArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -183,7 +183,7 @@ export class MemoryVectorStore extends VectorStore { * @returns Promise that resolves with a new `MemoryVectorStore` instance. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: MemoryVectorStoreArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/langchain/src/vectorstores/mongo.ts b/langchain/src/vectorstores/mongo.ts index 780c463c124b..31adf5ee44fd 100644 --- a/langchain/src/vectorstores/mongo.ts +++ b/langchain/src/vectorstores/mongo.ts @@ -1,10 +1,10 @@ +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import type { MongoClient, Collection, Document as MongoDocument, } from "mongodb"; import { VectorStore } from "./base.js"; -import { Embeddings } from "../embeddings/base.js"; import { Document } from "../document.js"; /** @deprecated use `MongoDBAtlasVectorSearch` instead. */ @@ -36,7 +36,7 @@ export class MongoVectorStore extends VectorStore { return "mongodb"; } - constructor(embeddings: Embeddings, args: MongoLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: MongoLibArgs) { super(embeddings, args); this.collection = args.collection; this.client = args.client; @@ -170,7 +170,7 @@ export class MongoVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MongoLibArgs ): Promise { const docs: Document[] = []; @@ -196,7 +196,7 @@ export class MongoVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MongoLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/create-langchain-integration/template/src/vectorstores.ts b/libs/create-langchain-integration/template/src/vectorstores.ts index 27c83543801b..80a3f769450c 100644 --- a/libs/create-langchain-integration/template/src/vectorstores.ts +++ b/libs/create-langchain-integration/template/src/vectorstores.ts @@ -1,4 +1,4 @@ -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -17,7 +17,10 @@ export class VectorstoreIntegration extends VectorStore { return "vectorstore_integration"; } - constructor(embeddings: Embeddings, params: VectorstoreIntegrationParams) { + constructor( + embeddings: EmbeddingsInterface, + params: VectorstoreIntegrationParams + ) { super(embeddings, params); this.embeddings = embeddings; } @@ -70,7 +73,7 @@ export class VectorstoreIntegration extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: VectorstoreIntegrationParams ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/agents/toolkits/aws_sfn.ts b/libs/langchain-community/src/agents/toolkits/aws_sfn.ts index 920990c0535c..da59ae20dde8 100644 --- a/libs/langchain-community/src/agents/toolkits/aws_sfn.ts +++ b/libs/langchain-community/src/agents/toolkits/aws_sfn.ts @@ -1,4 +1,4 @@ -import type { BaseLanguageModel } from "@langchain/core/language_models/base"; +import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base"; import { Tool } from "@langchain/core/tools"; import { SfnConfig, @@ -17,7 +17,7 @@ export interface AWSSfnToolkitArgs { description: string; stateMachineArn: string; asl?: string; - llm?: BaseLanguageModel; + llm?: BaseLanguageModelInterface; } /** diff --git a/libs/langchain-community/src/agents/toolkits/base.ts b/libs/langchain-community/src/agents/toolkits/base.ts index 4e1a20fab725..535f2ae2ac20 100644 --- a/libs/langchain-community/src/agents/toolkits/base.ts +++ b/libs/langchain-community/src/agents/toolkits/base.ts @@ -1,4 +1,4 @@ -import { Tool } from "@langchain/core/tools"; +import { ToolInterface } from "@langchain/core/tools"; /** * Abstract base class for toolkits in LangChain. Toolkits are collections @@ -6,5 +6,5 @@ import { Tool } from "@langchain/core/tools"; * property to provide the specific tools for the toolkit. */ export abstract class Toolkit { - abstract tools: Tool[]; + abstract tools: ToolInterface[]; } diff --git a/libs/langchain-community/src/agents/toolkits/connery/index.ts b/libs/langchain-community/src/agents/toolkits/connery/index.ts index a8b54f3d54d3..add3a035bafc 100644 --- a/libs/langchain-community/src/agents/toolkits/connery/index.ts +++ b/libs/langchain-community/src/agents/toolkits/connery/index.ts @@ -1,4 +1,4 @@ -import { Tool } from "@langchain/core/tools"; +import { ToolInterface } from "@langchain/core/tools"; import { Toolkit } from "../base.js"; import { ConneryService } from "../../../tools/connery.js"; @@ -12,7 +12,7 @@ import { ConneryService } from "../../../tools/connery.js"; * @extends Toolkit */ export class ConneryToolkit extends Toolkit { - tools: Tool[]; + tools: ToolInterface[]; /** * Creates a ConneryToolkit instance based on the provided ConneryService instance. diff --git a/libs/langchain-community/src/chat_models/minimax.ts b/libs/langchain-community/src/chat_models/minimax.ts index bb450bf92d38..4bccf448b582 100644 --- a/libs/langchain-community/src/chat_models/minimax.ts +++ b/libs/langchain-community/src/chat_models/minimax.ts @@ -13,7 +13,7 @@ import { import { ChatResult, ChatGeneration } from "@langchain/core/outputs"; import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; -import { StructuredTool } from "@langchain/core/tools"; +import type { StructuredToolInterface } from "@langchain/core/tools"; import { BaseFunctionCallOptions } from "@langchain/core/language_models/base"; import { formatToOpenAIFunction } from "@langchain/openai"; @@ -259,7 +259,7 @@ function messageToMinimaxRole(message: BaseMessage): MinimaxMessageRole { } export interface ChatMinimaxCallOptions extends BaseFunctionCallOptions { - tools?: StructuredTool[]; + tools?: StructuredToolInterface[]; defaultUserName?: string; defaultBotName?: string; plugins?: string[]; diff --git a/libs/langchain-community/src/retrievers/supabase.ts b/libs/langchain-community/src/retrievers/supabase.ts index 022bfc339570..e81ba9099d78 100644 --- a/libs/langchain-community/src/retrievers/supabase.ts +++ b/libs/langchain-community/src/retrievers/supabase.ts @@ -1,5 +1,5 @@ import type { SupabaseClient } from "@supabase/supabase-js"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { BaseRetriever, @@ -86,9 +86,9 @@ export class SupabaseHybridSearch extends BaseRetriever { keywordQueryName: string; - embeddings: Embeddings; + embeddings: EmbeddingsInterface; - constructor(embeddings: Embeddings, args: SupabaseLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: SupabaseLibArgs) { super(args); this.embeddings = embeddings; this.client = args.client; diff --git a/libs/langchain-community/src/vectorstores/analyticdb.ts b/libs/langchain-community/src/vectorstores/analyticdb.ts index bd4f5caffabe..8f6539be453a 100644 --- a/libs/langchain-community/src/vectorstores/analyticdb.ts +++ b/libs/langchain-community/src/vectorstores/analyticdb.ts @@ -5,7 +5,7 @@ import { pipeline } from "node:stream/promises"; import { Readable } from "node:stream"; import { VectorStore } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; const _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_document"; @@ -57,7 +57,7 @@ export class AnalyticDBVectorStore extends VectorStore { return "analyticdb"; } - constructor(embeddings: Embeddings, args: AnalyticDBArgs) { + constructor(embeddings: EmbeddingsInterface, args: AnalyticDBArgs) { super(embeddings, args); this.pool = new pg.Pool({ @@ -339,7 +339,7 @@ export class AnalyticDBVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: AnalyticDBArgs ): Promise { const docs = []; @@ -364,7 +364,7 @@ export class AnalyticDBVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: AnalyticDBArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -380,7 +380,7 @@ export class AnalyticDBVectorStore extends VectorStore { * @returns Promise that resolves to an instance of `AnalyticDBVectorStore`. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: AnalyticDBArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/cassandra.ts b/libs/langchain-community/src/vectorstores/cassandra.ts index 4ffe4e774bf1..d8459e564f99 100644 --- a/libs/langchain-community/src/vectorstores/cassandra.ts +++ b/libs/langchain-community/src/vectorstores/cassandra.ts @@ -5,7 +5,7 @@ import { AsyncCaller, AsyncCallerParams, } from "@langchain/core/utils/async_caller"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -85,7 +85,7 @@ export class CassandraStore extends VectorStore { return "cassandra"; } - constructor(embeddings: Embeddings, args: CassandraLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: CassandraLibArgs) { super(embeddings, args); const { @@ -231,7 +231,7 @@ export class CassandraStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object | object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: CassandraLibArgs ): Promise { const docs: Document[] = []; @@ -257,7 +257,7 @@ export class CassandraStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: CassandraLibArgs ): Promise { const instance = new this(embeddings, args); @@ -275,7 +275,7 @@ export class CassandraStore extends VectorStore { * @returns Promise that resolves with a new instance of CassandraStore. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: CassandraLibArgs ): Promise { const instance = new this(embeddings, args); diff --git a/libs/langchain-community/src/vectorstores/chroma.ts b/libs/langchain-community/src/vectorstores/chroma.ts index 96e6b15475dc..b1da37c8591e 100644 --- a/libs/langchain-community/src/vectorstores/chroma.ts +++ b/libs/langchain-community/src/vectorstores/chroma.ts @@ -2,7 +2,7 @@ import * as uuid from "uuid"; import type { ChromaClient as ChromaClientT, Collection } from "chromadb"; import type { CollectionMetadata, Where } from "chromadb/dist/main/types.js"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -67,7 +67,7 @@ export class Chroma extends VectorStore { return "chroma"; } - constructor(embeddings: Embeddings, args: ChromaLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: ChromaLibArgs) { super(embeddings, args); this.numDimensions = args.numDimensions; this.embeddings = embeddings; @@ -286,7 +286,7 @@ export class Chroma extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ChromaLibArgs ): Promise { const docs: Document[] = []; @@ -311,7 +311,7 @@ export class Chroma extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ChromaLibArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -327,7 +327,7 @@ export class Chroma extends VectorStore { * @returns A promise that resolves with a new `Chroma` instance. */ static async fromExistingCollection( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ChromaLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/clickhouse.ts b/libs/langchain-community/src/vectorstores/clickhouse.ts index 4cb9bd127e7c..b2db3d28d3f8 100644 --- a/libs/langchain-community/src/vectorstores/clickhouse.ts +++ b/libs/langchain-community/src/vectorstores/clickhouse.ts @@ -1,7 +1,7 @@ import * as uuid from "uuid"; import { ClickHouseClient, createClient } from "@clickhouse/client"; import { format } from "mysql2"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -71,7 +71,7 @@ export class ClickHouseStore extends VectorStore { return "clickhouse"; } - constructor(embeddings: Embeddings, args: ClickHouseLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: ClickHouseLibArgs) { super(embeddings, args); this.indexType = args.indexType || "annoy"; @@ -168,7 +168,7 @@ export class ClickHouseStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object | object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: ClickHouseLibArgs ): Promise { const docs: Document[] = []; @@ -192,7 +192,7 @@ export class ClickHouseStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: ClickHouseLibArgs ): Promise { const instance = new this(embeddings, args); @@ -208,7 +208,7 @@ export class ClickHouseStore extends VectorStore { * @returns Promise that resolves with a new instance of ClickHouseStore. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: ClickHouseLibArgs ): Promise { const instance = new this(embeddings, args); diff --git a/libs/langchain-community/src/vectorstores/closevector/common.ts b/libs/langchain-community/src/vectorstores/closevector/common.ts index ec62f28b7987..aa5928f10531 100644 --- a/libs/langchain-community/src/vectorstores/closevector/common.ts +++ b/libs/langchain-community/src/vectorstores/closevector/common.ts @@ -1,6 +1,6 @@ import type { CloseVectorSaveableVectorStore } from "closevector-common"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { SaveableVectorStore } from "@langchain/core/vectorstores"; @@ -38,7 +38,7 @@ export abstract class CloseVector< } constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: { space: "l2" | "ip" | "cosine"; numDimensions?: number; diff --git a/libs/langchain-community/src/vectorstores/closevector/node.ts b/libs/langchain-community/src/vectorstores/closevector/node.ts index c45bf012bcdc..843877813495 100644 --- a/libs/langchain-community/src/vectorstores/closevector/node.ts +++ b/libs/langchain-community/src/vectorstores/closevector/node.ts @@ -5,7 +5,7 @@ import { CloseVectorCredentials, } from "closevector-node"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { CloseVector } from "./common.js"; @@ -36,7 +36,7 @@ export class CloseVectorNode extends CloseVector { declare FilterType: (doc: Document) => boolean; constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: CloseVectorNodeArgs, credentials?: CloseVectorCredentials ) { @@ -79,7 +79,7 @@ export class CloseVectorNode extends CloseVector { static async loadFromCloud( options: Omit< Parameters<(typeof CloseVectorHNSWNode)["loadFromCloud"]>[0] & { - embeddings: Embeddings; + embeddings: EmbeddingsInterface; credentials: CloseVectorCredentials; }, "accessKey" | "secret" @@ -111,7 +111,7 @@ export class CloseVectorNode extends CloseVector { */ static async load( directory: string, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, credentials?: CloseVectorCredentials ) { const instance = await CloseVectorHNSWNode.load(directory, embeddings); @@ -133,7 +133,7 @@ export class CloseVectorNode extends CloseVector { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args?: Record, credential?: CloseVectorCredentials ): Promise { @@ -158,7 +158,7 @@ export class CloseVectorNode extends CloseVector { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args?: Record, credentials?: CloseVectorCredentials ): Promise { diff --git a/libs/langchain-community/src/vectorstores/closevector/web.ts b/libs/langchain-community/src/vectorstores/closevector/web.ts index 9a0896041df5..b9fe47e2d995 100644 --- a/libs/langchain-community/src/vectorstores/closevector/web.ts +++ b/libs/langchain-community/src/vectorstores/closevector/web.ts @@ -6,7 +6,7 @@ import { HnswlibModule, } from "closevector-web"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { CloseVector } from "./common.js"; @@ -36,7 +36,7 @@ export class CloseVectorWeb extends CloseVector { declare FilterType: (doc: Document) => boolean; constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: CloseVectorWebArgs, credentials?: CloseVectorCredentials ) { @@ -79,7 +79,7 @@ export class CloseVectorWeb extends CloseVector { */ static async loadFromCloud( options: Parameters[0] & { - embeddings: Embeddings; + embeddings: EmbeddingsInterface; credentials?: CloseVectorCredentials; } ) { @@ -102,7 +102,7 @@ export class CloseVectorWeb extends CloseVector { */ static async load( directory: string, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, credentials?: CloseVectorCredentials ) { const instance = await CloseVectorHNSWWeb.load(directory, embeddings); @@ -124,7 +124,7 @@ export class CloseVectorWeb extends CloseVector { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args?: Record, credential?: CloseVectorCredentials ): Promise { @@ -157,7 +157,7 @@ export class CloseVectorWeb extends CloseVector { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args?: Record, credentials?: CloseVectorCredentials ): Promise { diff --git a/libs/langchain-community/src/vectorstores/cloudflare_vectorize.ts b/libs/langchain-community/src/vectorstores/cloudflare_vectorize.ts index 605aa7ab44ec..188413ad9ab5 100644 --- a/libs/langchain-community/src/vectorstores/cloudflare_vectorize.ts +++ b/libs/langchain-community/src/vectorstores/cloudflare_vectorize.ts @@ -4,7 +4,7 @@ import { VectorizeIndex, VectorizeVectorMetadata, } from "@cloudflare/workers-types"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { @@ -43,7 +43,7 @@ export class CloudflareVectorizeStore extends VectorStore { return "cloudflare_vectorize"; } - constructor(embeddings: Embeddings, args: VectorizeLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: VectorizeLibArgs) { super(embeddings, args); this.embeddings = embeddings; @@ -179,7 +179,7 @@ export class CloudflareVectorizeStore extends VectorStore { metadatas: | Record[] | Record, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: VectorizeLibArgs ): Promise { const docs: Document[] = []; @@ -205,7 +205,7 @@ export class CloudflareVectorizeStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: VectorizeLibArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -221,7 +221,7 @@ export class CloudflareVectorizeStore extends VectorStore { * @returns Promise that resolves with a new instance of the CloudflareVectorizeStore class. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: VectorizeLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/convex.ts b/libs/langchain-community/src/vectorstores/convex.ts index 72d3661a8b2c..3faeec691273 100644 --- a/libs/langchain-community/src/vectorstores/convex.ts +++ b/libs/langchain-community/src/vectorstores/convex.ts @@ -14,7 +14,7 @@ import { VectorIndexNames, makeFunctionReference, } from "convex/server"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -135,7 +135,7 @@ export class ConvexVectorStore< } constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: ConvexVectorStoreConfig< DataModel, TableName, @@ -284,7 +284,7 @@ export class ConvexVectorStore< >( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ConvexVectorStoreConfig< DataModel, TableName, @@ -346,7 +346,7 @@ export class ConvexVectorStore< > >( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ConvexVectorStoreConfig< DataModel, TableName, diff --git a/libs/langchain-community/src/vectorstores/elasticsearch.ts b/libs/langchain-community/src/vectorstores/elasticsearch.ts index 76e58e2f2592..a783f03ee962 100644 --- a/libs/langchain-community/src/vectorstores/elasticsearch.ts +++ b/libs/langchain-community/src/vectorstores/elasticsearch.ts @@ -1,6 +1,6 @@ import * as uuid from "uuid"; import { Client, estypes } from "@elastic/elasticsearch"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; /** @@ -67,7 +67,7 @@ export class ElasticVectorSearch extends VectorStore { return "elasticsearch"; } - constructor(embeddings: Embeddings, args: ElasticClientArgs) { + constructor(embeddings: EmbeddingsInterface, args: ElasticClientArgs) { super(embeddings, args); this.engine = args.vectorSearchOptions?.engine ?? "hnsw"; @@ -210,7 +210,7 @@ export class ElasticVectorSearch extends VectorStore { static fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: ElasticClientArgs ): Promise { const documents = texts.map((text, idx) => { @@ -232,7 +232,7 @@ export class ElasticVectorSearch extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ElasticClientArgs ): Promise { const store = new ElasticVectorSearch(embeddings, dbConfig); @@ -249,7 +249,7 @@ export class ElasticVectorSearch extends VectorStore { * @returns A promise that resolves with the created ElasticVectorSearch instance if the index exists, otherwise it throws an error. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: ElasticClientArgs ): Promise { const store = new ElasticVectorSearch(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/faiss.ts b/libs/langchain-community/src/vectorstores/faiss.ts index 0403aa89c726..f1b6f1e8cfce 100644 --- a/libs/langchain-community/src/vectorstores/faiss.ts +++ b/libs/langchain-community/src/vectorstores/faiss.ts @@ -1,7 +1,7 @@ import type { IndexFlatL2 } from "faiss-node"; import type { NameRegistry, Parser } from "pickleparser"; import * as uuid from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { SaveableVectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { SynchronousInMemoryDocstore } from "../stores/doc/in_memory.js"; @@ -42,7 +42,7 @@ export class FaissStore extends SaveableVectorStore { return this.docstore; } - constructor(embeddings: Embeddings, args: FaissLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: FaissLibArgs) { super(embeddings, args); this.args = args; this._index = args.index; @@ -260,7 +260,7 @@ export class FaissStore extends SaveableVectorStore { * @param embeddings An Embeddings object. * @returns A Promise that resolves with a new FaissStore instance. */ - static async load(directory: string, embeddings: Embeddings) { + static async load(directory: string, embeddings: EmbeddingsInterface) { const fs = await import("node:fs/promises"); const path = await import("node:path"); const readStore = (directory: string) => @@ -281,7 +281,10 @@ export class FaissStore extends SaveableVectorStore { return new this(embeddings, { docstore, index, mapping }); } - static async loadFromPython(directory: string, embeddings: Embeddings) { + static async loadFromPython( + directory: string, + embeddings: EmbeddingsInterface + ) { const fs = await import("node:fs/promises"); const path = await import("node:path"); const { Parser, NameRegistry } = await this.importPickleparser(); @@ -363,7 +366,7 @@ export class FaissStore extends SaveableVectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } @@ -390,7 +393,7 @@ export class FaissStore extends SaveableVectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } @@ -413,7 +416,7 @@ export class FaissStore extends SaveableVectorStore { */ static async fromIndex( targetIndex: FaissStore, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } diff --git a/libs/langchain-community/src/vectorstores/googlevertexai.ts b/libs/langchain-community/src/vectorstores/googlevertexai.ts index 974455d27332..1f826695b8f2 100644 --- a/libs/langchain-community/src/vectorstores/googlevertexai.ts +++ b/libs/langchain-community/src/vectorstores/googlevertexai.ts @@ -2,7 +2,7 @@ import * as uuid from "uuid"; import flatten from "flat"; import { GoogleAuth, GoogleAuthOptions } from "google-auth-library"; import { VectorStore } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document, DocumentInput } from "@langchain/core/documents"; import { AsyncCaller, @@ -369,7 +369,7 @@ export class MatchingEngine extends VectorStore implements MatchingEngineArgs { upsertDatapointClient: UpsertDatapointConnection; - constructor(embeddings: Embeddings, args: MatchingEngineArgs) { + constructor(embeddings: EmbeddingsInterface, args: MatchingEngineArgs) { super(embeddings, args); this.embeddings = embeddings; @@ -725,7 +725,7 @@ export class MatchingEngine extends VectorStore implements MatchingEngineArgs { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MatchingEngineArgs ): Promise { const docs: Document[] = texts.map( @@ -739,7 +739,7 @@ export class MatchingEngine extends VectorStore implements MatchingEngineArgs { static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MatchingEngineArgs ): Promise { const ret = new MatchingEngine(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/hnswlib.ts b/libs/langchain-community/src/vectorstores/hnswlib.ts index 86d896a70566..31a304f7e76e 100644 --- a/libs/langchain-community/src/vectorstores/hnswlib.ts +++ b/libs/langchain-community/src/vectorstores/hnswlib.ts @@ -2,7 +2,7 @@ import type { HierarchicalNSW as HierarchicalNSWT, SpaceName, } from "hnswlib-node"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { SaveableVectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { SynchronousInMemoryDocstore } from "../stores/doc/in_memory.js"; @@ -45,7 +45,7 @@ export class HNSWLib extends SaveableVectorStore { return "hnswlib"; } - constructor(embeddings: Embeddings, args: HNSWLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: HNSWLibArgs) { super(embeddings, args); this._index = args.index; this.args = args; @@ -260,7 +260,7 @@ export class HNSWLib extends SaveableVectorStore { * @param embeddings The embeddings to be used by the HNSWLib instance. * @returns A Promise that resolves to a new HNSWLib instance. */ - static async load(directory: string, embeddings: Embeddings) { + static async load(directory: string, embeddings: EmbeddingsInterface) { const fs = await import("node:fs/promises"); const path = await import("node:path"); const args = JSON.parse( @@ -293,7 +293,7 @@ export class HNSWLib extends SaveableVectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } @@ -321,7 +321,7 @@ export class HNSWLib extends SaveableVectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } diff --git a/libs/langchain-community/src/vectorstores/lancedb.ts b/libs/langchain-community/src/vectorstores/lancedb.ts index 86b87a111758..def5a6d61cb4 100644 --- a/libs/langchain-community/src/vectorstores/lancedb.ts +++ b/libs/langchain-community/src/vectorstores/lancedb.ts @@ -1,5 +1,5 @@ import { Table } from "vectordb"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -22,7 +22,7 @@ export class LanceDB extends VectorStore { private textKey: string; - constructor(embeddings: Embeddings, args: LanceDBArgs) { + constructor(embeddings: EmbeddingsInterface, args: LanceDBArgs) { super(embeddings, args); this.table = args.table; this.embeddings = embeddings; @@ -118,7 +118,7 @@ export class LanceDB extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: LanceDBArgs ): Promise { const docs: Document[] = []; @@ -142,7 +142,7 @@ export class LanceDB extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: LanceDBArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/milvus.ts b/libs/langchain-community/src/vectorstores/milvus.ts index b9978554da96..e60b0e6e89cb 100644 --- a/libs/langchain-community/src/vectorstores/milvus.ts +++ b/libs/langchain-community/src/vectorstores/milvus.ts @@ -8,7 +8,7 @@ import { ClientConfig, } from "@zilliz/milvus2-sdk-node"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; @@ -118,7 +118,7 @@ export class Milvus extends VectorStore { return "milvus"; } - constructor(embeddings: Embeddings, args: MilvusLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: MilvusLibArgs) { super(embeddings, args); this.embeddings = embeddings; this.collectionName = args.collectionName ?? genCollectionName(); @@ -463,7 +463,7 @@ export class Milvus extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: MilvusLibArgs ): Promise { const docs: Document[] = []; @@ -487,7 +487,7 @@ export class Milvus extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: MilvusLibArgs ): Promise { const args: MilvusLibArgs = { @@ -515,7 +515,7 @@ export class Milvus extends VectorStore { * @returns Promise resolving to a new Milvus instance. */ static async fromExistingCollection( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MilvusLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/momento_vector_index.ts b/libs/langchain-community/src/vectorstores/momento_vector_index.ts index e9623ee1a131..a6a29268dc00 100644 --- a/libs/langchain-community/src/vectorstores/momento_vector_index.ts +++ b/libs/langchain-community/src/vectorstores/momento_vector_index.ts @@ -12,7 +12,7 @@ import { } from "@gomomento/sdk-core"; import * as uuid from "uuid"; import { Document } from "@langchain/core/documents"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { MaxMarginalRelevanceSearchOptions, VectorStore, @@ -76,7 +76,10 @@ export class MomentoVectorIndex extends VectorStore { * @param embeddings The embeddings instance to use to generate embeddings from documents. * @param args The arguments to use to configure the vector store. */ - constructor(embeddings: Embeddings, args: MomentoVectorIndexLibArgs) { + constructor( + embeddings: EmbeddingsInterface, + args: MomentoVectorIndexLibArgs + ) { super(embeddings, args); this.embeddings = embeddings; @@ -356,7 +359,7 @@ export class MomentoVectorIndex extends VectorStore { public static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MomentoVectorIndexLibArgs, documentProps?: DocumentProps ): Promise { @@ -391,7 +394,7 @@ export class MomentoVectorIndex extends VectorStore { */ public static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MomentoVectorIndexLibArgs, documentProps?: DocumentProps ): Promise { diff --git a/libs/langchain-community/src/vectorstores/mongodb_atlas.ts b/libs/langchain-community/src/vectorstores/mongodb_atlas.ts index 10a56dc3f7df..36ed4328f501 100755 --- a/libs/langchain-community/src/vectorstores/mongodb_atlas.ts +++ b/libs/langchain-community/src/vectorstores/mongodb_atlas.ts @@ -3,7 +3,7 @@ import { MaxMarginalRelevanceSearchOptions, VectorStore, } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { maximalMarginalRelevance } from "@langchain/core/utils/math"; @@ -52,7 +52,10 @@ export class MongoDBAtlasVectorSearch extends VectorStore { return "mongodb_atlas"; } - constructor(embeddings: Embeddings, args: MongoDBAtlasVectorSearchLibArgs) { + constructor( + embeddings: EmbeddingsInterface, + args: MongoDBAtlasVectorSearchLibArgs + ) { super(embeddings, args); this.collection = args.collection; this.indexName = args.indexName ?? "default"; @@ -225,7 +228,7 @@ export class MongoDBAtlasVectorSearch extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MongoDBAtlasVectorSearchLibArgs ): Promise { const docs: Document[] = []; @@ -251,7 +254,7 @@ export class MongoDBAtlasVectorSearch extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: MongoDBAtlasVectorSearchLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/myscale.ts b/libs/langchain-community/src/vectorstores/myscale.ts index 316505414b57..887c565b2394 100644 --- a/libs/langchain-community/src/vectorstores/myscale.ts +++ b/libs/langchain-community/src/vectorstores/myscale.ts @@ -1,7 +1,7 @@ import * as uuid from "uuid"; import { ClickHouseClient, createClient } from "@clickhouse/client"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -75,7 +75,7 @@ export class MyScaleStore extends VectorStore { return "myscale"; } - constructor(embeddings: Embeddings, args: MyScaleLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: MyScaleLibArgs) { super(embeddings, args); this.indexType = args.indexType || "MSTG"; @@ -170,7 +170,7 @@ export class MyScaleStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object | object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: MyScaleLibArgs ): Promise { const docs: Document[] = []; @@ -194,7 +194,7 @@ export class MyScaleStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: MyScaleLibArgs ): Promise { const instance = new this(embeddings, args); @@ -210,7 +210,7 @@ export class MyScaleStore extends VectorStore { * @returns Promise that resolves with a new instance of MyScaleStore. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: MyScaleLibArgs ): Promise { const instance = new this(embeddings, args); diff --git a/libs/langchain-community/src/vectorstores/neo4j_vector.ts b/libs/langchain-community/src/vectorstores/neo4j_vector.ts index 3837dced1e66..75ef364b1d12 100644 --- a/libs/langchain-community/src/vectorstores/neo4j_vector.ts +++ b/libs/langchain-community/src/vectorstores/neo4j_vector.ts @@ -1,6 +1,6 @@ import neo4j from "neo4j-driver"; import * as uuid from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -71,12 +71,12 @@ export class Neo4jVectorStore extends VectorStore { return "neo4jvector"; } - constructor(embeddings: Embeddings, config: Neo4jVectorStoreArgs) { + constructor(embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs) { super(embeddings, config); } static async initialize( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs ) { const store = new Neo4jVectorStore(embeddings, config); @@ -162,7 +162,7 @@ export class Neo4jVectorStore extends VectorStore { texts: string[], // eslint-disable-next-line @typescript-eslint/no-explicit-any metadatas: any, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs ): Promise { const docs = []; @@ -181,7 +181,7 @@ export class Neo4jVectorStore extends VectorStore { static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs ): Promise { const { @@ -230,7 +230,7 @@ export class Neo4jVectorStore extends VectorStore { } static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs ) { const { searchType = DEFAULT_SEARCH_TYPE, keywordIndexName = "keyword" } = @@ -279,7 +279,7 @@ export class Neo4jVectorStore extends VectorStore { } static async fromExistingGraph( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: Neo4jVectorStoreArgs ) { const { diff --git a/libs/langchain-community/src/vectorstores/opensearch.ts b/libs/langchain-community/src/vectorstores/opensearch.ts index 0ea90dff456a..86d24e0799f9 100644 --- a/libs/langchain-community/src/vectorstores/opensearch.ts +++ b/libs/langchain-community/src/vectorstores/opensearch.ts @@ -1,6 +1,6 @@ import { Client, RequestParams, errors } from "@opensearch-project/opensearch"; import * as uuid from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -65,7 +65,7 @@ export class OpenSearchVectorStore extends VectorStore { return "opensearch"; } - constructor(embeddings: Embeddings, args: OpenSearchClientArgs) { + constructor(embeddings: EmbeddingsInterface, args: OpenSearchClientArgs) { super(embeddings, args); this.spaceType = args.vectorSearchOptions?.spaceType ?? "l2"; @@ -189,7 +189,7 @@ export class OpenSearchVectorStore extends VectorStore { static fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: OpenSearchClientArgs ): Promise { const documents = texts.map((text, idx) => { @@ -210,7 +210,7 @@ export class OpenSearchVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: OpenSearchClientArgs ): Promise { const store = new OpenSearchVectorStore(embeddings, dbConfig); @@ -226,7 +226,7 @@ export class OpenSearchVectorStore extends VectorStore { * @returns Promise resolving to a new instance of OpenSearchVectorStore. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: OpenSearchClientArgs ): Promise { const store = new OpenSearchVectorStore(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/pgvector.ts b/libs/langchain-community/src/vectorstores/pgvector.ts index cbcbf6903c7e..1b06d1a21048 100644 --- a/libs/langchain-community/src/vectorstores/pgvector.ts +++ b/libs/langchain-community/src/vectorstores/pgvector.ts @@ -1,6 +1,6 @@ import pg, { type Pool, type PoolClient, type PoolConfig } from "pg"; import { VectorStore } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; @@ -72,7 +72,10 @@ export class PGVectorStore extends VectorStore { return "pgvector"; } - private constructor(embeddings: Embeddings, config: PGVectorStoreArgs) { + private constructor( + embeddings: EmbeddingsInterface, + config: PGVectorStoreArgs + ) { super(embeddings, config); this.tableName = config.tableName; this.collectionTableName = config.collectionTableName; @@ -104,7 +107,7 @@ export class PGVectorStore extends VectorStore { * @returns A new instance of `PGVectorStore`. */ static async initialize( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: PGVectorStoreArgs ): Promise { const postgresqlVectorStore = new PGVectorStore(embeddings, config); @@ -478,7 +481,7 @@ export class PGVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: PGVectorStoreArgs ): Promise { const docs = []; @@ -505,7 +508,7 @@ export class PGVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: PGVectorStoreArgs ): Promise { const instance = await PGVectorStore.initialize(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/pinecone.ts b/libs/langchain-community/src/vectorstores/pinecone.ts index e368fe1670e9..123b6472b2ca 100644 --- a/libs/langchain-community/src/vectorstores/pinecone.ts +++ b/libs/langchain-community/src/vectorstores/pinecone.ts @@ -12,7 +12,7 @@ import { MaxMarginalRelevanceSearchOptions, VectorStore, } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { AsyncCaller, @@ -63,7 +63,7 @@ export class PineconeStore extends VectorStore { return "pinecone"; } - constructor(embeddings: Embeddings, args: PineconeLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: PineconeLibArgs) { super(embeddings, args); this.embeddings = embeddings; @@ -301,7 +301,7 @@ export class PineconeStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: | { pineconeIndex: PineconeIndex; @@ -338,7 +338,7 @@ export class PineconeStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: PineconeLibArgs ): Promise { const args = dbConfig; @@ -357,7 +357,7 @@ export class PineconeStore extends VectorStore { * @returns Promise that resolves with a new instance of the PineconeStore class. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: PineconeLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/prisma.ts b/libs/langchain-community/src/vectorstores/prisma.ts index 170a41d96367..099ff33d93c5 100644 --- a/libs/langchain-community/src/vectorstores/prisma.ts +++ b/libs/langchain-community/src/vectorstores/prisma.ts @@ -1,4 +1,4 @@ -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { Callbacks } from "@langchain/core/callbacks/manager"; @@ -136,7 +136,7 @@ export class PrismaVectorStore< } constructor( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: { db: PrismaClient; prisma: PrismaNamespace; @@ -186,7 +186,7 @@ export class PrismaVectorStore< TColumns extends ModelColumns, TFilters extends PrismaSqlFilter >( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: { prisma: TPrisma; tableName: keyof TPrisma["ModelName"] & string; @@ -208,7 +208,7 @@ export class PrismaVectorStore< >( texts: string[], metadatas: TModel[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: { prisma: TPrisma; tableName: keyof TPrisma["ModelName"] & string; @@ -238,7 +238,7 @@ export class PrismaVectorStore< TFilters extends PrismaSqlFilter >( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: { prisma: TPrisma; tableName: keyof TPrisma["ModelName"] & string; @@ -464,7 +464,7 @@ export class PrismaVectorStore< static async fromTexts( texts: string[], metadatas: object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: { db: PrismaClient; prisma: PrismaNamespace; @@ -495,7 +495,7 @@ export class PrismaVectorStore< */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: { db: PrismaClient; prisma: PrismaNamespace; diff --git a/libs/langchain-community/src/vectorstores/qdrant.ts b/libs/langchain-community/src/vectorstores/qdrant.ts index 8e72426281dc..7925c09bdae1 100644 --- a/libs/langchain-community/src/vectorstores/qdrant.ts +++ b/libs/langchain-community/src/vectorstores/qdrant.ts @@ -1,7 +1,7 @@ import { QdrantClient } from "@qdrant/js-client-rest"; import type { Schemas as QdrantSchemas } from "@qdrant/js-client-rest"; import { v4 as uuid } from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; @@ -63,7 +63,7 @@ export class QdrantVectorStore extends VectorStore { return "qdrant"; } - constructor(embeddings: Embeddings, args: QdrantLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: QdrantLibArgs) { super(embeddings, args); const url = args.url ?? getEnvironmentVariable("QDRANT_URL"); @@ -226,7 +226,7 @@ export class QdrantVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: QdrantLibArgs ): Promise { const docs = []; @@ -251,7 +251,7 @@ export class QdrantVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: QdrantLibArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -274,7 +274,7 @@ export class QdrantVectorStore extends VectorStore { * @returns Promise that resolves with a new `QdrantVectorStore` instance. */ static async fromExistingCollection( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: QdrantLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/redis.ts b/libs/langchain-community/src/vectorstores/redis.ts index 5df94f4646b4..dfe1e09f0ee4 100644 --- a/libs/langchain-community/src/vectorstores/redis.ts +++ b/libs/langchain-community/src/vectorstores/redis.ts @@ -5,7 +5,7 @@ import type { SearchOptions, } from "redis"; import { SchemaFieldTypes, VectorAlgorithms } from "redis"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -125,7 +125,10 @@ export class RedisVectorStore extends VectorStore { return "redis"; } - constructor(embeddings: Embeddings, _dbConfig: RedisVectorStoreConfig) { + constructor( + embeddings: EmbeddingsInterface, + _dbConfig: RedisVectorStoreConfig + ) { super(embeddings, _dbConfig); this.redisClient = _dbConfig.redisClient; @@ -272,7 +275,7 @@ export class RedisVectorStore extends VectorStore { static fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: RedisVectorStoreConfig ): Promise { const docs: Document[] = []; @@ -297,7 +300,7 @@ export class RedisVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: RedisVectorStoreConfig ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/rockset.ts b/libs/langchain-community/src/vectorstores/rockset.ts index 04a93f4f6689..553cf878e39c 100644 --- a/libs/langchain-community/src/vectorstores/rockset.ts +++ b/libs/langchain-community/src/vectorstores/rockset.ts @@ -2,7 +2,7 @@ import { MainApi } from "@rockset/client"; import type { CreateCollectionRequest } from "@rockset/client/dist/codegen/api.d.ts"; import { Collection } from "@rockset/client/dist/codegen/api.js"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; /** @@ -129,7 +129,7 @@ export class RocksetStore extends VectorStore { * page content * @param {RocksetLibArgs} args */ - constructor(embeddings: Embeddings, args: RocksetLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: RocksetLibArgs) { super(embeddings, args); this.embeddings = embeddings; @@ -293,7 +293,7 @@ export class RocksetStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: RocksetLibArgs ): Promise { const docs: Document[] = []; @@ -320,7 +320,7 @@ export class RocksetStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: RocksetLibArgs ): Promise { const args = { ...dbConfig, textKey: dbConfig.textKey ?? "text" }; @@ -418,7 +418,7 @@ export class RocksetStore extends VectorStore { * @returns {RocsketStore} */ static async withNewCollection( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: RocksetLibArgs, collectionOptions?: CreateCollectionRequest ): Promise { diff --git a/libs/langchain-community/src/vectorstores/singlestore.ts b/libs/langchain-community/src/vectorstores/singlestore.ts index 34abd51598a0..5ca99c7658fa 100644 --- a/libs/langchain-community/src/vectorstores/singlestore.ts +++ b/libs/langchain-community/src/vectorstores/singlestore.ts @@ -8,7 +8,7 @@ import type { } from "mysql2/promise"; import { format } from "mysql2"; import { createPool } from "mysql2/promise"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -100,7 +100,10 @@ export class SingleStoreVectorStore extends VectorStore { return "singlestore"; } - constructor(embeddings: Embeddings, config: SingleStoreVectorStoreConfig) { + constructor( + embeddings: EmbeddingsInterface, + config: SingleStoreVectorStoreConfig + ) { super(embeddings, config); this.connectionPool = createPool(withConnectAttributes(config)); this.tableName = config.tableName ?? "embeddings"; @@ -261,7 +264,7 @@ export class SingleStoreVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: SingleStoreVectorStoreConfig ): Promise { const docs = texts.map((text, idx) => { @@ -284,7 +287,7 @@ export class SingleStoreVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: SingleStoreVectorStoreConfig ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/supabase.ts b/libs/langchain-community/src/vectorstores/supabase.ts index 5d8e9a5d67cb..e12eb260933d 100644 --- a/libs/langchain-community/src/vectorstores/supabase.ts +++ b/libs/langchain-community/src/vectorstores/supabase.ts @@ -4,7 +4,7 @@ import { MaxMarginalRelevanceSearchOptions, VectorStore, } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { maximalMarginalRelevance } from "@langchain/core/utils/math"; @@ -66,7 +66,7 @@ export class SupabaseVectorStore extends VectorStore { return "supabase"; } - constructor(embeddings: Embeddings, args: SupabaseLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: SupabaseLibArgs) { super(embeddings, args); this.client = args.client; @@ -265,7 +265,7 @@ export class SupabaseVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: SupabaseLibArgs ): Promise { const docs: Document[] = []; @@ -289,7 +289,7 @@ export class SupabaseVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: SupabaseLibArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -304,7 +304,7 @@ export class SupabaseVectorStore extends VectorStore { * @returns A promise that resolves with a new SupabaseVectorStore instance when the instance has been created. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: SupabaseLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/tests/googlevertexai.int.test.ts b/libs/langchain-community/src/vectorstores/tests/googlevertexai.int.test.ts index db93d4be707a..a5252f2caa98 100644 --- a/libs/langchain-community/src/vectorstores/tests/googlevertexai.int.test.ts +++ b/libs/langchain-community/src/vectorstores/tests/googlevertexai.int.test.ts @@ -2,7 +2,7 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { beforeAll, expect, test } from "@jest/globals"; import { Document } from "@langchain/core/documents"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { SyntheticEmbeddings } from "../../utils/testing.js"; import { InMemoryDocstore } from "../../stores/doc/in_memory.js"; import { @@ -13,7 +13,7 @@ import { } from "../googlevertexai.js"; describe("Vertex AI matching", () => { - let embeddings: Embeddings; + let embeddings: EmbeddingsInterface; let store: InMemoryDocstore; let config: MatchingEngineArgs; let engine: MatchingEngine; diff --git a/libs/langchain-community/src/vectorstores/tests/googlevertexai.test.ts b/libs/langchain-community/src/vectorstores/tests/googlevertexai.test.ts index 07b2acbe2d17..3edf0e1cd6d9 100644 --- a/libs/langchain-community/src/vectorstores/tests/googlevertexai.test.ts +++ b/libs/langchain-community/src/vectorstores/tests/googlevertexai.test.ts @@ -1,13 +1,13 @@ /* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { beforeEach, expect, test } from "@jest/globals"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { SyntheticEmbeddings } from "../../utils/testing.js"; import { InMemoryDocstore } from "../../stores/doc/in_memory.js"; import { MatchingEngineArgs, MatchingEngine } from "../googlevertexai.js"; describe("Vertex AI matching", () => { - let embeddings: Embeddings; + let embeddings: EmbeddingsInterface; let store: InMemoryDocstore; let config: MatchingEngineArgs; let engine: MatchingEngine; diff --git a/libs/langchain-community/src/vectorstores/tests/zep.test.ts b/libs/langchain-community/src/vectorstores/tests/zep.test.ts index 1b6109d64fa6..1a01047ee5ed 100644 --- a/libs/langchain-community/src/vectorstores/tests/zep.test.ts +++ b/libs/langchain-community/src/vectorstores/tests/zep.test.ts @@ -8,7 +8,7 @@ import { NotFoundError, ZepClient, } from "@getzep/zep-js"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { IZepConfig, ZepVectorStore } from "../zep.js"; import { FakeEmbeddings } from "../../utils/testing.js"; @@ -68,7 +68,7 @@ function isADocument(obj: any): obj is IDocument { describe("ZepVectorStore", () => { let zepConfig: IZepConfig; - let embeddings: Embeddings; + let embeddings: EmbeddingsInterface; beforeEach(() => { zepConfig = { @@ -180,7 +180,7 @@ describe("ZepVectorStore", () => { const zepVectorStore = await originalFromDocuments.call( ZepVectorStore, docs as Document[], - embeddings as Embeddings, + embeddings as EmbeddingsInterface, zepConfig as IZepConfig ); (zepVectorStore as any).collection = mockCollection; diff --git a/libs/langchain-community/src/vectorstores/tigris.ts b/libs/langchain-community/src/vectorstores/tigris.ts index e4bc57623991..fe8ad4bf4898 100644 --- a/libs/langchain-community/src/vectorstores/tigris.ts +++ b/libs/langchain-community/src/vectorstores/tigris.ts @@ -1,6 +1,6 @@ import * as uuid from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -25,7 +25,7 @@ export class TigrisVectorStore extends VectorStore { return "tigris"; } - constructor(embeddings: Embeddings, args: TigrisLibArgs) { + constructor(embeddings: EmbeddingsInterface, args: TigrisLibArgs) { super(embeddings, args); this.embeddings = embeddings; @@ -127,7 +127,7 @@ export class TigrisVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TigrisLibArgs ): Promise { const docs: Document[] = []; @@ -152,7 +152,7 @@ export class TigrisVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TigrisLibArgs ): Promise { const instance = new this(embeddings, dbConfig); @@ -168,7 +168,7 @@ export class TigrisVectorStore extends VectorStore { * @returns A Promise that resolves to a new instance of TigrisVectorStore. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TigrisLibArgs ): Promise { const instance = new this(embeddings, dbConfig); diff --git a/libs/langchain-community/src/vectorstores/typeorm.ts b/libs/langchain-community/src/vectorstores/typeorm.ts index 22d2d85e1f95..68b70c931630 100644 --- a/libs/langchain-community/src/vectorstores/typeorm.ts +++ b/libs/langchain-community/src/vectorstores/typeorm.ts @@ -1,6 +1,6 @@ import { Metadata } from "@opensearch-project/opensearch/api/types.js"; import { DataSource, DataSourceOptions, EntitySchema } from "typeorm"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; @@ -52,7 +52,10 @@ export class TypeORMVectorStore extends VectorStore { return "typeorm"; } - private constructor(embeddings: Embeddings, fields: TypeORMVectorStoreArgs) { + private constructor( + embeddings: EmbeddingsInterface, + fields: TypeORMVectorStoreArgs + ) { super(embeddings, fields); this.tableName = fields.tableName || defaultDocumentTableName; this.filter = fields.filter; @@ -98,7 +101,7 @@ export class TypeORMVectorStore extends VectorStore { * @returns A new instance of `TypeORMVectorStore`. */ static async fromDataSource( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, fields: TypeORMVectorStoreArgs ): Promise { const postgresqlVectorStore = new TypeORMVectorStore(embeddings, fields); @@ -240,7 +243,7 @@ export class TypeORMVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TypeORMVectorStoreArgs ): Promise { const docs = []; @@ -266,7 +269,7 @@ export class TypeORMVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TypeORMVectorStoreArgs ): Promise { const instance = await TypeORMVectorStore.fromDataSource( @@ -286,7 +289,7 @@ export class TypeORMVectorStore extends VectorStore { * @returns Promise that resolves with a new instance of `TypeORMVectorStore`. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig: TypeORMVectorStoreArgs ): Promise { const instance = await TypeORMVectorStore.fromDataSource( diff --git a/libs/langchain-community/src/vectorstores/typesense.ts b/libs/langchain-community/src/vectorstores/typesense.ts index d914a6cc9eee..1b571f1b7103 100644 --- a/libs/langchain-community/src/vectorstores/typesense.ts +++ b/libs/langchain-community/src/vectorstores/typesense.ts @@ -4,7 +4,7 @@ import type { SearchResponseHit, DocumentSchema, } from "typesense/lib/Typesense/Documents.js"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { @@ -98,7 +98,7 @@ export class Typesense extends VectorStore { return "typesense"; } - constructor(embeddings: Embeddings, config: TypesenseConfig) { + constructor(embeddings: EmbeddingsInterface, config: TypesenseConfig) { super(embeddings, config); // Assign config values to class properties. @@ -288,7 +288,7 @@ export class Typesense extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: TypesenseConfig ): Promise { const instance = new Typesense(embeddings, config); @@ -308,7 +308,7 @@ export class Typesense extends VectorStore { static async fromTexts( texts: string[], metadatas: object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config: TypesenseConfig ) { const instance = new Typesense(embeddings, config); diff --git a/libs/langchain-community/src/vectorstores/usearch.ts b/libs/langchain-community/src/vectorstores/usearch.ts index 69711f75e877..97b0fa7a3fd9 100644 --- a/libs/langchain-community/src/vectorstores/usearch.ts +++ b/libs/langchain-community/src/vectorstores/usearch.ts @@ -1,6 +1,6 @@ import usearch from "usearch"; import * as uuid from "uuid"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { SaveableVectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { SynchronousInMemoryDocstore } from "../stores/doc/in_memory.js"; @@ -34,7 +34,7 @@ export class USearch extends SaveableVectorStore { return "usearch"; } - constructor(embeddings: Embeddings, args: USearchArgs) { + constructor(embeddings: EmbeddingsInterface, args: USearchArgs) { super(embeddings, args); this.args = args; this._index = args.index; @@ -180,7 +180,7 @@ export class USearch extends SaveableVectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } @@ -208,7 +208,7 @@ export class USearch extends SaveableVectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } diff --git a/libs/langchain-community/src/vectorstores/vectara.ts b/libs/langchain-community/src/vectorstores/vectara.ts index 8ced79d147c9..2ee6ee0f957f 100644 --- a/libs/langchain-community/src/vectorstores/vectara.ts +++ b/libs/langchain-community/src/vectorstores/vectara.ts @@ -1,6 +1,6 @@ import * as uuid from "uuid"; import { Document } from "@langchain/core/documents"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; import { VectorStore } from "@langchain/core/vectorstores"; import { @@ -607,7 +607,7 @@ export class VectaraStore extends VectorStore { static fromTexts( texts: string[], metadatas: object | object[], - _embeddings: Embeddings, + _embeddings: EmbeddingsInterface, args: VectaraLibArgs ): Promise { const docs: Document[] = []; @@ -632,7 +632,7 @@ export class VectaraStore extends VectorStore { */ static async fromDocuments( docs: Document[], - _embeddings: Embeddings, + _embeddings: EmbeddingsInterface, args: VectaraLibArgs ): Promise { const instance = new this(args); diff --git a/libs/langchain-community/src/vectorstores/vercel_postgres.ts b/libs/langchain-community/src/vectorstores/vercel_postgres.ts index 782428673b2a..6ad994ff1e9d 100644 --- a/libs/langchain-community/src/vectorstores/vercel_postgres.ts +++ b/libs/langchain-community/src/vectorstores/vercel_postgres.ts @@ -4,7 +4,7 @@ import { type VercelPostgresPoolConfig, createPool, } from "@vercel/postgres"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; @@ -60,7 +60,10 @@ export class VercelPostgres extends VectorStore { return "vercel"; } - private constructor(embeddings: Embeddings, config: VercelPostgresFields) { + private constructor( + embeddings: EmbeddingsInterface, + config: VercelPostgresFields + ) { super(embeddings, config); this.tableName = config.tableName ?? "langchain_vectors"; this.filter = config.filter; @@ -88,7 +91,7 @@ export class VercelPostgres extends VectorStore { * @returns A new instance of `VercelPostgres`. */ static async initialize( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, config?: Partial & { postgresConnectionOptions?: VercelPostgresPoolConfig; } @@ -341,7 +344,7 @@ export class VercelPostgres extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: Partial & { postgresConnectionOptions?: VercelPostgresPoolConfig; } @@ -370,7 +373,7 @@ export class VercelPostgres extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, dbConfig?: Partial & { postgresConnectionOptions?: VercelPostgresPoolConfig; } diff --git a/libs/langchain-community/src/vectorstores/voy.ts b/libs/langchain-community/src/vectorstores/voy.ts index a1a341eb7701..3da3467dbb42 100644 --- a/libs/langchain-community/src/vectorstores/voy.ts +++ b/libs/langchain-community/src/vectorstores/voy.ts @@ -1,5 +1,5 @@ import type { Voy as VoyOriginClient, SearchResult } from "voy-search"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -31,7 +31,7 @@ export class VoyVectorStore extends VectorStore { return "voi"; } - constructor(client: VoyClient, embeddings: Embeddings) { + constructor(client: VoyClient, embeddings: EmbeddingsInterface) { super(embeddings, {}); this.client = client; this.embeddings = embeddings; @@ -156,7 +156,7 @@ export class VoyVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, client: VoyClient ): Promise { const docs: Document[] = []; @@ -181,7 +181,7 @@ export class VoyVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, client: VoyClient ): Promise { const instance = new VoyVectorStore(client, embeddings); diff --git a/libs/langchain-community/src/vectorstores/weaviate.ts b/libs/langchain-community/src/vectorstores/weaviate.ts index cf45fcdda489..0988c80293ee 100644 --- a/libs/langchain-community/src/vectorstores/weaviate.ts +++ b/libs/langchain-community/src/vectorstores/weaviate.ts @@ -8,7 +8,7 @@ import { MaxMarginalRelevanceSearchOptions, VectorStore, } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { maximalMarginalRelevance } from "@langchain/core/utils/math"; @@ -105,7 +105,7 @@ export class WeaviateStore extends VectorStore { return "weaviate"; } - constructor(public embeddings: Embeddings, args: WeaviateLibArgs) { + constructor(public embeddings: EmbeddingsInterface, args: WeaviateLibArgs) { super(embeddings, args); this.client = args.client; @@ -386,7 +386,7 @@ export class WeaviateStore extends VectorStore { static fromTexts( texts: string[], metadatas: object | object[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: WeaviateLibArgs ): Promise { const docs: Document[] = []; @@ -411,7 +411,7 @@ export class WeaviateStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: WeaviateLibArgs ): Promise { const instance = new this(embeddings, args); @@ -427,7 +427,7 @@ export class WeaviateStore extends VectorStore { * @returns A new `WeaviateStore` instance. */ static async fromExistingIndex( - embeddings: Embeddings, + embeddings: EmbeddingsInterface, args: WeaviateLibArgs ): Promise { return new this(embeddings, args); diff --git a/libs/langchain-community/src/vectorstores/xata.ts b/libs/langchain-community/src/vectorstores/xata.ts index 5b5c1d23bc5c..b67a459e3919 100644 --- a/libs/langchain-community/src/vectorstores/xata.ts +++ b/libs/langchain-community/src/vectorstores/xata.ts @@ -1,5 +1,5 @@ import { BaseClient } from "@xata.io/client"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore } from "@langchain/core/vectorstores"; import { Document } from "@langchain/core/documents"; @@ -35,7 +35,10 @@ export class XataVectorSearch< return "xata"; } - constructor(embeddings: Embeddings, args: XataClientArgs) { + constructor( + embeddings: EmbeddingsInterface, + args: XataClientArgs + ) { super(embeddings, args); this.client = args.client; diff --git a/libs/langchain-community/src/vectorstores/zep.ts b/libs/langchain-community/src/vectorstores/zep.ts index 0606c3437495..6fe9e90faa39 100644 --- a/libs/langchain-community/src/vectorstores/zep.ts +++ b/libs/langchain-community/src/vectorstores/zep.ts @@ -9,7 +9,7 @@ import { MaxMarginalRelevanceSearchOptions, VectorStore, } from "@langchain/core/vectorstores"; -import { Embeddings } from "@langchain/core/embeddings"; +import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { Document } from "@langchain/core/documents"; import { Callbacks } from "@langchain/core/callbacks/manager"; import { maximalMarginalRelevance } from "@langchain/core/utils/math"; @@ -67,7 +67,7 @@ export class ZepVectorStore extends VectorStore { private autoEmbed = false; - constructor(embeddings: Embeddings, args: IZepConfig) { + constructor(embeddings: EmbeddingsInterface, args: IZepConfig) { super(embeddings, args); this.embeddings = embeddings; @@ -366,7 +366,7 @@ export class ZepVectorStore extends VectorStore { static async fromTexts( texts: string[], metadatas: object[] | object, - embeddings: Embeddings, + embeddings: EmbeddingsInterface, zepConfig: IZepConfig ): Promise { const docs: Document[] = []; @@ -391,7 +391,7 @@ export class ZepVectorStore extends VectorStore { */ static async fromDocuments( docs: Document[], - embeddings: Embeddings, + embeddings: EmbeddingsInterface, zepConfig: IZepConfig ): Promise { const instance = new this(embeddings, zepConfig); diff --git a/libs/langchain-openai/src/chat_models.ts b/libs/langchain-openai/src/chat_models.ts index 88bc4d756e2c..72bbbeb3c3a8 100644 --- a/libs/langchain-openai/src/chat_models.ts +++ b/libs/langchain-openai/src/chat_models.ts @@ -18,7 +18,7 @@ import { ChatGenerationChunk, type ChatResult, } from "@langchain/core/outputs"; -import { StructuredTool } from "@langchain/core/tools"; +import type { StructuredToolInterface } from "@langchain/core/tools"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; import { BaseChatModel, @@ -171,7 +171,7 @@ function convertMessagesToOpenAIParams(messages: BaseMessage[]) { export interface ChatOpenAICallOptions extends OpenAICallOptions, BaseFunctionCallOptions { - tools?: StructuredTool[] | OpenAIClient.ChatCompletionTool[]; + tools?: StructuredToolInterface[] | OpenAIClient.ChatCompletionTool[]; tool_choice?: OpenAIClient.ChatCompletionToolChoiceOption; promptIndex?: number; response_format?: { type: "json_object" }; @@ -396,11 +396,11 @@ export class ChatOpenAI< ): Omit { function isStructuredToolArray( tools?: unknown[] - ): tools is StructuredTool[] { + ): tools is StructuredToolInterface[] { return ( tools !== undefined && tools.every((tool) => - Array.isArray((tool as StructuredTool).lc_namespace) + Array.isArray((tool as StructuredToolInterface).lc_namespace) ) ); } diff --git a/libs/langchain-openai/src/utils/openai.ts b/libs/langchain-openai/src/utils/openai.ts index 699b7afd4e20..6602b1db8989 100644 --- a/libs/langchain-openai/src/utils/openai.ts +++ b/libs/langchain-openai/src/utils/openai.ts @@ -4,7 +4,7 @@ import { type OpenAI as OpenAIClient, } from "openai"; import { zodToJsonSchema } from "zod-to-json-schema"; -import { StructuredTool } from "@langchain/core/tools"; +import type { StructuredToolInterface } from "@langchain/core/tools"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function wrapOpenAIClientError(e: any) { @@ -28,7 +28,7 @@ export function wrapOpenAIClientError(e: any) { * schema, which is then used as the parameters for the OpenAI function. */ export function formatToOpenAIFunction( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Chat.ChatCompletionCreateParams.Function { return { name: tool.name, @@ -38,7 +38,7 @@ export function formatToOpenAIFunction( } export function formatToOpenAITool( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Chat.ChatCompletionTool { const schema = zodToJsonSchema(tool.schema); return { @@ -52,7 +52,7 @@ export function formatToOpenAITool( } export function formatToOpenAIAssistantTool( - tool: StructuredTool + tool: StructuredToolInterface ): OpenAIClient.Beta.AssistantCreateParams.AssistantToolsFunction { return { type: "function",