index
int64
0
0
repo_id
stringclasses
596 values
file_path
stringlengths
31
168
content
stringlengths
1
6.2M
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/document_loaders.ts
import * as path from "node:path"; import * as fs from "node:fs"; import { boldText, getUserInput, greenText, redBackground, } from "../utils/get-input.js"; import { fetchURLStatus } from "../utils/fetch-url-status.js"; import { SIDEBAR_LABEL_PLACEHOLDER, MODULE_NAME_PLACEHOLDER, PACKAGE_NAME_PLACEHOLDER, FULL_IMPORT_PATH_PLACEHOLDER, ENV_VAR_NAME_PLACEHOLDER, PYTHON_DOC_URL_PLACEHOLDER, API_REF_MODULE_PLACEHOLDER, API_REF_PACKAGE_PLACEHOLDER, LOCAL_PLACEHOLDER, SERIALIZABLE_PLACEHOLDER, PY_SUPPORT_PLACEHOLDER, } from "../constants.js"; const NODE_SUPPORT_PLACEHOLDER = "__fs_support__"; const NODE_ONLY_SIDEBAR_BADGE_PLACEHOLDER = "__node_only_sidebar__"; const NODE_ONLY_TOOL_TIP_PLACEHOLDER = "__node_only_tooltip__"; const TEMPLATE_PATH = path.resolve( "./src/cli/docs/templates/document_loaders.ipynb" ); const INTEGRATIONS_DOCS_PATH = path.resolve( "../../docs/core_docs/docs/integrations/document_loaders" ); const NODE_ONLY_TOOLTIP = "```{=mdx}\\n\\n:::tip Compatibility\\n\\nOnly available on Node.js.\\n\\n:::\\n\\n```\\n"; const NODE_ONLY_SIDEBAR_BADGE = `sidebar_class_name: node-only`; type ExtraFields = { webLoader: boolean; nodeOnly: boolean; serializable: boolean; pySupport: boolean; local: boolean; envVarName: string; fullImportPath: string; packageName: string; }; async function promptExtraFields(fields: { envVarGuess: string; }): Promise<ExtraFields> { const isWebLoader = await getUserInput( "Is this integration a web loader? (y/n) ", undefined, true ); const isNodeOnly = await getUserInput( "Does this integration _only_ support Node environments? (y/n) ", undefined, true ); const isSerializable = await getUserInput( "Does this integration support serializable output? (y/n) ", undefined, true ); const hasPySupport = await getUserInput( "Does this integration have Python support? (y/n) ", undefined, true ); const hasLocalSupport = await getUserInput( "Does this integration support running locally? (y/n) ", undefined, true ); const importPath = await getUserInput( "What is the full import path of the integration? (e.g @langchain/community/llms/togetherai) ", undefined, true ); let packageName = ""; if (importPath.startsWith("langchain/")) { packageName = "langchain"; } else { packageName = importPath.split("/").slice(0, 2).join("/"); } const verifyPackageName = await getUserInput( `Is ${packageName} the correct package name? (y/n) `, undefined, true ); if (verifyPackageName.toLowerCase() === "n") { packageName = await getUserInput( "Please enter the full package name (e.g @langchain/community) ", undefined, true ); } const isEnvGuessCorrect = await getUserInput( `Is the environment variable for the API key named ${fields.envVarGuess}? (y/n) `, undefined, true ); let envVarName = fields.envVarGuess; if (isEnvGuessCorrect.toLowerCase() === "n") { envVarName = await getUserInput( "Please enter the correct environment variable name ", undefined, true ); } return { webLoader: isWebLoader.toLowerCase() === "y", nodeOnly: isNodeOnly.toLowerCase() === "y", serializable: isSerializable.toLowerCase() === "y", pySupport: hasPySupport.toLowerCase() === "y", local: hasLocalSupport.toLowerCase() === "y", envVarName, fullImportPath: importPath, packageName, }; } export async function fillDocLoaderIntegrationDocTemplate(fields: { className: string; }) { const sidebarLabel = fields.className.replace("Loader", ""); const pyDocUrl = `https://python.langchain.com/docs/integrations/document_loaders/${sidebarLabel.toLowerCase()}/`; let envVarName = `${sidebarLabel.toUpperCase()}_API_KEY`; const extraFields = await promptExtraFields({ envVarGuess: envVarName, }); envVarName = extraFields.envVarName; const importPathEnding = extraFields.fullImportPath.split("/").pop() ?? ""; const apiRefModuleUrl = `https://api.js.langchain.com/classes/${extraFields.fullImportPath .replace("@", "") .replaceAll("/", "_") .replaceAll("-", "_")}_${importPathEnding}.${fields.className}.html`; const apiRefPackageUrl = apiRefModuleUrl .replace("/classes/", "/modules/") .replace(`.${fields.className}.html`, ".html"); const apiRefUrlSuccesses = await Promise.all([ fetchURLStatus(apiRefModuleUrl), fetchURLStatus(apiRefPackageUrl), ]); if (apiRefUrlSuccesses.find((s) => !s)) { console.warn( "API ref URLs invalid. Please manually ensure they are correct." ); } const docTemplate = (await fs.promises.readFile(TEMPLATE_PATH, "utf-8")) .replaceAll(SIDEBAR_LABEL_PLACEHOLDER, sidebarLabel) .replaceAll(MODULE_NAME_PLACEHOLDER, fields.className) .replaceAll(PACKAGE_NAME_PLACEHOLDER, extraFields.packageName) .replaceAll(FULL_IMPORT_PATH_PLACEHOLDER, extraFields.fullImportPath) .replaceAll(ENV_VAR_NAME_PLACEHOLDER, envVarName) .replaceAll(PYTHON_DOC_URL_PLACEHOLDER, pyDocUrl) .replaceAll(API_REF_MODULE_PLACEHOLDER, apiRefModuleUrl) .replaceAll(API_REF_PACKAGE_PLACEHOLDER, apiRefPackageUrl) .replaceAll( NODE_ONLY_SIDEBAR_BADGE_PLACEHOLDER, extraFields.nodeOnly ? NODE_ONLY_SIDEBAR_BADGE : "" ) .replaceAll( NODE_ONLY_TOOL_TIP_PLACEHOLDER, extraFields?.nodeOnly ? NODE_ONLY_TOOLTIP : "" ) .replaceAll( NODE_SUPPORT_PLACEHOLDER, extraFields?.nodeOnly ? "Node-only" : "All environments" ) .replaceAll(LOCAL_PLACEHOLDER, extraFields?.local ? "✅" : "❌") .replaceAll( SERIALIZABLE_PLACEHOLDER, extraFields?.serializable ? "beta" : "❌" ) .replaceAll(PY_SUPPORT_PLACEHOLDER, extraFields?.pySupport ? "✅" : "❌"); const docPath = path.join( INTEGRATIONS_DOCS_PATH, extraFields?.webLoader ? "web_loaders" : "file_loaders", `${importPathEnding}.ipynb` ); await fs.promises.writeFile(docPath, docTemplate); const prettyDocPath = docPath.split("docs/core_docs/")[1]; const updatePythonDocUrlText = ` ${redBackground( "- Update the Python documentation URL with the proper URL." )}`; const successText = `\nSuccessfully created new document loader integration doc at ${prettyDocPath}.`; console.log( `${greenText(successText)}\n ${boldText("Next steps:")} ${extraFields?.pySupport ? updatePythonDocUrlText : ""} - Run all code cells in the generated doc to record the outputs. - Add extra sections on integration specific features.\n` ); }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/index.ts
// --------------------------------------------- // CLI for creating integration docs. // --------------------------------------------- import { Command } from "commander"; import { fillChatIntegrationDocTemplate } from "./chat.js"; import { fillDocLoaderIntegrationDocTemplate } from "./document_loaders.js"; import { fillLLMIntegrationDocTemplate } from "./llms.js"; import { fillRetrieverIntegrationDocTemplate } from "./retrievers.js"; import { fillEmbeddingsIntegrationDocTemplate } from "./embeddings.js"; import { fillToolkitIntegrationDocTemplate } from "./toolkits.js"; import { fillToolIntegrationDocTemplate } from "./tools.js"; import { fillKVStoreIntegrationDocTemplate } from "./kv_store.js"; import { fillVectorStoreIntegrationDocTemplate } from "./vectorstores.js"; type CLIInput = { type: string; classname: string; }; const ALLOWED_TYPES = [ "chat", "llm", "retriever", "embeddings", "doc_loader", "toolkit", "tool", "kv_store", "vectorstore", ]; async function main() { const program = new Command(); program .description("Create a new integration doc.") .option( "--classname <classname>", "Class name of the integration. e.g ChatOpenAI" ) .option( "--type <type>", `Type of integration.\nMust be one of:\n - ${ALLOWED_TYPES.join("\n - ")}` ); program.parse(); const options = program.opts<CLIInput>(); const { classname: className, type } = options; switch (type) { case "chat": await fillChatIntegrationDocTemplate({ className, }); break; case "llm": await fillLLMIntegrationDocTemplate({ className, }); break; case "embeddings": await fillEmbeddingsIntegrationDocTemplate({ className, }); break; case "retriever": await fillRetrieverIntegrationDocTemplate({ className, }); break; case "doc_loader": await fillDocLoaderIntegrationDocTemplate({ className, }); break; case "toolkit": await fillToolkitIntegrationDocTemplate({ className, }); break; case "tool": await fillToolIntegrationDocTemplate({ className, }); break; case "kv_store": await fillKVStoreIntegrationDocTemplate({ className, }); break; case "vectorstore": await fillVectorStoreIntegrationDocTemplate({ className, }); break; default: console.error( `Invalid type: '${type}'.\nMust be one of:\n - ${ALLOWED_TYPES.join( "\n - " )}` ); process.exit(1); } } main().catch((err) => { throw err; });
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/embeddings.ts
import * as path from "node:path"; import * as fs from "node:fs"; import { boldText, getUserInput, greenText, redBackground, } from "../utils/get-input.js"; import { fetchURLStatus } from "../utils/fetch-url-status.js"; import { PACKAGE_NAME_PLACEHOLDER, MODULE_NAME_PLACEHOLDER, SIDEBAR_LABEL_PLACEHOLDER, FULL_IMPORT_PATH_PLACEHOLDER, LOCAL_PLACEHOLDER, PY_SUPPORT_PLACEHOLDER, ENV_VAR_NAME_PLACEHOLDER, API_REF_MODULE_PLACEHOLDER, API_REF_PACKAGE_PLACEHOLDER, PYTHON_DOC_URL_PLACEHOLDER, } from "../constants.js"; const TEMPLATE_PATH = path.resolve( "./src/cli/docs/templates/text_embedding.ipynb" ); const INTEGRATIONS_DOCS_PATH = path.resolve( "../../docs/core_docs/docs/integrations/text_embedding" ); type ExtraFields = { local: boolean; pySupport: boolean; packageName: string; fullImportPath?: string; envVarName: string; }; async function promptExtraFields(fields: { envVarGuess: string; }): Promise<ExtraFields> { const { envVarGuess } = fields; const canRunLocally = await getUserInput( "Does this embeddings model support local usage? (y/n) ", undefined, true ); const hasPySupport = await getUserInput( "Does this integration have Python support? (y/n) ", undefined, true ); const importPath = await getUserInput( "What is the full import path of the integration? (e.g @langchain/community/embeddings/togetherai) ", undefined, true ); let packageName = ""; if (importPath.startsWith("langchain/")) { packageName = "langchain"; } else { packageName = importPath.split("/").slice(0, 2).join("/"); } const verifyPackageName = await getUserInput( `Is ${packageName} the correct package name? (y/n) `, undefined, true ); if (verifyPackageName.toLowerCase() === "n") { packageName = await getUserInput( "Please enter the full package name (e.g @langchain/community) ", undefined, true ); } const isEnvGuessCorrect = await getUserInput( `Is the environment variable for the API key named ${envVarGuess}? (y/n) `, undefined, true ); let envVarName = envVarGuess; if (isEnvGuessCorrect.toLowerCase() === "n") { envVarName = await getUserInput( "Please enter the correct environment variable name ", undefined, true ); } return { local: canRunLocally.toLowerCase() === "y", pySupport: hasPySupport.toLowerCase() === "y", packageName, fullImportPath: importPath, envVarName, }; } export async function fillEmbeddingsIntegrationDocTemplate(fields: { className: string; }) { const sidebarLabel = fields.className.replace("Embeddings", ""); const pyDocUrl = `https://python.langchain.com/docs/integrations/text_embedding/${sidebarLabel.toLowerCase()}/`; let envVarName = `${sidebarLabel.toUpperCase()}_API_KEY`; const extraFields = await promptExtraFields({ envVarGuess: envVarName, }); envVarName = extraFields.envVarName; const { pySupport } = extraFields; const localSupport = extraFields.local; const { packageName } = extraFields; const fullImportPath = extraFields.fullImportPath ?? extraFields.packageName; const apiRefModuleUrl = `https://api.js.langchain.com/classes/${fullImportPath .replace("@", "") .replaceAll("/", "_") .replaceAll("-", "_")}.${fields.className}.html`; const apiRefPackageUrl = apiRefModuleUrl .replace("/classes/", "/modules/") .replace(`.${fields.className}.html`, ".html"); const apiRefUrlSuccesses = await Promise.all([ fetchURLStatus(apiRefModuleUrl), fetchURLStatus(apiRefPackageUrl), ]); if (apiRefUrlSuccesses.find((s) => !s)) { console.warn( "API ref URLs invalid. Please manually ensure they are correct." ); } const docTemplate = (await fs.promises.readFile(TEMPLATE_PATH, "utf-8")) .replaceAll(PACKAGE_NAME_PLACEHOLDER, packageName) .replaceAll(MODULE_NAME_PLACEHOLDER, fields.className) .replaceAll(SIDEBAR_LABEL_PLACEHOLDER, sidebarLabel) .replaceAll(FULL_IMPORT_PATH_PLACEHOLDER, fullImportPath) .replaceAll(LOCAL_PLACEHOLDER, localSupport ? "✅" : "❌") .replaceAll(PY_SUPPORT_PLACEHOLDER, pySupport ? "✅" : "❌") .replaceAll(ENV_VAR_NAME_PLACEHOLDER, envVarName) .replaceAll(API_REF_MODULE_PLACEHOLDER, apiRefModuleUrl) .replaceAll(API_REF_PACKAGE_PLACEHOLDER, apiRefPackageUrl) .replaceAll(PYTHON_DOC_URL_PLACEHOLDER, pyDocUrl); const docFileName = fullImportPath.split("/").pop(); const docPath = path.join(INTEGRATIONS_DOCS_PATH, `${docFileName}.ipynb`); await fs.promises.writeFile(docPath, docTemplate); const prettyDocPath = docPath.split("docs/core_docs/")[1]; const updatePythonDocUrlText = ` ${redBackground( "- Update the Python documentation URL with the proper URL." )}`; const successText = `\nSuccessfully created new chat model integration doc at ${prettyDocPath}.`; console.log( `${greenText(successText)}\n ${boldText("Next steps:")} ${extraFields?.pySupport ? updatePythonDocUrlText : ""} - Run all code cells in the generated doc to record the outputs. - Add extra sections on integration specific features.\n` ); }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/toolkits.ts
import * as path from "node:path"; import * as fs from "node:fs"; import { boldText, getUserInput, greenText, redBackground, } from "../utils/get-input.js"; import { fetchURLStatus } from "../utils/fetch-url-status.js"; import { SIDEBAR_LABEL_PLACEHOLDER, MODULE_NAME_PLACEHOLDER, PACKAGE_NAME_PLACEHOLDER, FULL_IMPORT_PATH_PLACEHOLDER, PYTHON_DOC_URL_PLACEHOLDER, API_REF_MODULE_PLACEHOLDER, PY_SUPPORT_PLACEHOLDER, } from "../constants.js"; const TEMPLATE_PATH = path.resolve("./src/cli/docs/templates/toolkits.ipynb"); const INTEGRATIONS_DOCS_PATH = path.resolve( "../../docs/core_docs/docs/integrations/toolkits" ); type ExtraFields = { pySupport: boolean; fullImportPath: string; packageName: string; }; async function promptExtraFields(): Promise<ExtraFields> { const hasPySupport = await getUserInput( "Does this integration have Python support? (y/n) ", undefined, true ); const importPath = await getUserInput( "What is the full import path of the integration? (e.g @langchain/community/llms/togetherai) ", undefined, true ); let packageName = ""; if (importPath.startsWith("langchain/")) { packageName = "langchain"; } else { packageName = importPath.split("/").slice(0, 2).join("/"); } const verifyPackageName = await getUserInput( `Is ${packageName} the correct package name? (y/n) `, undefined, true ); if (verifyPackageName.toLowerCase() === "n") { packageName = await getUserInput( "Please enter the full package name (e.g @langchain/community) ", undefined, true ); } return { pySupport: hasPySupport.toLowerCase() === "y", fullImportPath: importPath, packageName, }; } export async function fillToolkitIntegrationDocTemplate(fields: { className: string; }) { const sidebarLabel = fields.className.replace("Toolkit", ""); const pyDocUrl = `https://python.langchain.com/docs/integrations/toolkits/${sidebarLabel.toLowerCase()}/`; const extraFields = await promptExtraFields(); const importPathEnding = extraFields.fullImportPath.split("/").pop() ?? ""; const apiRefModuleUrl = `https://api.js.langchain.com/classes/${extraFields.fullImportPath .replace("@", "") .replaceAll("/", "_") .replaceAll("-", "_")}.${fields.className}.html`; const apiRefUrlSuccess = await fetchURLStatus(apiRefModuleUrl); if (apiRefUrlSuccess === false) { console.warn( "API ref URL is invalid. Please manually ensure it is correct." ); } const docTemplate = (await fs.promises.readFile(TEMPLATE_PATH, "utf-8")) .replaceAll(SIDEBAR_LABEL_PLACEHOLDER, sidebarLabel) .replaceAll(MODULE_NAME_PLACEHOLDER, fields.className) .replaceAll(PACKAGE_NAME_PLACEHOLDER, extraFields.packageName) .replaceAll(FULL_IMPORT_PATH_PLACEHOLDER, extraFields.fullImportPath) .replaceAll(PYTHON_DOC_URL_PLACEHOLDER, pyDocUrl) .replaceAll(API_REF_MODULE_PLACEHOLDER, apiRefModuleUrl) .replaceAll(PY_SUPPORT_PLACEHOLDER, extraFields?.pySupport ? "✅" : "❌"); const docPath = path.join( INTEGRATIONS_DOCS_PATH, `${importPathEnding}.ipynb` ); await fs.promises.writeFile(docPath, docTemplate); const prettyDocPath = docPath.split("docs/core_docs/")[1]; const updatePythonDocUrlText = ` ${redBackground( "- Update the Python documentation URL with the proper URL." )}`; const successText = `\nSuccessfully created new document loader integration doc at ${prettyDocPath}.`; console.log( `${greenText(successText)}\n ${boldText("Next steps:")} ${extraFields?.pySupport ? updatePythonDocUrlText : ""} - Run all code cells in the generated doc to record the outputs. - Add extra sections on integration specific features.\n` ); }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/text_embedding.ipynb
import { __module_name__ } from "__full_import_path__"; const embeddings = new __module_name__({ model: "model-name", // ... });// Create a vector store with a sample text import { MemoryVectorStore } from "langchain/vectorstores/memory"; const text = "LangChain is the framework for building context-aware reasoning applications"; const vectorstore = await MemoryVectorStore.fromDocuments( [{ pageContent: text, metadata: {} }], embeddings, ); // Use the vector store as a retriever that returns a single document const retriever = vectorstore.asRetriever(1); // Retrieve the most similar text const retrievedDocuments = await retriever.invoke("What is LangChain?"); retrievedDocuments[0].pageContent;const singleVector = await embeddings.embedQuery(text); console.log(singleVector.slice(0, 100));const text2 = "LangGraph is a library for building stateful, multi-actor applications with LLMs"; const vectors = await embeddings.embedDocuments([text, text2]); console.log(vectors[0].slice(0, 100)); console.log(vectors[1].slice(0, 100));
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/llms.ipynb
import { __module_name__ } from "__full_import_path__" const llm = new __module_name__({ model: "model-name", temperature: 0, maxTokens: undefined, timeout: undefined, maxRetries: 2, // other params... })const inputText = "__module_name__ is an AI company that " const completion = await llm.invoke(inputText) completionimport { PromptTemplate } from "@langchain/core/prompts" const prompt = PromptTemplate.fromTemplate("How to say {input} in {output_language}:\n") const chain = prompt.pipe(llm); await chain.invoke( { output_language: "German", input: "I love programming.", } )
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/chat.ipynb
import { __module_name__ } from "__full_import_path__" const llm = new __module_name__({ model: "model-name", temperature: 0, maxTokens: undefined, timeout: undefined, maxRetries: 2, // other params... })const aiMsg = await llm.invoke([ [ "system", "You are a helpful assistant that translates English to French. Translate the user sentence.", ], ["human", "I love programming."], ]) aiMsgconsole.log(aiMsg.content)import { ChatPromptTemplate } from "@langchain/core/prompts" const prompt = ChatPromptTemplate.fromMessages( [ [ "system", "You are a helpful assistant that translates {input_language} to {output_language}.", ], ["human", "{input}"], ] ) const chain = prompt.pipe(llm); await chain.invoke( { input_language: "English", output_language: "German", input: "I love programming.", } )
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/document_loaders.ipynb
import { __module_name__ } from "__full_import_path__" const loader = new __module_name__({ // required params = ... // optional params = ... })const docs = await loader.load() docs[0]console.log(docs[0].metadata)
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/vectorstores.ipynb
import { __module_name__ } from "__full_import_path__"; import { OpenAIEmbeddings } from "@langchain/openai"; const embeddings = new OpenAIEmbeddings({ model: "text-embedding-3-small", }); const vectorStore = new __module_name__(embeddings);import type { Document } from "@langchain/core/documents"; const document1: Document = { pageContent: "The powerhouse of the cell is the mitochondria", metadata: { source: "https://example.com" } }; const document2: Document = { pageContent: "Buildings are made out of brick", metadata: { source: "https://example.com" } }; const document3: Document = { pageContent: "Mitochondria are made out of lipids", metadata: { source: "https://example.com" } }; const document4: Document = { pageContent: "The 2024 Olympics are in Paris", metadata: { source: "https://example.com" } } const documents = [document1, document2, document3, document4]; await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });await vectorStore.delete({ ids: ["4"] });const filter = { source: "https://example.com" }; const similaritySearchResults = await vectorStore.similaritySearch("biology", 2, filter); for (const doc of similaritySearchResults) { console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`); }const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2, filter) for (const [doc, score] of similaritySearchWithScoreResults) { console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`); }const retriever = vectorStore.asRetriever({ // Optional filter filter: filter, k: 2, }); await retriever.invoke("biology");
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/kv_store.ipynb
import { __module_name__ } from "__full_import_path__" const kvStore = new __module_name__({ // params... })const encoder = new TextEncoder(); const decoder = new TextDecoder();await kvStore.mset( [ ["key1", encoder.encode("value1")], ["key2", encoder.encode("value2")], ] ) const results = await kvStore.mget( [ "key1", "key2", ] ) console.log(results.map((v) => decoder.decode(v)));await kvStore.mdelete( [ "key1", "key2", ] ) await kvStore.mget( [ "key1", "key2", ] )import { __module_name__ } from "__full_import_path__" const kvStoreForYield = new __module_name__({ ... }); const encoderForYield = new TextEncoder(); // Add some data to the store await kvStoreForYield.mset( [ ["message:id:key1", encoderForYield.encode("value1")], ["message:id:key2", encoderForYield.encode("value2")], ] ) const yieldedKeys = []; for await (const key of kvStoreForYield.yieldKeys("message:id:")) { yieldedKeys.push(key); } console.log(yieldedKeys);
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/tools.ipynb
import { __module_name__ } from "__full_import_path__" const tool = new __module_name__({ // ... })await tool.invoke("...")// This is usually generated by a model, but we'll create a tool call directly for demo purposes. const modelGeneratedToolCall = { args: {}, // TODO: FILL IN id: "1", name: tool.name, type: "tool_call", } await tool.invoke(modelGeneratedToolCall)// @lc-docs-hide-cell import { ChatOpenAI } from "@langchain/openai" const llm = new ChatOpenAI({ model: "gpt-4o-mini", })import { HumanMessage } from "@langchain/core/messages"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { RunnableLambda } from "@langchain/core/runnables"; const prompt = ChatPromptTemplate.fromMessages( [ ["system", "You are a helpful assistant."], ["placeholder", "{messages}"], ] ) const llmWithTools = llm.bindTools([tool]); const chain = prompt.pipe(llmWithTools); const toolChain = RunnableLambda.from( async (userInput: string, config) => { const humanMessage = new HumanMessage(userInput,); const aiMsg = await chain.invoke({ messages: [new HumanMessage(userInput)], }, config); const toolMsgs = await tool.batch(aiMsg.tool_calls, config); return chain.invoke({ messages: [humanMessage, aiMsg, ...toolMsgs], }, config); } ); const toolChainResult = await toolChain.invoke("what is the current weather in sf?");const { tool_calls, content } = toolChainResult; console.log("AIMessage", JSON.stringify({ tool_calls, content, }, null, 2));
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/toolkits.ipynb
import { __module_name__ } from "__full_import_path__" const toolkit = new __module_name__({ // ... })const tools = toolkit.getTools(); console.log(tools.map((tool) => ({ name: tool.name, description: tool.description, })))// @lc-docs-hide-cell import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0, })import { createReactAgent } from "@langchain/langgraph/prebuilt" const agentExecutor = createReactAgent({ llm, tools });const exampleQuery = "..." const events = await agentExecutor.stream( { messages: [["user", exampleQuery]]}, { streamMode: "values", } ) for await (const event of events) { const lastMsg = event.messages[event.messages.length - 1]; if (lastMsg.tool_calls?.length) { console.dir(lastMsg.tool_calls, { depth: null }); } else if (lastMsg.content) { console.log(lastMsg.content); } }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/docs/templates/retrievers.ipynb
import { __module_name__ } from "__full_import_path__"; const retriever = new __module_name__( // ... );const query = "..." await retriever.invoke(query);// @lc-docs-hide-cell import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0, });import { ChatPromptTemplate } from "@langchain/core/prompts"; import { RunnablePassthrough, RunnableSequence } from "@langchain/core/runnables"; import { StringOutputParser } from "@langchain/core/output_parsers"; import type { Document } from "@langchain/core/documents"; const prompt = ChatPromptTemplate.fromTemplate(` Answer the question based only on the context provided. Context: {context} Question: {question}`); const formatDocs = (docs: Document[]) => { return docs.map((doc) => doc.pageContent).join("\n\n"); } // See https://js.langchain.com/docs/tutorials/rag const ragChain = RunnableSequence.from([ { context: retriever.pipe(formatDocs), question: new RunnablePassthrough(), }, prompt, llm, new StringOutputParser(), ]);await ragChain.invoke("...")
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/utils/fetch-url-status.ts
export const fetchURLStatus = async (url: string): Promise<boolean> => { try { const res = await fetch(url); if (res.status !== 200) { throw new Error(`API Reference URL ${url} not found.`); } return true; } catch (_) { return false; } };
0
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli
lc_public_repos/langchainjs/libs/langchain-scripts/src/cli/utils/get-input.ts
import * as readline from "readline"; type Color = "green" | "red_background" | "white_background"; export const greenText = (text: string) => `\x1b[1m\x1b[92m${text}\x1b[0m`; export const boldText = (text: string) => `\x1b[1m${text}\x1b[0m`; export const redBackground = (text: string) => `\x1b[41m\x1b[37m${text}\x1b[0m`; export const whiteBackground = (text: string) => `\x1b[30m\x1b[47m${text}\x1b[0m`; /** * Prompts the user with a question and returns the user input. * * @param {string} question The question to log to the users terminal. * @param {Color | undefined} color The color to use for the question. * @param {boolean | undefined} bold Whether to make the question bold. * @returns {Promise<string>} The user input. */ export async function getUserInput( question: string, color?: Color, bold?: boolean ): Promise<string> { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let questionWithStyling = question; if (bold) { questionWithStyling = boldText(questionWithStyling); } if (color === "green") { questionWithStyling = greenText(questionWithStyling); } else if (color === "red_background") { questionWithStyling = redBackground(questionWithStyling); } else if (color === "white_background") { questionWithStyling = whiteBackground(questionWithStyling); } return new Promise((resolve) => { rl.question(questionWithStyling, (input) => { rl.close(); resolve(input); }); }); }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src
lc_public_repos/langchainjs/libs/langchain-scripts/src/build/index.ts
import { spawn } from "node:child_process"; import ts from "typescript"; import fs from "node:fs"; import { Command } from "commander"; import { rollup } from "@rollup/wasm-node"; import path from "node:path"; import { glob } from "glob"; import { ExportsMapValue, ImportData, LangChainConfig } from "../types.js"; async function asyncSpawn(command: string, args: string[]) { return new Promise<void>((resolve, reject) => { const child = spawn(command, args, { stdio: "inherit", env: { // eslint-disable-next-line no-process-env ...process.env, NODE_OPTIONS: "--max-old-space-size=4096", }, shell: true, }); child.on("close", (code) => { if (code !== 0) { reject(new Error(`Command failed: ${command} ${args.join(" ")}`)); return; } resolve(); }); }); } const fsRmRfSafe = async (inputPath: string) => { try { await fs.promises.rm(inputPath, { recursive: true, force: true }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { console.log( `Error deleting directory via fs.promises.rm: ${error.code}. Path: ${inputPath}` ); } }; const fsUnlinkSafe = async (filePath: string) => { try { await fs.promises.unlink(filePath); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { console.log( `Error deleting file via fs.promises.unlink: ${error.code}. Path: ${filePath}` ); } }; const NEWLINE = ` `; // List of test-exports-* packages which we use to test that the exports field // works correctly across different JS environments. // Each entry is a tuple of [package name, import statement]. const testExports: Array<[string, (p: string) => string]> = [ [ "test-exports-esm", (p: string) => `import * as ${p.replace(/\//g, "_")} from "langchain/${p}";`, ], [ "test-exports-esbuild", (p: string) => `import * as ${p.replace(/\//g, "_")} from "langchain/${p}";`, ], [ "test-exports-cjs", (p: string) => `const ${p.replace(/\//g, "_")} = require("langchain/${p}");`, ], ["test-exports-cf", (p: string) => `export * from "langchain/${p}";`], ["test-exports-vercel", (p: string) => `export * from "langchain/${p}";`], ["test-exports-vite", (p: string) => `export * from "langchain/${p}";`], ["test-exports-bun", (p: string) => `export * from "langchain/${p}";`], ]; const DEFAULT_GITIGNORE_PATHS = ["node_modules", "dist", ".yarn"]; async function createImportMapFile(config: LangChainConfig): Promise<void> { const createImportStatement = (k: string, p: string) => `export * as ${k.replace(/\//g, "__")} from "../${ p.replace("src/", "").endsWith(".ts") ? p.replace(".ts", ".js") : `${p}.js` }";`; const entrypointsToInclude = Object.keys(config.entrypoints) .filter((key) => key !== "load") .filter((key) => !config.deprecatedNodeOnly?.includes(key)) .filter((key) => !config.requiresOptionalDependency?.includes(key)) .filter((key) => !config.deprecatedOmitFromImportMap?.includes(key)); const importMapExports = entrypointsToInclude .map((key) => `${createImportStatement(key, config.entrypoints[key])}`) .join("\n"); let extraContent = ""; if (config.extraImportMapEntries) { const extraImportData = config.extraImportMapEntries?.reduce<ImportData>( (data, { modules, alias, path }) => { const newData = { ...data }; if (!newData.imports[path]) { newData.imports[path] = []; } newData.imports[path] = [ ...new Set(newData.imports[path].concat(modules)), ]; const exportAlias = alias.join("__"); if (!newData.exportedAliases[exportAlias]) { newData.exportedAliases[exportAlias] = []; } newData.exportedAliases[exportAlias] = newData.exportedAliases[exportAlias].concat(modules); return newData; }, { imports: {}, exportedAliases: {}, } ); const extraImportStatements = Object.entries(extraImportData.imports).map( ([path, modules]) => `import {\n ${modules.join(",\n ")}\n} from "${path}";` ); const extraDeclarations = Object.entries( extraImportData.exportedAliases ).map(([exportAlias, modules]) => [ `const ${exportAlias} = {\n ${modules.join(",\n ")}\n};`, `export { ${exportAlias} };`, ].join("\n") ); extraContent = `${extraImportStatements.join( "\n" )}\n${extraDeclarations.join("\n")}\n`; extraContent.trim(); if (!/[a-zA-Z0-9]/.test(extraContent)) { extraContent = ""; } } const importMapContents = `// Auto-generated by build script. Do not edit manually.\n\n${importMapExports}\n${extraContent}`; await fs.promises.writeFile("src/load/import_map.ts", importMapContents); } async function generateImportConstants(config: LangChainConfig): Promise<void> { // Generate import constants const entrypointsToInclude = Object.keys(config.entrypoints) .filter((key) => !config.deprecatedNodeOnly?.includes(key)) .filter((key) => config.requiresOptionalDependency?.includes(key)); const importConstantsPath = "src/load/import_constants.ts"; const createImportStatement = (k: string) => ` "langchain${ config.packageSuffix ? `_${config.packageSuffix}` : "" }/${k}"`; const contents = entrypointsToInclude.length > 0 ? `\n${entrypointsToInclude .map((key) => createImportStatement(key)) .join(",\n")},\n];\n` : "];\n"; await fs.promises.writeFile( `${importConstantsPath}`, `// Auto-generated by \`scripts/create-entrypoints.js\`. Do not edit manually.\n\nexport const optionalImportEntrypoints: string[] = [${contents}` ); } const generateFiles = (config: LangChainConfig): Record<string, string> => { const files = [...Object.entries(config.entrypoints)].flatMap( ([key, value]) => { const nrOfDots = key.split("/").length - 1; const relativePath = "../".repeat(nrOfDots) || "./"; const compiledPath = `${relativePath}dist/${value}.js`; return [ [ `${key}.cjs`, `module.exports = require('${relativePath}dist/${value}.cjs');`, ], [`${key}.js`, `export * from '${compiledPath}'`], [`${key}.d.ts`, `export * from '${compiledPath}'`], [`${key}.d.cts`, `export * from '${compiledPath}'`], ]; } ); return Object.fromEntries(files); }; async function updateExportTestFiles(config: LangChainConfig): Promise<void[]> { // Update test-exports-*/entrypoints.js const entrypointsToTest = Object.keys(config.entrypoints) .filter((key) => !config.deprecatedNodeOnly?.includes(key)) .filter((key) => !config.requiresOptionalDependency?.includes(key)); return Promise.all( testExports.map(async ([pkg, importStatement]) => { const contents = `${entrypointsToTest .map((key) => importStatement(key)) .join("\n")}\n`; return fs.promises.writeFile( `../environment_tests/${pkg}/src/entrypoints.js`, contents ); }) ); } async function writeTopLevelGeneratedFiles( generatedFiles: Record<string, string> ): Promise<void[]> { return Promise.all( Object.entries(generatedFiles).map(async ([filename, content]) => { await fs.promises.mkdir(path.dirname(filename), { recursive: true }); await fs.promises.writeFile(filename, content); }) ); } async function updateGitIgnore( config: LangChainConfig, filenames: string[] ): Promise<void> { const gitignorePaths = [ ...filenames, ...DEFAULT_GITIGNORE_PATHS, ...(config.additionalGitignorePaths ? config.additionalGitignorePaths : []), ]; // Update .gitignore return fs.promises.writeFile( "./.gitignore", `${gitignorePaths.join("\n")}\n` ); } async function updatePackageJson(config: LangChainConfig): Promise<void> { const packageJson = JSON.parse( await fs.promises.readFile(`package.json`, "utf8") ); const generatedFiles = generateFiles(config); const filenames = Object.keys(generatedFiles); packageJson.files = ["dist/", ...filenames]; packageJson.exports = Object.keys(config.entrypoints).reduce( (acc: Record<string, ExportsMapValue>, key) => { let entrypoint = `./${key}`; if (key === "index") { entrypoint = "."; } acc[entrypoint] = { types: { import: `./${key}.d.ts`, require: `./${key}.d.cts`, default: `./${key}.d.ts`, }, import: `./${key}.js`, require: `./${key}.cjs`, }; return acc; }, {} ); packageJson.exports = { ...packageJson.exports, "./package.json": "./package.json", }; let packageJsonString = JSON.stringify(packageJson, null, 2); if ( !packageJsonString.endsWith("\n") && !packageJsonString.endsWith(NEWLINE) ) { packageJsonString += NEWLINE; } // Write package.json and generate d.cts files // Optionally, update test exports files await Promise.all([ fs.promises.writeFile(`package.json`, packageJsonString), writeTopLevelGeneratedFiles(generatedFiles), updateGitIgnore(config, filenames), config.shouldTestExports ? updateExportTestFiles(config) : Promise.resolve(), ]); } export function identifySecrets(absTsConfigPath: string) { const secrets = new Set(); const tsConfig = ts.parseJsonConfigFileContent( ts.readJsonConfigFile(absTsConfigPath, (p) => fs.readFileSync(p, "utf-8")), ts.sys, "./src/" ); // `tsConfig.options.target` is not always defined when running this // via the `@langchain/scripts` package. Instead, fallback to the raw // tsConfig.json file contents. const tsConfigFileContentsText = "text" in tsConfig.raw ? JSON.parse(tsConfig.raw.text as string) : { compilerOptions: {} }; const tsConfigTarget = tsConfig.options.target || tsConfigFileContentsText.compilerOptions.target; for (const fileName of tsConfig.fileNames.filter( (fn) => !fn.endsWith("test.ts") )) { if (!tsConfigTarget) { continue; } const sourceFile = ts.createSourceFile( fileName, fs.readFileSync(fileName, "utf-8"), tsConfigTarget, true ); sourceFile.forEachChild((node) => { switch (node.kind) { case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.ClassExpression: { node.forEachChild((node) => { // look for get lc_secrets() switch (node.kind) { case ts.SyntaxKind.GetAccessor: { const property = node; if ( ts.isGetAccessor(property) && property.name.getText() === "lc_secrets" ) { // look for return { ... } property.body?.statements.forEach((stmt) => { if ( ts.isReturnStatement(stmt) && stmt.expression && ts.isObjectLiteralExpression(stmt.expression) ) { stmt.expression.properties.forEach((element) => { if (ts.isPropertyAssignment(element)) { // Type guard for PropertyAssignment if ( element.initializer && ts.isStringLiteral(element.initializer) ) { const secret = element.initializer.text; if (secret.toUpperCase() !== secret) { throw new Error( `Secret identifier must be uppercase: ${secret} at ${fileName}` ); } if (/\s/.test(secret)) { throw new Error( `Secret identifier must not contain whitespace: ${secret} at ${fileName}` ); } secrets.add(secret); } } }); } }); } break; } default: break; } }); break; } default: break; } }); } return secrets; } async function generateImportTypes(config: LangChainConfig): Promise<void> { // Generate import types const pkg = `langchain${ config.packageSuffix ? `-${config.packageSuffix}` : "" }`; const importTypesPath = "src/load/import_type.ts"; await fs.promises.writeFile( `../${pkg}/${importTypesPath}`, `// Auto-generated by \`scripts/create-entrypoints.js\`. Do not edit manually. export interface OptionalImportMap {} export interface SecretMap { ${[...identifySecrets(config.tsConfigPath)] .sort() .map((secret) => ` ${secret}?: string;`) .join("\n")} } ` ); } function listExternals( // eslint-disable-next-line @typescript-eslint/no-explicit-any packageJson: Record<string, any>, extraInternals?: Array<string | RegExp> ) { return [ ...Object.keys(packageJson.dependencies ?? {}), ...Object.keys(packageJson.peerDependencies ?? {}), ...(extraInternals || []), ]; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function listEntrypoints(packageJson: Record<string, any>) { const { exports } = packageJson; /** @type {Record<string, ExportsMapValue | string> | null} */ const exportsWithoutPackageJSON: Record< string, ExportsMapValue | string > | null = exports ? Object.entries(exports) .filter(([k]) => k !== "./package.json") .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) : null; if (!exportsWithoutPackageJSON) { throw new Error("No exports found in package.json"); } /** @type {string[]} */ const entrypoints = []; for (const [key, value] of Object.entries(exportsWithoutPackageJSON)) { if (key === "./package.json") { continue; } if (typeof value === "string") { entrypoints.push(value); } else if ( "import" in value && value.import && typeof value.import === "string" ) { entrypoints.push(value.import); } } return entrypoints; } /** * Checks whether or not the file has side effects marked with the `__LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__` * keyword comment. If it does, this function will return `true`, otherwise it will return `false`. * * @param {string} entrypoint * @returns {Promise<boolean>} Whether or not the file has side effects which are explicitly marked as allowed. */ const checkAllowSideEffects = async ( entrypoint: string, filename?: string ): Promise<boolean> => { let entrypointContent; try { entrypointContent = await fs.promises.readFile(`./dist/${entrypoint}.js`); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (e: any) { if (e.message.includes("ENOENT")) { // Entrypoint is likely via an `index.js` file, retry with `index.js` appended to path entrypointContent = await fs.promises.readFile( `./dist/${entrypoint}/index.js` ); } else { entrypointContent = Buffer.from(""); } } let fileContent; try { fileContent = await fs.promises.readFile(`./${filename}`); } catch (e) { fileContent = Buffer.from(""); } // Allow escaping side effects strictly within code directly // within an entrypoint return ( entrypointContent .toString() .includes("/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */") || fileContent .toString() .includes("/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */") ); }; async function checkTreeShaking(config: LangChainConfig) { const packageJson = JSON.parse( await fs.promises.readFile("package.json", "utf8") ); const externals = listExternals(packageJson, config?.internals ?? []); const entrypoints = listEntrypoints(packageJson); const consoleInfo = console.info; /** @type {Map<string, { log: string; hasUnexpectedSideEffects: boolean; }>} */ const reportMap = new Map(); for (const entrypoint of entrypoints) { const sideEffects: { log: string; filename?: string }[] = []; console.info = function (...args) { const line = args.length ? args.join(" ") : ""; if (line.includes("First side effect in")) { const match = line.match(/First side effect in (.+?) is at/); const filename = match ? match[1] : undefined; sideEffects.push({ log: `${line}\n`, filename }); } }; await rollup({ external: externals, input: entrypoint, experimentalLogSideEffects: true, }); let hasUnexpectedSideEffects = false; for (const sideEffect of sideEffects) { if (sideEffect.filename) { // Map the entrypoint back to the actual file entrypoint using the LangChainConfig file const actualEntrypoint = config.entrypoints[entrypoint.replace(/^\.\/|\.js$/g, "")]; const allowSideEffects = await checkAllowSideEffects( actualEntrypoint, sideEffect.filename ); if (!allowSideEffects) { hasUnexpectedSideEffects = true; break; } } else { // If we can't determine the filename, we'll consider it an unexpected side effect hasUnexpectedSideEffects = true; break; } } reportMap.set(entrypoint, { log: sideEffects.map(({ log }) => log).join(""), hasUnexpectedSideEffects, }); } console.info = consoleInfo; let failed = false; for (const [entrypoint, report] of reportMap) { if (report.hasUnexpectedSideEffects) { failed = true; console.log("---------------------------------"); console.log(`Tree shaking failed for ${entrypoint}`); console.log(report.log); } } if (failed) { // TODO: Throw a hard error here console.log("Tree shaking checks failed."); } else { console.log("Tree shaking checks passed!"); } } function processOptions(): { shouldCreateEntrypoints: boolean; shouldCheckTreeShaking: boolean; shouldGenMaps: boolean; pre: boolean; } { const program = new Command(); program .description("Run a build script for a LangChain package.") .option( "--config <config>", "Path to the config file, defaults to ./langchain.config.js" ) .option( "--create-entrypoints", "Pass only if you want to create entrypoints" ) .option("--tree-shaking", "Pass only if you want to check tree shaking") .option("--gen-maps") .option("--pre"); program.parse(); const options = program.opts(); const shouldCreateEntrypoints = options.createEntrypoints; const shouldCheckTreeShaking = options.treeShaking; const shouldGenMaps = options.genMaps; const { pre } = options; return { shouldCreateEntrypoints, shouldCheckTreeShaking, shouldGenMaps, pre, }; } async function cleanGeneratedFiles(config: LangChainConfig) { const allFileNames = Object.keys(config.entrypoints) .map((key) => [`${key}.cjs`, `${key}.js`, `${key}.d.ts`]) .flat(); return Promise.all( allFileNames.map(async (fileName) => { await fsUnlinkSafe(fileName); }) ); } export async function moveAndRename({ source, dest, abs, }: { source: string; dest: string; abs: (p: string) => string; }) { if (!fs.existsSync(abs(source))) { return; } let renamedDestination = ""; try { for await (const file of await fs.promises.readdir(abs(source), { withFileTypes: true, })) { if (file.isDirectory()) { await moveAndRename({ source: `${source}/${file.name}`, dest: `${dest}/${file.name}`, abs, }); } else if (file.isFile()) { const parsed = path.parse(file.name); // Ignore anything that's not a .js file if (parsed.ext !== ".js") { continue; } // Rewrite any require statements to use .cjs const content = await fs.promises.readFile( abs(`${source}/${file.name}`), "utf8" ); const rewritten = content.replace( /require\("(\..+?).js"\)/g, (_, p1) => `require("${p1}.cjs")` ); // Rename the file to .cjs const renamed = path.format({ name: parsed.name, ext: ".cjs" }); renamedDestination = abs(`${dest}/${renamed}`); await fs.promises.writeFile(renamedDestination, rewritten, "utf8"); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { console.error("Error during moveAndRename"); if (error.code === "ENOENT") { // Check if file already exists in destination if (fs.existsSync(renamedDestination)) { console.error( `File already exists in destination: ${renamedDestination}` ); } else { console.error(`File not found: ${error.path}`); } } } } export async function buildWithTSup() { const { shouldCreateEntrypoints, shouldCheckTreeShaking, shouldGenMaps, pre, } = processOptions(); let langchainConfigPath = path.resolve("langchain.config.js"); if (process.platform === "win32") { // windows, must resolve path with file:// langchainConfigPath = `file:///${langchainConfigPath}`; } const { config }: { config: LangChainConfig } = await import( langchainConfigPath ); // Clean & generate build files if (pre && shouldGenMaps) { await Promise.all([ fsRmRfSafe("dist").catch((e) => { console.error("Error removing dist (pre && shouldGenMaps)"); throw e; }), cleanGeneratedFiles(config), createImportMapFile(config), generateImportConstants(config), generateImportTypes(config), ]); } else if (pre && !shouldGenMaps) { await Promise.all([ fsRmRfSafe("dist").catch((e) => { console.error("Error removing dist (pre && !shouldGenMaps)"); throw e; }), cleanGeneratedFiles(config), ]); } if (shouldCreateEntrypoints) { await Promise.all([ asyncSpawn("tsc", ["--outDir", "dist/"]), asyncSpawn("tsc", ["--outDir", "dist-cjs/", "-p", "tsconfig.cjs.json"]), ]); await moveAndRename({ source: config.cjsSource, dest: config.cjsDestination, abs: config.abs, }); // move CJS to dist await Promise.all([ updatePackageJson(config), fsRmRfSafe("dist-cjs").catch((e) => { console.error("Error removing dist-cjs"); throw e; }), fsRmRfSafe("dist/tests").catch((e) => { console.error("Error removing dist/tests"); throw e; }), (async () => { // Required for cross-platform compatibility. // Windows does not manage globs the same as Max/Linux when deleting directories. const testFolders = await glob("dist/**/tests"); await Promise.all(testFolders.map((folder) => fsRmRfSafe(folder))); })().catch((e) => { console.error("Error removing dist/**/tests"); throw e; }), ]); } if (shouldCheckTreeShaking) { // Checks tree shaking via rollup await checkTreeShaking(config); } } /* #__PURE__ */ buildWithTSup().catch((e) => { console.error(e); process.exit(1); });
0
lc_public_repos/langchainjs/libs/langchain-scripts/src
lc_public_repos/langchainjs/libs/langchain-scripts/src/build/utils.ts
import { LangChainConfig } from "../types.js"; export function _verifyObjectIsLangChainConfig( // eslint-disable-next-line @typescript-eslint/no-explicit-any obj: any ): obj is LangChainConfig { if (typeof obj !== "object") { console.error("LangChain config file is not an object"); return false; } if ( !("entrypoints" in obj) || !("tsConfigPath" in obj) || !("cjsSource" in obj) || !("cjsDestination" in obj) || !("abs" in obj) ) { console.error( `LangChain config file is missing required fields. One of: entrypoints, tsConfigPath, cjsSource, cjsDestination, abs` ); return false; } if (typeof obj.entrypoints !== "object") { console.error( "entrypoints field in LangChain config file is not an object" ); return false; } if (Object.values(obj.entrypoints).some((v) => typeof v !== "string")) { console.error( "entrypoints field in LangChain config file is not an object of strings" ); return false; } if ( typeof obj.tsConfigPath !== "string" || typeof obj.cjsSource !== "string" || typeof obj.cjsDestination !== "string" ) { console.error( "tsConfigPath, cjsSource, or cjsDestination fields in LangChain config file are not strings" ); return false; } if (typeof obj.abs !== "function") { console.error("abs field in LangChain config file is not a function"); return false; } // Optional fields if ( "requiresOptionalDependency" in obj && (!Array.isArray(obj.requiresOptionalDependency) || // eslint-disable-next-line @typescript-eslint/no-explicit-any obj.requiresOptionalDependency.some((v: any) => typeof v !== "string")) ) { console.error( "requiresOptionalDependency field in LangChain config file is not an array of strings" ); return false; } if ( "deprecatedNodeOnly" in obj && (!Array.isArray(obj.deprecatedNodeOnly) || // eslint-disable-next-line @typescript-eslint/no-explicit-any obj.deprecatedNodeOnly.some((v: any) => typeof v !== "string")) ) { console.error( "deprecatedNodeOnly field in LangChain config file is not an array of strings" ); return false; } if ( "deprecatedOmitFromImportMap" in obj && (!Array.isArray(obj.deprecatedOmitFromImportMap) || // eslint-disable-next-line @typescript-eslint/no-explicit-any obj.deprecatedOmitFromImportMap.some((v: any) => typeof v !== "string")) ) { console.error( "deprecatedOmitFromImportMap field in LangChain config file is not an array of strings" ); return false; } if ("packageSuffix" in obj && typeof obj.packageSuffix !== "string") { console.error( "packageSuffix field in LangChain config file is not a string" ); return false; } if ( "shouldTestExports" in obj && typeof obj.shouldTestExports !== "boolean" ) { console.error( "shouldTestExports field in LangChain config file is not a boolean" ); return false; } if ( "extraImportMapEntries" in obj && !Array.isArray(obj.extraImportMapEntries) ) { console.error( "extraImportMapEntries field in LangChain config file is not an array" ); return false; } if ( "gitignorePaths" in obj && (!Array.isArray(obj.gitignorePaths) || // eslint-disable-next-line @typescript-eslint/no-explicit-any obj.gitignorePaths.some((v: any) => typeof v !== "string")) ) { console.error( "gitignorePaths field in LangChain config file is not an array of strings" ); return false; } if ("internals" in obj && !Array.isArray(obj.internals)) { console.error("internals field in LangChain config file is not an array"); return false; } return true; }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src
lc_public_repos/langchainjs/libs/langchain-scripts/src/notebooks/check_notebook_type_errors.ts
import fs from "node:fs"; import ts from "typescript"; import { Project } from "ts-morph"; const SKIP_VALIDATION = ["lcel_cheatsheet.ipynb"]; export function extract(filepath: string) { const { cells } = JSON.parse(fs.readFileSync(filepath).toString()); if (cells[0]?.source.includes("lc_docs_skip_validation: true\n")) { return ""; } const project = new Project({ useInMemoryFileSystem: true }); const sourceFile = project.createSourceFile("temp.ts", ""); // eslint-disable-next-line @typescript-eslint/no-explicit-any cells.forEach((cell: Record<string, any>) => { const source = cell.source .join("") .replace(/\/\/ ?@lc-ts-ignore/g, "// @ts-ignore"); if (cell.cell_type === "code") { sourceFile.addStatements(source); } }); // Deduplicate imports const importDeclarations = sourceFile.getImportDeclarations(); const uniqueImports = new Map< string, { default?: string; namespace?: string; named: Set<string> } >(); importDeclarations.forEach((importDecl) => { const moduleSpecifier = importDecl.getModuleSpecifierValue(); if (!uniqueImports.has(moduleSpecifier)) { uniqueImports.set(moduleSpecifier, { named: new Set() }); } const defaultImport = importDecl.getDefaultImport(); if (defaultImport) { uniqueImports.get(moduleSpecifier)!.default = defaultImport.getText(); } const namespaceImport = importDecl.getNamespaceImport(); if (namespaceImport) { uniqueImports.get(moduleSpecifier)!.namespace = namespaceImport.getText(); } importDecl.getNamedImports().forEach((namedImport) => { uniqueImports.get(moduleSpecifier)!.named.add(namedImport.getText()); }); }); // Remove all existing imports importDeclarations.forEach((importDecl) => importDecl.remove()); // Add deduplicated imports at the top uniqueImports.forEach( ({ default: defaultImport, namespace, named }, moduleSpecifier) => { sourceFile.addImportDeclaration({ moduleSpecifier, defaultImport, namespaceImport: namespace, namedImports: Array.from(named), }); } ); return sourceFile.getFullText(); } const [pathname] = process.argv.slice(2); if (!pathname) { throw new Error("No pathname provided."); } export async function checkNotebookTypeErrors() { if (!pathname.endsWith(".ipynb")) { throw new Error("Only .ipynb files are supported."); } const notebookName = pathname.split("/")[pathname.split("/").length - 1]; if (SKIP_VALIDATION.includes(notebookName)) { return; } const filename = notebookName.replace(".ipynb", ".mts"); const tempFilepath = `./tmp/${filename}`; try { const typescriptSource = extract(pathname); if (!fs.existsSync("./tmp")) { fs.mkdirSync("./tmp"); } fs.writeFileSync(tempFilepath, typescriptSource); const program = ts.createProgram([tempFilepath], { module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext, target: ts.ScriptTarget.ES2021, alwaysStrict: true, skipLibCheck: true, }); const diagnostics = ts.getPreEmitDiagnostics(program); const issueStrings: string[] = []; if (diagnostics.length === 0) { console.log("No type errors found."); } else { diagnostics.forEach((diagnostic) => { if (diagnostic.file) { const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); const message = ts.flattenDiagnosticMessageText( diagnostic.messageText, "\n" ); issueStrings.push( `${diagnostic.file.fileName} (${line + 1},${ character + 1 }): ${message}` ); } else { issueStrings.push( ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n") ); } }); } if (issueStrings.length) { const issues = issueStrings.join("\n"); console.error(issues); const err = new Error("Found type errors in new notebook."); // eslint-disable-next-line @typescript-eslint/no-explicit-any (err as any).details = issues; throw err; } } finally { try { fs.rmSync(tempFilepath); } catch (e) { // Do nothing } } }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src
lc_public_repos/langchainjs/libs/langchain-scripts/src/notebooks/index.ts
import { checkNotebookTypeErrors } from "./check_notebook_type_errors.js"; import { checkUnexpectedRebuildError } from "./check_unexpected_rebuild_timer.js"; async function main() { await Promise.all([checkNotebookTypeErrors(), checkUnexpectedRebuildError()]); } try { void main(); } catch { process.exit(1); }
0
lc_public_repos/langchainjs/libs/langchain-scripts/src
lc_public_repos/langchainjs/libs/langchain-scripts/src/notebooks/check_unexpected_rebuild_timer.ts
import fs from "fs"; const [pathname] = process.argv.slice(2); if (!pathname) { throw new Error("No pathname provided."); } /** * tslab will sometimes throw an error inside the output cells of a notebook * if the notebook is being rebuilt. This function checks for that error, * because we do not want to commit that to our docs. */ export async function checkUnexpectedRebuildError() { if (!pathname.endsWith(".ipynb")) { throw new Error("Only .ipynb files are supported."); } const notebookContents = await fs.promises.readFile(pathname, "utf-8"); if ( notebookContents.includes( "UncaughtException: Error: Unexpected pending rebuildTimer" ) ) { throw new Error(`Found unexpected pending rebuildTimer in ${pathname}`); } }
0
lc_public_repos/langchainjs/libs/langchain-scripts
lc_public_repos/langchainjs/libs/langchain-scripts/bin/build.js
#!/usr/bin/env node import "../dist/build/index.js";
0
lc_public_repos/langchainjs/libs/langchain-scripts
lc_public_repos/langchainjs/libs/langchain-scripts/bin/validate_notebook.js
#!/usr/bin/env node import "../dist/notebooks/index.js";
0
lc_public_repos/langchainjs/libs/langchain-scripts
lc_public_repos/langchainjs/libs/langchain-scripts/bin/filter_spam_comment.js
#!/usr/bin/env node import "../dist/filter_spam_comment.js";
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/tsconfig.json
{ "extends": "@tsconfig/recommended", "compilerOptions": { "outDir": "../dist", "rootDir": "./src", "target": "ES2021", "lib": [ "ES2021", "ES2022.Object", "DOM" ], "module": "ES2020", "moduleResolution": "nodenext", "esModuleInterop": true, "declaration": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUnusedLocals": true, "noUnusedParameters": true, "useDefineForClassFields": true, "strictPropertyInitialization": false, "allowJs": true, "strict": true }, "include": [ "src/**/*" ], "exclude": [ "node_modules", "dist", "docs" ] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/LICENSE
The MIT License Copyright (c) Harrison Chase Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/jest.config.cjs
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: "ts-jest/presets/default-esm", testEnvironment: "./jest.env.cjs", modulePathIgnorePatterns: ["dist/", "docs/"], moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", }, transform: { '^.+\\.tsx?$': ['@swc/jest'], }, transformIgnorePatterns: [ "/node_modules/", "\\.pnp\\.[^\\/]+$", "./scripts/jest-setup-after-env.js", ], setupFiles: ["dotenv/config"], testTimeout: 20_000, passWithNoTests: true };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/babel.config.cjs
// babel.config.js module.exports = { presets: [["@babel/preset-env", { targets: { node: true } }]], };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/jest.env.cjs
const { TestEnvironment } = require("jest-environment-node"); class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment { constructor(config, context) { // Make `instanceof Float32Array` return true in tests // to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549 super(config, context); this.global.Float32Array = Float32Array; } } module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/README.md
# @langchain/anthropic This package contains the LangChain.js integrations for Anthropic through their SDK. ## Installation ```bash npm2yarn npm install @langchain/anthropic @langchain/core ``` This package, along with the main LangChain package, depends on [`@langchain/core`](https://npmjs.com/package/@langchain/core/). If you are using this package with other LangChain packages, you should make sure that all of the packages depend on the same instance of @langchain/core. You can do so by adding appropriate fields to your project's `package.json` like this: ```json { "name": "your-project", "version": "0.0.0", "dependencies": { "@langchain/anthropic": "^0.0.9", "@langchain/core": "^0.3.0" }, "resolutions": { "@langchain/core": "^0.3.0" }, "overrides": { "@langchain/core": "^0.3.0" }, "pnpm": { "overrides": { "@langchain/core": "^0.3.0" } } } ``` The field you need depends on the package manager you're using, but we recommend adding a field for the common `yarn`, `npm`, and `pnpm` to maximize compatibility. ## Chat Models This package contains the `ChatAnthropic` class, which is the recommended way to interface with the Anthropic series of models. To use, install the requirements, and configure your environment. ```bash export ANTHROPIC_API_KEY=your-api-key ``` Then initialize ```typescript import { ChatAnthropicMessages } from "@langchain/anthropic"; const model = new ChatAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const response = await model.invoke(new HumanMessage("Hello world!")); ``` ### Streaming ```typescript import { ChatAnthropicMessages } from "@langchain/anthropic"; const model = new ChatAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, model: "claude-3-sonnet-20240229", }); const response = await model.stream(new HumanMessage("Hello world!")); ``` ## Development To develop the Anthropic package, you'll need to follow these instructions: ### Install dependencies ```bash yarn install ``` ### Build the package ```bash yarn build ``` Or from the repo root: ```bash yarn build --filter=@langchain/anthropic ``` ### Run tests Test files should live within a `tests/` file in the `src/` folder. Unit tests should end in `.test.ts` and integration tests should end in `.int.test.ts`: ```bash $ yarn test $ yarn test:int ``` ### Lint & Format Run the linter & formatter to ensure your code is up to standard: ```bash yarn lint && yarn format ``` ### Adding new entrypoints If you add a new file to be exported, either import & re-export from `src/index.ts`, or add it to the `entrypoints` field in the `config` variable located inside `langchain.config.js` and run `yarn build` to generate the new entrypoint. ## Publishing After running `yarn build`, publish a new version with: ```bash $ npm publish ```
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/.release-it.json
{ "github": { "release": true, "autoGenerate": true, "tokenRef": "GITHUB_TOKEN_RELEASE" }, "npm": { "versionArgs": [ "--workspaces-update=false" ] } }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/.eslintrc.cjs
module.exports = { extends: [ "airbnb-base", "eslint:recommended", "prettier", "plugin:@typescript-eslint/recommended", ], parserOptions: { ecmaVersion: 12, parser: "@typescript-eslint/parser", project: "./tsconfig.json", sourceType: "module", }, plugins: ["@typescript-eslint", "no-instanceof", "eslint-plugin-jest"], ignorePatterns: [ "src/utils/@cfworker", "src/utils/fast-json-patch", "src/utils/js-sha1", ".eslintrc.cjs", "scripts", "node_modules", "dist", "dist-cjs", "*.js", "*.cjs", "*.d.ts", ], rules: { "no-process-env": 2, "no-instanceof/no-instanceof": 2, "@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/no-empty-function": 0, "@typescript-eslint/no-shadow": 0, "@typescript-eslint/no-empty-interface": 0, "@typescript-eslint/no-use-before-define": ["error", "nofunc"], "@typescript-eslint/no-unused-vars": ["warn", { args: "none" }], "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-misused-promises": "error", camelcase: 0, "class-methods-use-this": 0, "import/extensions": [2, "ignorePackages"], "import/no-extraneous-dependencies": [ "error", { devDependencies: ["**/*.test.ts"] }, ], "import/no-unresolved": 0, "import/prefer-default-export": 0, "keyword-spacing": "error", "max-classes-per-file": 0, "max-len": 0, "no-await-in-loop": 0, "no-bitwise": 0, "no-console": 0, "no-restricted-syntax": 0, "no-shadow": 0, "no-continue": 0, "no-void": 0, "no-underscore-dangle": 0, "no-use-before-define": 0, "no-useless-constructor": 0, "no-return-await": 0, "consistent-return": 0, "no-else-return": 0, "func-names": 0, "no-lonely-if": 0, "prefer-rest-params": 0, "new-cap": ["error", { properties: false, capIsNew: false }], 'jest/no-focused-tests': 'error', }, overrides: [ { files: ['**/*.test.ts'], rules: { '@typescript-eslint/no-unused-vars': 'off' } } ] };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/langchain.config.js
import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; /** * @param {string} relativePath * @returns {string} */ function abs(relativePath) { return resolve(dirname(fileURLToPath(import.meta.url)), relativePath); } export const config = { internals: [/node\:/, /@langchain\/core\//], entrypoints: { index: "index", experimental: "experimental/index", }, packageSuffix: "anthropic", tsConfigPath: resolve("./tsconfig.json"), cjsSource: "./dist-cjs", cjsDestination: "./dist", abs, }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/package.json
{ "name": "@langchain/anthropic", "version": "0.3.8", "description": "Anthropic integrations for LangChain.js", "type": "module", "engines": { "node": ">=18" }, "main": "./index.js", "types": "./index.d.ts", "repository": { "type": "git", "url": "git@github.com:langchain-ai/langchainjs.git" }, "homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-anthropic/", "scripts": { "build": "yarn turbo:command build:internal --filter=@langchain/anthropic", "build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking --gen-maps", "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/", "lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts", "lint": "yarn lint:eslint && yarn lint:dpdm", "lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm", "clean": "rm -rf .turbo dist/", "prepack": "yarn build", "test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%", "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts", "test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000", "test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%", "test:standard:unit": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.test.ts --testTimeout 100000 --maxWorkers=50%", "test:standard:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%", "test:standard": "yarn test:standard:unit && yarn test:standard:int", "format": "prettier --config .prettierrc --write \"src\"", "format:check": "prettier --config .prettierrc --check \"src\"" }, "author": "LangChain", "license": "MIT", "dependencies": { "@anthropic-ai/sdk": "^0.27.3", "fast-xml-parser": "^4.4.1", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.4" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" }, "devDependencies": { "@anthropic-ai/vertex-sdk": "^0.4.1", "@jest/globals": "^29.5.0", "@langchain/core": "workspace:*", "@langchain/scripts": ">=0.1.0 <0.2.0", "@langchain/standard-tests": "0.0.0", "@swc/core": "^1.3.90", "@swc/jest": "^0.2.29", "dpdm": "^3.12.0", "eslint": "^8.33.0", "eslint-config-airbnb-base": "^15.0.0", "eslint-config-prettier": "^8.6.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-jest": "^27.6.0", "eslint-plugin-no-instanceof": "^1.0.1", "eslint-plugin-prettier": "^4.2.1", "jest": "^29.5.0", "jest-environment-node": "^29.6.4", "prettier": "^2.8.3", "release-it": "^17.6.0", "rimraf": "^5.0.1", "ts-jest": "^29.1.0", "typescript": "~5.1.6" }, "publishConfig": { "access": "public" }, "keywords": [ "llm", "ai", "gpt3", "chain", "prompt", "prompt engineering", "chatgpt", "machine learning", "ml", "anthropic", "embeddings", "vectorstores" ], "exports": { ".": { "types": { "import": "./index.d.ts", "require": "./index.d.cts", "default": "./index.d.ts" }, "import": "./index.js", "require": "./index.cjs" }, "./experimental": { "types": { "import": "./experimental.d.ts", "require": "./experimental.d.cts", "default": "./experimental.d.ts" }, "import": "./experimental.js", "require": "./experimental.cjs" }, "./package.json": "./package.json" }, "files": [ "dist/", "index.cjs", "index.js", "index.d.ts", "index.d.cts", "experimental.cjs", "experimental.js", "experimental.d.ts", "experimental.d.cts" ] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/tsconfig.cjs.json
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "declaration": false }, "exclude": [ "node_modules", "dist", "docs", "**/tests" ] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/turbo.json
{ "extends": ["//"], "pipeline": { "build": { "outputs": ["**/dist/**"] }, "build:internal": { "dependsOn": ["^build:internal"] } } }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-anthropic/.prettierrc
{ "$schema": "https://json.schemastore.org/prettierrc", "printWidth": 80, "tabWidth": 2, "useTabs": false, "semi": true, "singleQuote": false, "quoteProps": "as-needed", "jsxSingleQuote": false, "trailingComma": "es5", "bracketSpacing": true, "arrowParens": "always", "requirePragma": false, "insertPragma": false, "proseWrap": "preserve", "htmlWhitespaceSensitivity": "css", "vueIndentScriptAndStyle": false, "endOfLine": "lf" }
0
lc_public_repos/langchainjs/libs/langchain-anthropic
lc_public_repos/langchainjs/libs/langchain-anthropic/src/output_parsers.ts
import { z } from "zod"; import { BaseLLMOutputParser, OutputParserException, } from "@langchain/core/output_parsers"; import { JsonOutputKeyToolsParserParams } from "@langchain/core/output_parsers/openai_tools"; import { ChatGeneration } from "@langchain/core/outputs"; import { ToolCall } from "@langchain/core/messages/tool"; // eslint-disable-next-line @typescript-eslint/no-explicit-any interface AnthropicToolsOutputParserParams<T extends Record<string, any>> extends JsonOutputKeyToolsParserParams<T> {} export class AnthropicToolsOutputParser< // eslint-disable-next-line @typescript-eslint/no-explicit-any T extends Record<string, any> = Record<string, any> > extends BaseLLMOutputParser<T> { static lc_name() { return "AnthropicToolsOutputParser"; } lc_namespace = ["langchain", "anthropic", "output_parsers"]; returnId = false; /** The type of tool calls to return. */ keyName: string; /** Whether to return only the first tool call. */ returnSingle = false; zodSchema?: z.ZodType<T>; constructor(params: AnthropicToolsOutputParserParams<T>) { super(params); this.keyName = params.keyName; this.returnSingle = params.returnSingle ?? this.returnSingle; this.zodSchema = params.zodSchema; } protected async _validateResult(result: unknown): Promise<T> { let parsedResult = result; if (typeof result === "string") { try { parsedResult = JSON.parse(result); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (e: any) { throw new OutputParserException( `Failed to parse. Text: "${JSON.stringify( result, null, 2 )}". Error: ${JSON.stringify(e.message)}`, result ); } } else { parsedResult = result; } if (this.zodSchema === undefined) { return parsedResult as T; } const zodParsedResult = await this.zodSchema.safeParseAsync(parsedResult); if (zodParsedResult.success) { return zodParsedResult.data; } else { throw new OutputParserException( `Failed to parse. Text: "${JSON.stringify( result, null, 2 )}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(parsedResult, null, 2) ); } } async parseResult(generations: ChatGeneration[]): Promise<T> { const tools = generations.flatMap((generation) => { const { message } = generation; if (!Array.isArray(message.content)) { return []; } const tool = extractToolCalls(message.content)[0]; return tool; }); if (tools[0] === undefined) { throw new Error( "No parseable tool calls provided to AnthropicToolsOutputParser." ); } const [tool] = tools; const validatedResult = await this._validateResult(tool.args); return validatedResult; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function extractToolCalls(content: Record<string, any>[]) { const toolCalls: ToolCall[] = []; for (const block of content) { if (block.type === "tool_use") { toolCalls.push({ name: block.name, args: block.input, id: block.id, type: "tool_call", }); } } return toolCalls; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic
lc_public_repos/langchainjs/libs/langchain-anthropic/src/types.ts
import Anthropic from "@anthropic-ai/sdk"; import type { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index.mjs"; import { BindToolsInput } from "@langchain/core/language_models/chat_models"; export type AnthropicToolResponse = { type: "tool_use"; id: string; name: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any input: Record<string, any>; }; export type AnthropicMessageParam = Anthropic.MessageParam; export type AnthropicMessageResponse = | Anthropic.ContentBlock | AnthropicToolResponse; export type AnthropicMessageCreateParams = Anthropic.MessageCreateParamsNonStreaming; export type AnthropicStreamingMessageCreateParams = Anthropic.MessageCreateParamsStreaming; export type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent; export type AnthropicRequestOptions = Anthropic.RequestOptions; export type AnthropicToolChoice = | { type: "tool"; name: string; } | "any" | "auto" | "none" | string; export type ChatAnthropicToolType = AnthropicTool | BindToolsInput;
0
lc_public_repos/langchainjs/libs/langchain-anthropic
lc_public_repos/langchainjs/libs/langchain-anthropic/src/index.ts
export * from "./chat_models.js"; export { convertPromptToAnthropic } from "./utils/prompts.js";
0
lc_public_repos/langchainjs/libs/langchain-anthropic
lc_public_repos/langchainjs/libs/langchain-anthropic/src/chat_models.ts
import { Anthropic, type ClientOptions } from "@anthropic-ai/sdk"; import type { Stream } from "@anthropic-ai/sdk/streaming"; import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager"; import { AIMessageChunk, type BaseMessage } from "@langchain/core/messages"; import { ChatGenerationChunk, type ChatResult } from "@langchain/core/outputs"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; import { BaseChatModel, BaseChatModelCallOptions, LangSmithParams, type BaseChatModelParams, } from "@langchain/core/language_models/chat_models"; import { type StructuredOutputMethodOptions, type BaseLanguageModelInput, isOpenAITool, } from "@langchain/core/language_models/base"; import { zodToJsonSchema } from "zod-to-json-schema"; import { BaseLLMOutputParser } from "@langchain/core/output_parsers"; import { Runnable, RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables"; import { isZodSchema } from "@langchain/core/utils/types"; import { z } from "zod"; import type { MessageCreateParams, Tool as AnthropicTool, } from "@anthropic-ai/sdk/resources/index.mjs"; import { isLangChainTool } from "@langchain/core/utils/function_calling"; import { AnthropicToolsOutputParser } from "./output_parsers.js"; import { handleToolChoice } from "./utils/tools.js"; import { _convertMessagesToAnthropicPayload } from "./utils/message_inputs.js"; import { _makeMessageChunkFromAnthropicEvent, anthropicResponseToChatMessages, } from "./utils/message_outputs.js"; import { AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicToolChoice, ChatAnthropicToolType, } from "./types.js"; import { wrapAnthropicClientError } from "./utils/errors.js"; export interface ChatAnthropicCallOptions extends BaseChatModelCallOptions, Pick<AnthropicInput, "streamUsage"> { tools?: ChatAnthropicToolType[]; /** * Whether or not to specify what tool the model should use * @default "auto" */ tool_choice?: AnthropicToolChoice; /** * Custom headers to pass to the Anthropic API * when making a request. */ headers?: Record<string, string>; } function _toolsInParams(params: AnthropicMessageCreateParams): boolean { return !!(params.tools && params.tools.length > 0); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function isAnthropicTool(tool: any): tool is AnthropicTool { return "input_schema" in tool; } /** * Input to AnthropicChat class. */ export interface AnthropicInput { /** Amount of randomness injected into the response. Ranges * from 0 to 1. Use temp closer to 0 for analytical / * multiple choice, and temp closer to 1 for creative * and generative tasks. */ temperature?: number; /** Only sample from the top K options for each subsequent * token. Used to remove "long tail" low probability * responses. Defaults to -1, which disables it. */ topK?: number; /** Does nucleus sampling, in which we compute the * cumulative distribution over all the options for each * subsequent token in decreasing probability order and * cut it off once it reaches a particular probability * specified by top_p. Defaults to -1, which disables it. * Note that you should either alter temperature or top_p, * but not both. */ topP?: number; /** A maximum number of tokens to generate before stopping. */ maxTokens?: number; /** * A maximum number of tokens to generate before stopping. * @deprecated Use "maxTokens" instead. */ maxTokensToSample?: number; /** A list of strings upon which to stop generating. * You probably want `["\n\nHuman:"]`, as that's the cue for * the next turn in the dialog agent. */ stopSequences?: string[]; /** Whether to stream the results or not */ streaming?: boolean; /** Anthropic API key */ anthropicApiKey?: string; /** Anthropic API key */ apiKey?: string; /** Anthropic API URL */ anthropicApiUrl?: string; /** @deprecated Use "model" instead */ modelName?: string; /** Model name to use */ model?: string; /** Overridable Anthropic ClientOptions */ clientOptions?: ClientOptions; /** Holds any additional parameters that are valid to pass to {@link * https://console.anthropic.com/docs/api/reference | * `anthropic.messages`} that are not explicitly specified on this class. */ invocationKwargs?: Kwargs; /** * Whether or not to include token usage data in streamed chunks. * @default true */ streamUsage?: boolean; /** * Optional method that returns an initialized underlying Anthropic client. * Useful for accessing Anthropic models hosted on other cloud services * such as Google Vertex. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any createClient?: (options: ClientOptions) => any; } /** * A type representing additional parameters that can be passed to the * Anthropic API. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any type Kwargs = Record<string, any>; function extractToken(chunk: AIMessageChunk): string | undefined { if (typeof chunk.content === "string") { return chunk.content; } else if ( Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0] ) { return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); } else if ( Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] ) { return chunk.content[0].text; } return undefined; } /** * Anthropic chat model integration. * * Setup: * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`. * * ```bash * npm install @langchain/anthropic * export ANTHROPIC_API_KEY="your-api-key" * ``` * * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor) * * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html) * * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: * * ```typescript * // When calling `.bind`, call options should be passed via the first argument * const llmWithArgsBound = llm.bind({ * stop: ["\n"], * tools: [...], * }); * * // When calling `.bindTools`, call options should be passed via the second argument * const llmWithTools = llm.bindTools( * [...], * { * tool_choice: "auto", * } * ); * ``` * * ## Examples * * <details open> * <summary><strong>Instantiate</strong></summary> * * ```typescript * import { ChatAnthropic } from '@langchain/anthropic'; * * const llm = new ChatAnthropic({ * model: "claude-3-5-sonnet-20240620", * temperature: 0, * maxTokens: undefined, * maxRetries: 2, * // apiKey: "...", * // baseUrl: "...", * // other params... * }); * ``` * </details> * * <br /> * * <details> * <summary><strong>Invoking</strong></summary> * * ```typescript * const input = `Translate "I love programming" into French.`; * * // Models also accept a list of chat messages or a formatted prompt * const result = await llm.invoke(input); * console.log(result); * ``` * * ```txt * AIMessage { * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", * "content": "Here's the translation to French:\n\nJ'adore la programmation.", * "response_metadata": { * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", * "model": "claude-3-5-sonnet-20240620", * "stop_reason": "end_turn", * "stop_sequence": null, * "usage": { * "input_tokens": 25, * "output_tokens": 19 * }, * "type": "message", * "role": "assistant" * }, * "usage_metadata": { * "input_tokens": 25, * "output_tokens": 19, * "total_tokens": 44 * } * } * ``` * </details> * * <br /> * * <details> * <summary><strong>Streaming Chunks</strong></summary> * * ```typescript * for await (const chunk of await llm.stream(input)) { * console.log(chunk); * } * ``` * * ```txt * AIMessageChunk { * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", * "content": "", * "additional_kwargs": { * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", * "type": "message", * "role": "assistant", * "model": "claude-3-5-sonnet-20240620" * }, * "usage_metadata": { * "input_tokens": 25, * "output_tokens": 1, * "total_tokens": 26 * } * } * AIMessageChunk { * "content": "", * } * AIMessageChunk { * "content": "Here", * } * AIMessageChunk { * "content": "'s", * } * AIMessageChunk { * "content": " the translation to", * } * AIMessageChunk { * "content": " French:\n\nJ", * } * AIMessageChunk { * "content": "'adore la programmation", * } * AIMessageChunk { * "content": ".", * } * AIMessageChunk { * "content": "", * "additional_kwargs": { * "stop_reason": "end_turn", * "stop_sequence": null * }, * "usage_metadata": { * "input_tokens": 0, * "output_tokens": 19, * "total_tokens": 19 * } * } * ``` * </details> * * <br /> * * <details> * <summary><strong>Aggregate Streamed Chunks</strong></summary> * * ```typescript * import { AIMessageChunk } from '@langchain/core/messages'; * import { concat } from '@langchain/core/utils/stream'; * * const stream = await llm.stream(input); * let full: AIMessageChunk | undefined; * for await (const chunk of stream) { * full = !full ? chunk : concat(full, chunk); * } * console.log(full); * ``` * * ```txt * AIMessageChunk { * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", * "content": "Here's the translation to French:\n\nJ'adore la programmation.", * "additional_kwargs": { * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", * "type": "message", * "role": "assistant", * "model": "claude-3-5-sonnet-20240620", * "stop_reason": "end_turn", * "stop_sequence": null * }, * "usage_metadata": { * "input_tokens": 25, * "output_tokens": 20, * "total_tokens": 45 * } * } * ``` * </details> * * <br /> * * <details> * <summary><strong>Bind tools</strong></summary> * * ```typescript * import { z } from 'zod'; * * const GetWeather = { * name: "GetWeather", * description: "Get the current weather in a given location", * schema: z.object({ * location: z.string().describe("The city and state, e.g. San Francisco, CA") * }), * } * * const GetPopulation = { * name: "GetPopulation", * description: "Get the current population in a given location", * schema: z.object({ * location: z.string().describe("The city and state, e.g. San Francisco, CA") * }), * } * * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); * const aiMsg = await llmWithTools.invoke( * "Which city is hotter today and which is bigger: LA or NY?" * ); * console.log(aiMsg.tool_calls); * ``` * * ```txt * [ * { * name: 'GetWeather', * args: { location: 'Los Angeles, CA' }, * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5', * type: 'tool_call' * }, * { * name: 'GetWeather', * args: { location: 'New York, NY' }, * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe', * type: 'tool_call' * }, * { * name: 'GetPopulation', * args: { location: 'Los Angeles, CA' }, * id: 'toolu_0165qYWBA2VFyUst5RA18zew', * type: 'tool_call' * }, * { * name: 'GetPopulation', * args: { location: 'New York, NY' }, * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo', * type: 'tool_call' * } * ] * ``` * </details> * * <br /> * * <details> * <summary><strong>Structured Output</strong></summary> * * ```typescript * import { z } from 'zod'; * * const Joke = z.object({ * setup: z.string().describe("The setup of the joke"), * punchline: z.string().describe("The punchline to the joke"), * rating: z.number().optional().describe("How funny the joke is, from 1 to 10") * }).describe('Joke to tell user.'); * * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); * console.log(jokeResult); * ``` * * ```txt * { * setup: "Why don't cats play poker in the jungle?", * punchline: 'Too many cheetahs!', * rating: 7 * } * ``` * </details> * * <br /> * * <details> * <summary><strong>Multimodal</strong></summary> * * ```typescript * import { HumanMessage } from '@langchain/core/messages'; * * const imageUrl = "https://example.com/image.jpg"; * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); * const base64Image = Buffer.from(imageData).toString('base64'); * * const message = new HumanMessage({ * content: [ * { type: "text", text: "describe the weather in this image" }, * { * type: "image_url", * image_url: { url: `data:image/jpeg;base64,${base64Image}` }, * }, * ] * }); * * const imageDescriptionAiMsg = await llm.invoke([message]); * console.log(imageDescriptionAiMsg.content); * ``` * * ```txt * The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth. * ``` * </details> * * <br /> * * <details> * <summary><strong>Usage Metadata</strong></summary> * * ```typescript * const aiMsgForMetadata = await llm.invoke(input); * console.log(aiMsgForMetadata.usage_metadata); * ``` * * ```txt * { input_tokens: 25, output_tokens: 19, total_tokens: 44 } * ``` * </details> * * <br /> * * <details> * <summary><strong>Stream Usage Metadata</strong></summary> * * ```typescript * const streamForMetadata = await llm.stream( * input, * { * streamUsage: true * } * ); * let fullForMetadata: AIMessageChunk | undefined; * for await (const chunk of streamForMetadata) { * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk); * } * console.log(fullForMetadata?.usage_metadata); * ``` * * ```txt * { input_tokens: 25, output_tokens: 20, total_tokens: 45 } * ``` * </details> * * <br /> * * <details> * <summary><strong>Response Metadata</strong></summary> * * ```typescript * const aiMsgForResponseMetadata = await llm.invoke(input); * console.log(aiMsgForResponseMetadata.response_metadata); * ``` * * ```txt * { * id: 'msg_01STxeQxJmp4sCSpioD6vK3L', * model: 'claude-3-5-sonnet-20240620', * stop_reason: 'end_turn', * stop_sequence: null, * usage: { input_tokens: 25, output_tokens: 19 }, * type: 'message', * role: 'assistant' * } * ``` * </details> * * <br /> */ export class ChatAnthropicMessages< CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions > extends BaseChatModel<CallOptions, AIMessageChunk> implements AnthropicInput { static lc_name() { return "ChatAnthropic"; } get lc_secrets(): { [key: string]: string } | undefined { return { anthropicApiKey: "ANTHROPIC_API_KEY", apiKey: "ANTHROPIC_API_KEY", }; } get lc_aliases(): Record<string, string> { return { modelName: "model", }; } lc_serializable = true; anthropicApiKey?: string; apiKey?: string; apiUrl?: string; temperature = 1; topK = -1; topP = -1; maxTokens = 2048; modelName = "claude-2.1"; model = "claude-2.1"; invocationKwargs?: Kwargs; stopSequences?: string[]; streaming = false; clientOptions: ClientOptions; // Used for non-streaming requests protected batchClient: Anthropic; // Used for streaming requests protected streamingClient: Anthropic; streamUsage = true; /** * Optional method that returns an initialized underlying Anthropic client. * Useful for accessing Anthropic models hosted on other cloud services * such as Google Vertex. */ createClient: (options: ClientOptions) => Anthropic; constructor(fields?: AnthropicInput & BaseChatModelParams) { super(fields ?? {}); this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); if (!this.anthropicApiKey && !fields?.createClient) { throw new Error("Anthropic API key not found"); } this.clientOptions = fields?.clientOptions ?? {}; /** Keep anthropicApiKey for backwards compatibility */ this.apiKey = this.anthropicApiKey; // Support overriding the default API URL (i.e., https://api.anthropic.com) this.apiUrl = fields?.anthropicApiUrl; /** Keep modelName for backwards compatibility */ this.modelName = fields?.model ?? fields?.modelName ?? this.model; this.model = this.modelName; this.invocationKwargs = fields?.invocationKwargs ?? {}; this.temperature = fields?.temperature ?? this.temperature; this.topK = fields?.topK ?? this.topK; this.topP = fields?.topP ?? this.topP; this.maxTokens = fields?.maxTokensToSample ?? fields?.maxTokens ?? this.maxTokens; this.stopSequences = fields?.stopSequences ?? this.stopSequences; this.streaming = fields?.streaming ?? false; this.streamUsage = fields?.streamUsage ?? this.streamUsage; this.createClient = fields?.createClient ?? ((options: ClientOptions) => new Anthropic(options)); } getLsParams(options: this["ParsedCallOptions"]): LangSmithParams { const params = this.invocationParams(options); return { ls_provider: "anthropic", ls_model_name: this.model, ls_model_type: "chat", ls_temperature: params.temperature ?? undefined, ls_max_tokens: params.max_tokens ?? undefined, ls_stop: options.stop, }; } /** * Formats LangChain StructuredTools to AnthropicTools. * * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed. */ formatStructuredToolToAnthropic( tools: ChatAnthropicCallOptions["tools"] ): AnthropicTool[] | undefined { if (!tools || !tools.length) { return undefined; } return tools.map((tool) => { if (isAnthropicTool(tool)) { return tool; } if (isOpenAITool(tool)) { return { name: tool.function.name, description: tool.function.description, input_schema: tool.function.parameters as AnthropicTool.InputSchema, }; } if (isLangChainTool(tool)) { return { name: tool.name, description: tool.description, input_schema: zodToJsonSchema( tool.schema ) as AnthropicTool.InputSchema, }; } throw new Error( `Unknown tool type passed to ChatAnthropic: ${JSON.stringify( tool, null, 2 )}` ); }); } override bindTools( tools: ChatAnthropicToolType[], kwargs?: Partial<CallOptions> ): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions> { return this.bind({ tools: this.formatStructuredToolToAnthropic(tools), ...kwargs, } as Partial<CallOptions>); } /** * Get the parameters used to invoke the model */ override invocationParams( options?: this["ParsedCallOptions"] ): Omit< AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams, "messages" > & Kwargs { const tool_choice: | MessageCreateParams.ToolChoiceAuto | MessageCreateParams.ToolChoiceAny | MessageCreateParams.ToolChoiceTool | undefined = handleToolChoice(options?.tool_choice); return { model: this.model, temperature: this.temperature, top_k: this.topK, top_p: this.topP, stop_sequences: options?.stop ?? this.stopSequences, stream: this.streaming, max_tokens: this.maxTokens, tools: this.formatStructuredToolToAnthropic(options?.tools), tool_choice, ...this.invocationKwargs, }; } /** @ignore */ _identifyingParams() { return { model_name: this.model, ...this.invocationParams(), }; } /** * Get the identifying parameters for the model */ identifyingParams() { return { model_name: this.model, ...this.invocationParams(), }; } async *_streamResponseChunks( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): AsyncGenerator<ChatGenerationChunk> { const params = this.invocationParams(options); const formattedMessages = _convertMessagesToAnthropicPayload(messages); const coerceContentToString = !_toolsInParams({ ...params, ...formattedMessages, stream: false, }); const stream = await this.createStreamWithRetry( { ...params, ...formattedMessages, stream: true, }, { headers: options.headers, } ); for await (const data of stream) { if (options.signal?.aborted) { stream.controller.abort(); throw new Error("AbortError: User aborted the request."); } const shouldStreamUsage = this.streamUsage ?? options.streamUsage; const result = _makeMessageChunkFromAnthropicEvent(data, { streamUsage: shouldStreamUsage, coerceContentToString, }); if (!result) continue; const { chunk } = result; // Extract the text content token for text field and runManager. const token = extractToken(chunk); const generationChunk = new ChatGenerationChunk({ message: new AIMessageChunk({ // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached(). content: chunk.content, additional_kwargs: chunk.additional_kwargs, tool_call_chunks: chunk.tool_call_chunks, usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined, response_metadata: chunk.response_metadata, id: chunk.id, }), text: token ?? "", }); yield generationChunk; await runManager?.handleLLMNewToken( token ?? "", undefined, undefined, undefined, undefined, { chunk: generationChunk } ); } } /** @ignore */ async _generateNonStreaming( messages: BaseMessage[], params: Omit< | Anthropic.Messages.MessageCreateParamsNonStreaming | Anthropic.Messages.MessageCreateParamsStreaming, "messages" > & Kwargs, requestOptions: AnthropicRequestOptions ) { const response = await this.completionWithRetry( { ...params, stream: false, ..._convertMessagesToAnthropicPayload(messages), }, requestOptions ); const { content, ...additionalKwargs } = response; const generations = anthropicResponseToChatMessages( content, additionalKwargs ); // eslint-disable-next-line @typescript-eslint/no-unused-vars const { role: _role, type: _type, ...rest } = additionalKwargs; return { generations, llmOutput: rest }; } /** @ignore */ async _generate( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): Promise<ChatResult> { if (this.stopSequences && options.stop) { throw new Error( `"stopSequence" parameter found in input and default params` ); } const params = this.invocationParams(options); if (params.stream) { let finalChunk: ChatGenerationChunk | undefined; const stream = this._streamResponseChunks(messages, options, runManager); for await (const chunk of stream) { if (finalChunk === undefined) { finalChunk = chunk; } else { finalChunk = finalChunk.concat(chunk); } } if (finalChunk === undefined) { throw new Error("No chunks returned from Anthropic API."); } return { generations: [ { text: finalChunk.text, message: finalChunk.message, }, ], }; } else { return this._generateNonStreaming(messages, params, { signal: options.signal, headers: options.headers, }); } } /** * Creates a streaming request with retry. * @param request The parameters for creating a completion. * @param options * @returns A streaming request. */ protected async createStreamWithRetry( request: AnthropicStreamingMessageCreateParams & Kwargs, options?: AnthropicRequestOptions ): Promise<Stream<AnthropicMessageStreamEvent>> { if (!this.streamingClient) { const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined; this.streamingClient = this.createClient({ dangerouslyAllowBrowser: true, ...this.clientOptions, ...options_, apiKey: this.apiKey, // Prefer LangChain built-in retries maxRetries: 0, }); } const makeCompletionRequest = async () => { try { return await this.streamingClient.messages.create( { ...request, ...this.invocationKwargs, stream: true, } as AnthropicStreamingMessageCreateParams, options ); } catch (e) { const error = wrapAnthropicClientError(e); throw error; } }; return this.caller.call(makeCompletionRequest); } /** @ignore */ protected async completionWithRetry( request: AnthropicMessageCreateParams & Kwargs, options: AnthropicRequestOptions ): Promise<Anthropic.Message> { if (!this.batchClient) { const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined; this.batchClient = this.createClient({ dangerouslyAllowBrowser: true, ...this.clientOptions, ...options, apiKey: this.apiKey, maxRetries: 0, }); } const makeCompletionRequest = async () => { try { return await this.batchClient.messages.create( { ...request, ...this.invocationKwargs, } as AnthropicMessageCreateParams, options ); } catch (e) { const error = wrapAnthropicClientError(e); throw error; } }; return this.caller.callWithOptions( { signal: options.signal ?? undefined }, makeCompletionRequest ); } _llmType() { return "anthropic"; } withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<false> ): Runnable<BaseLanguageModelInput, RunOutput>; withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<true> ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>; withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<boolean> ): | Runnable<BaseLanguageModelInput, RunOutput> | Runnable< BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput } > { // eslint-disable-next-line @typescript-eslint/no-explicit-any const schema: z.ZodType<RunOutput> | Record<string, any> = outputSchema; const name = config?.name; const method = config?.method; const includeRaw = config?.includeRaw; if (method === "jsonMode") { throw new Error(`Anthropic only supports "functionCalling" as a method.`); } let functionName = name ?? "extract"; let outputParser: BaseLLMOutputParser<RunOutput>; let tools: AnthropicTool[]; if (isZodSchema(schema)) { const jsonSchema = zodToJsonSchema(schema); tools = [ { name: functionName, description: jsonSchema.description ?? "A function available to call.", input_schema: jsonSchema as AnthropicTool.InputSchema, }, ]; outputParser = new AnthropicToolsOutputParser({ returnSingle: true, keyName: functionName, zodSchema: schema, }); } else { let anthropicTools: AnthropicTool; if ( typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null ) { anthropicTools = schema as AnthropicTool; functionName = schema.name; } else { anthropicTools = { name: functionName, description: schema.description ?? "", input_schema: schema as AnthropicTool.InputSchema, }; } tools = [anthropicTools]; outputParser = new AnthropicToolsOutputParser<RunOutput>({ returnSingle: true, keyName: functionName, }); } const llm = this.bind({ tools, tool_choice: { type: "tool", name: functionName, }, } as Partial<CallOptions>); if (!includeRaw) { return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput", }) as Runnable<BaseLanguageModelInput, RunOutput>; } const parserAssign = RunnablePassthrough.assign({ // eslint-disable-next-line @typescript-eslint/no-explicit-any parsed: (input: any, config) => outputParser.invoke(input.raw, config), }); const parserNone = RunnablePassthrough.assign({ parsed: () => null, }); const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone], }); return RunnableSequence.from< BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput } >([ { raw: llm, }, parsedWithFallback, ]).withConfig({ runName: "StructuredOutputRunnable", }); } } export class ChatAnthropic extends ChatAnthropicMessages {}
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/serializable.ts
export * from "@langchain/core/load/serializable";
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/import_constants.ts
// Auto-generated by `scripts/create-entrypoints.js`. Do not edit manually. export const optionalImportEntrypoints: string[] = [];
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/map_keys.ts
export interface SerializedFields { // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/import_type.ts
// Auto-generated by `scripts/create-entrypoints.js`. Do not edit manually. export interface OptionalImportMap {} export interface SecretMap { ANTHROPIC_API_KEY?: string; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/import_map.ts
// Auto-generated by build script. Do not edit manually. export * as index from "../index.js"; export * as experimental from "../experimental/index.js";
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/load/index.ts
import { load as coreLoad } from "@langchain/core/load"; import { type OptionalImportMap, type SecretMap } from "./import_type.js"; import * as importMap from "./import_map.js"; import { optionalImportEntrypoints } from "./import_constants.js"; export { optionalImportEntrypoints, importMap, type OptionalImportMap, type SecretMap, }; /** * Load a LangChain module from a serialized text representation. * NOTE: This functionality is currently in beta. * Loaded classes may change independently of semver. * @param text Serialized text representation of the module. * @param secretsMap * @param optionalImportsMap * @returns A loaded instance of a LangChain module. */ export async function load<T>( text: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any secretsMap: Record<string, any> = {}, // eslint-disable-next-line @typescript-eslint/no-explicit-any optionalImportsMap: OptionalImportMap & Record<string, any> = {} ): Promise<T> { return coreLoad(text, { secretsMap, optionalImportsMap, optionalImportEntrypoints, importMap, }); }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/agent.int.test.ts
// import { test, expect } from "@jest/globals"; // import { ChatPromptTemplate } from "@langchain/core/prompts"; // import { TavilySearchResults } from "@langchain/community/tools/tavily_search"; // import { AgentExecutor, createToolCallingAgent } from "langchain/agents"; // import { ChatAnthropic } from "../index.js"; // const tools = [new TavilySearchResults({ maxResults: 1 })]; // TODO: This test breaks CI build due to dependencies. Figure out a way around it. test("createToolCallingAgent works", async () => { // const prompt = ChatPromptTemplate.fromMessages([ // ["system", "You are a helpful assistant"], // ["placeholder", "{chat_history}"], // ["human", "{input}"], // ["placeholder", "{agent_scratchpad}"], // ]); // const llm = new ChatAnthropic({ // modelName: "claude-3-sonnet-20240229", // temperature: 0, // }); // const agent = await createToolCallingAgent({ // llm, // tools, // prompt, // }); // const agentExecutor = new AgentExecutor({ // agent, // tools, // }); // const input = "what is the current weather in SF?"; // const result = await agentExecutor.invoke({ // input, // }); // console.log(result); // expect(result.input).toBe(input); // expect(typeof result.output).toBe("string"); // // Length greater than 10 because any less than that would warrant // // an investigation into why such a short generation was returned. // expect(result.output.length).toBeGreaterThan(10); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/prompts.int.test.ts
import Anthropic from "@anthropic-ai/sdk"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { convertPromptToAnthropic } from "../utils/prompts.js"; test("Convert hub prompt to Anthropic payload and invoke", async () => { const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a world class comedian"], ["human", "Tell me a joke about {topic}"], ]); const formattedPrompt = await prompt.invoke({ topic: "cats", }); const { system, messages } = convertPromptToAnthropic(formattedPrompt); const anthropicClient = new Anthropic(); const anthropicResponse = await anthropicClient.messages.create({ model: "claude-3-haiku-20240307", system, messages, max_tokens: 1024, stream: false, }); expect(anthropicResponse.content).toBeDefined(); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/chat_models.standard.int.test.ts
/* eslint-disable no-process-env */ import { test, expect } from "@jest/globals"; import { ChatModelIntegrationTests } from "@langchain/standard-tests"; import { AIMessageChunk } from "@langchain/core/messages"; import { ChatAnthropic, ChatAnthropicCallOptions } from "../chat_models.js"; class ChatAnthropicStandardIntegrationTests extends ChatModelIntegrationTests< ChatAnthropicCallOptions, AIMessageChunk > { constructor() { if (!process.env.ANTHROPIC_API_KEY) { throw new Error( "ANTHROPIC_API_KEY must be set to run standard integration tests." ); } super({ Cls: ChatAnthropic, chatModelHasToolCalling: true, chatModelHasStructuredOutput: true, supportsParallelToolCalls: true, constructorArgs: { model: "claude-3-haiku-20240307", }, }); } async testParallelToolCalling() { // Override constructor args to use a better model for this test. // I found that haiku struggles with parallel tool calling. const constructorArgsCopy = { ...this.constructorArgs }; this.constructorArgs = { ...this.constructorArgs, model: "claude-3-5-sonnet-20240620", }; await super.testParallelToolCalling(); this.constructorArgs = constructorArgsCopy; } } const testClass = new ChatAnthropicStandardIntegrationTests(); test("ChatAnthropicStandardIntegrationTests", async () => { const testResults = await testClass.runTests(); expect(testResults).toBe(true); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/chat_models.standard.test.ts
/* eslint-disable no-process-env */ import { test, expect } from "@jest/globals"; import { ChatModelUnitTests } from "@langchain/standard-tests"; import { AIMessageChunk } from "@langchain/core/messages"; import { ChatAnthropic, ChatAnthropicCallOptions } from "../chat_models.js"; class ChatAnthropicStandardUnitTests extends ChatModelUnitTests< ChatAnthropicCallOptions, AIMessageChunk > { constructor() { super({ Cls: ChatAnthropic, chatModelHasToolCalling: true, chatModelHasStructuredOutput: true, constructorArgs: {}, }); // This must be set so method like `.bindTools` or `.withStructuredOutput` // which we call after instantiating the model will work. // (constructor will throw if API key is not set) process.env.ANTHROPIC_API_KEY = "test"; } testChatModelInitApiKey() { // Unset the API key env var here so this test can properly check // the API key class arg. process.env.ANTHROPIC_API_KEY = ""; super.testChatModelInitApiKey(); // Re-set the API key env var here so other tests can run properly. process.env.ANTHROPIC_API_KEY = "test"; } } const testClass = new ChatAnthropicStandardUnitTests(); test("ChatAnthropicStandardUnitTests", () => { const testResults = testClass.runTests(); expect(testResults).toBe(true); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/chat_models.int.test.ts
/* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { expect, test } from "@jest/globals"; import { AIMessageChunk, HumanMessage, SystemMessage, } from "@langchain/core/messages"; import { ChatPromptValue } from "@langchain/core/prompt_values"; import { PromptTemplate, ChatPromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate, } from "@langchain/core/prompts"; import { CallbackManager } from "@langchain/core/callbacks/manager"; import { concat } from "@langchain/core/utils/stream"; import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"; import { ChatAnthropic } from "../chat_models.js"; test("Test ChatAnthropic", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const message = new HumanMessage("Hello!"); const res = await chat.invoke([message]); // console.log({ res }); expect(res.response_metadata.usage).toBeDefined(); }); test("Test ChatAnthropic with a bad API key throws appropriate error", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, apiKey: "bad", }); let error; try { const message = new HumanMessage("Hello!"); await chat.invoke([message]); } catch (e) { error = e; } expect(error).toBeDefined(); expect((error as any).lc_error_code).toEqual("MODEL_AUTHENTICATION"); }); test("Test ChatAnthropic with unknown model throws appropriate error", async () => { const chat = new ChatAnthropic({ modelName: "badbad", maxRetries: 0, }); let error; try { const message = new HumanMessage("Hello!"); await chat.invoke([message]); } catch (e) { error = e; } expect(error).toBeDefined(); expect((error as any).lc_error_code).toEqual("MODEL_NOT_FOUND"); }); test("Test ChatAnthropic Generate", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const message = new HumanMessage("Hello!"); const res = await chat.generate([[message], [message]]); expect(res.generations.length).toBe(2); for (const generation of res.generations) { expect(generation.length).toBe(1); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var for (const message of generation) { // console.log(message.text); } } // console.log({ res }); }); test.skip("Test ChatAnthropic Generate w/ ClientOptions", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, clientOptions: { defaultHeaders: { "Helicone-Auth": "HELICONE_API_KEY", }, }, }); const message = new HumanMessage("Hello!"); const res = await chat.generate([[message], [message]]); expect(res.generations.length).toBe(2); for (const generation of res.generations) { expect(generation.length).toBe(1); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var for (const message of generation) { // console.log(message.text); } } // console.log({ res }); }); test("Test ChatAnthropic Generate with a signal in call options", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const controller = new AbortController(); const message = new HumanMessage( "How is your day going? Be extremely verbose!" ); await expect(() => { const res = chat.generate([[message], [message]], { signal: controller.signal, }); setTimeout(() => { controller.abort(); }, 1000); return res; }).rejects.toThrow(); }, 10000); test("Test ChatAnthropic tokenUsage with a batch", async () => { const model = new ChatAnthropic({ temperature: 0, maxRetries: 0, modelName: "claude-3-sonnet-20240229", }); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const res = await model.generate([ [new HumanMessage(`Hello!`)], [new HumanMessage(`Hi!`)], ]); // console.log({ res }); }); test("Test ChatAnthropic in streaming mode", async () => { let nrNewTokens = 0; let streamedCompletion = ""; const model = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, streaming: true, callbacks: CallbackManager.fromHandlers({ async handleLLMNewToken(token: string) { nrNewTokens += 1; streamedCompletion += token; }, }), }); const message = new HumanMessage("Hello!"); const res = await model.invoke([message]); // console.log({ res }); expect(nrNewTokens > 0).toBe(true); expect(res.content).toBe(streamedCompletion); }); test("Test ChatAnthropic in streaming mode with a signal", async () => { let nrNewTokens = 0; let streamedCompletion = ""; const model = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, streaming: true, callbacks: CallbackManager.fromHandlers({ async handleLLMNewToken(token: string) { nrNewTokens += 1; streamedCompletion += token; }, }), }); const controller = new AbortController(); const message = new HumanMessage( "Hello! Give me an extremely verbose response" ); await expect(() => { const res = model.invoke([message], { signal: controller.signal, }); setTimeout(() => { controller.abort(); }, 500); return res; }).rejects.toThrow(); // console.log({ nrNewTokens, streamedCompletion }); }, 5000); test.skip("Test ChatAnthropic prompt value", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const message = new HumanMessage("Hello!"); const res = await chat.generatePrompt([new ChatPromptValue([message])]); expect(res.generations.length).toBe(1); for (const generation of res.generations) { // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var for (const g of generation) { // console.log(g.text); } } // console.log({ res }); }); test.skip("ChatAnthropic, docs, prompt templates", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, temperature: 0, }); const systemPrompt = PromptTemplate.fromTemplate( "You are a helpful assistant that translates {input_language} to {output_language}." ); const chatPrompt = ChatPromptTemplate.fromMessages([ new SystemMessagePromptTemplate(systemPrompt), HumanMessagePromptTemplate.fromTemplate("{text}"), ]); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const responseA = await chat.generatePrompt([ await chatPrompt.formatPromptValue({ input_language: "English", output_language: "French", text: "I love programming.", }), ]); // console.log(responseA.generations); }); test.skip("ChatAnthropic, longer chain of messages", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, temperature: 0, }); const chatPrompt = ChatPromptTemplate.fromMessages([ HumanMessagePromptTemplate.fromTemplate(`Hi, my name is Joe!`), AIMessagePromptTemplate.fromTemplate(`Nice to meet you, Joe!`), HumanMessagePromptTemplate.fromTemplate("{text}"), ]); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const responseA = await chat.generatePrompt([ await chatPrompt.formatPromptValue({ text: "What did I just say my name was?", }), ]); // console.log(responseA.generations); }); test.skip("ChatAnthropic, Anthropic apiUrl set manually via constructor", async () => { // Pass the default URL through (should use this, and work as normal) const anthropicApiUrl = "https://api.anthropic.com"; const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, anthropicApiUrl, }); const message = new HumanMessage("Hello!"); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const res = await chat.call([message]); // console.log({ res }); }); test("Test ChatAnthropic stream method", async () => { const model = new ChatAnthropic({ maxTokens: 50, maxRetries: 0, modelName: "claude-3-sonnet-20240229", }); const stream = await model.stream("Print hello world."); const chunks = []; for await (const chunk of stream) { chunks.push(chunk); } expect(chunks.length).toBeGreaterThan(1); }); test("Test ChatAnthropic stream method with abort", async () => { await expect(async () => { const model = new ChatAnthropic({ maxTokens: 500, maxRetries: 0, modelName: "claude-3-sonnet-20240229", }); const stream = await model.stream( "How is your day going? Be extremely verbose.", { signal: AbortSignal.timeout(1000), } ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var for await (const chunk of stream) { // console.log(chunk); } }).rejects.toThrow(); }); test("Test ChatAnthropic stream method with early break", async () => { const model = new ChatAnthropic({ maxTokens: 50, maxRetries: 0, modelName: "claude-3-sonnet-20240229", }); const stream = await model.stream( "How is your day going? Be extremely verbose." ); let i = 0; // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var for await (const chunk of stream) { // console.log(chunk); i += 1; if (i > 10) { break; } } }); test("Test ChatAnthropic headers passed through", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, apiKey: "NOT_REAL", clientOptions: { defaultHeaders: { "X-Api-Key": process.env.ANTHROPIC_API_KEY, }, }, }); const message = new HumanMessage("Hello!"); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const res = await chat.invoke([message]); // console.log({ res }); }); test("Test ChatAnthropic multimodal", async () => { const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const res = await chat.invoke([ new HumanMessage({ content: [ { type: "image_url", image_url: { url: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMCAggHCQgGCQgICAcICAgICAgICAYICAgHDAgHCAgICAgIBggICAgICAgICBYICAgICwkKCAgNDQoIDggICQgBAwQEBgUGCgYGCBALCg0QCg0NEA0KCg8LDQoKCgoLDgoQDQoLDQoKCg4NDQ0NDgsQDw0OCg4NDQ4NDQoJDg8OCP/AABEIALAAsAMBEQACEQEDEQH/xAAdAAEAAgEFAQAAAAAAAAAAAAAABwgJAQIEBQYD/8QANBAAAgIBAwIDBwQCAgIDAAAAAQIAAwQFERIIEwYhMQcUFyJVldQjQVGBcZEJMzJiFRYk/8QAGwEBAAMAAwEAAAAAAAAAAAAAAAQFBgEDBwL/xAA5EQACAQIDBQQJBAIBBQAAAAAAAQIDEQQhMQVBUWGREhRxgRMVIjJSU8HR8CNyobFCguEGJGKi4v/aAAwDAQACEQMRAD8ApfJplBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBANl16qOTEKB6kkAD+z5Tkcj0On+z7Ub1FlOmanejeavj6dqV6kfsQ1OK4IP8AIM6pVYR1kuqJdLCV6qvCnJ/6v66nL+Ems/RNc+y63+BOvvFL411O/wBW4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6D4Saz9E1z7Lrf4Ed4pfGuo9W4r5T6HE1D2e6lQpsu0zU6EXzZ8jTtSoUD9yWuxUAA/kmdkasJaSXVHRVwlekrzpyX+r+mh56m9WHJSGU+hUgg/wBjynaRORvnAEAQBAEAQBAEAQCbennpVzfER95LHE0tX4tlsnJr2B2srw6yQLCpBQ3Me1W+4/VZLKlh4jFRo5ay4cPH7f0XWA2XUxft37MONs34ffRcy/Xsu6bdG0UK2Nh1tkAbHMyAt+Wx2HIi11/SDcQe3jrTXv6IJRVcRUqe88uC0Nxhdn0MMv0458XnJ+e7wVlyJPJkYsTSAIAgCAIAgCAIBqDAIx9qHTbo2tBmycOtcgjYZmOBRlqdjxJtQDuhdye3ette/qhkmliKlP3XlwehXYrZ9DEr9SOfFZS6rXwd1yKCdQ3Srm+HT7yGOXpbPxXLVOLUMTtXXmVgkVliQgvU9qx9h+kz11Ne4fFRrZaS4cfD7f2YfH7LqYT279qHHevH76PlvhKTClEAQBAEAQBAJp6WOn0+I80i7mumYnF8x1LIbSSe3iV2DYq13ElnQ8q6gdijWUuIeKxHoY5e89PuXWy8D3qp7S9iOvN/D9+XiZRNN06uiuvHqrSqmpFrqqrVUrrrUBUREUBVVVAAUAAATNNtu7PR4xUUoxVkskloktxyCZwfRj26jetHPtzrMXSM4Uabj7Vrfj10O2ZdsDbb3bqrCKEYmpeyED8Hs53LZVwvsPg4qN6kbt+OS8t5hdobYqOo44edorK6SzfmtFpz14H16f8Arkz6cmrD1e9crBvsFZy3ropvxC2yo7NTXXXbjhtuXcTmisz91hX2yr4KLjemrNbuPXeMDtuoqihiGnF/5ZJx55ZNceF76GQSUJuhAEAQBAEAhb239WWl+H391s7mXnbAnExu2WqUjdWyLHda6Qw2IXdrCCGFZX5pMo4WdXNZLiyoxm1KOFfZl7UuCtdeN2kvzcRB4d/5JMV7OOVpWRRSWAFmPk1ZTKN9uT1PRi+QHnsj2H12DHYGXLZzS9mV3zVvuVFL/qGDlapSaXFST6qyfS/3tb4M8a4up49WoYlyZGLcCUsTf1B2ZGVgHrsRgVNbqrIwIYAjaVc4Sg+zJWZqaVWFWCnB3T0/PodnqOnV312Y9taW02o1dtViq9dlbAq6OjAqyspIKkEEGfKbTuj7lFSTjJXTyaejXAxd9U/T6fDmYBTzbTMvm+G7FnNRBHcxLLDuWankCrueVlRG5dq7nOlwuI9NHP3lr9zzjamA7rU9n3Jacn8P25eBC0mFKIAgCAIBtdwASfQDc/4nIbsZXulr2ZDR9HwsYpxybqxmZe4Xl71cquyMR69hO3jg+fy0r5n1OWxNX0lRvdovBflz1DZuG7vh4xtZtXl+55vpp5EsyKWZ5X2seH783TdRwsZgmVk4OVRQzMUUXPRYle7gEoCxA5gEqDvsdp2U5KM03omv7I+Ig6lKUIuzaaXmigPtb6HNQ0bEytTGXjZeLiKlhWuu6rINPMLbY1bFqkXHQ908b7CyK+wUqFe+pY2FSSjZpvnl+MwmJ2JVw9OVTtqUYq+Sadt+WaVtd9+W+uLLv5HzB8j/AIlgZ8yRdGfUXXq2JXpGTZtquFUE+cnfMxU2Wu9CzEvaicEsG+/MdzYLbsmexmHdOXaS9l/w+H2PQ9kY9V6apyftxVtdUtJc3x58iykrjQCAIAgFdurzqbPh+lMHFKHVspC6FuLLh427Icp0O4d2ZWREb5WZLGbktJrssMJhvSu8vdX8vh9zP7X2i8LBRp27b46Rj8Vt73JebyVnCfSz0jNqh/8AsGsrZZRcxuoxrms7ua7HmcvLYkOaXJ5Ctjvkb8n/AE+K3TcVi+x+nS6rdyX33eJTbL2S636+JTaeaTveTf8AlLlwjv35ZFmfHnSnoWo47Yo0/FxLOBWnJw8ejHuobb5GVqkUOqnY9qwOjDyI9CKyGKqwd+03ybdjS19mYarHs+jSe5pJNdP6KudBPiTIwNYz/D1jA1WJk91AWKLqGJctDWVg+QFlfdQtsGcVY+//AFgSzx0VKmqi5dJK/wCeZm9iVJ0sRPDye6WWdu1BpXWeV78M8uGd/wCURuCJuqX2YjWNHzMYJyyaKzmYm3Hl71SrOqKW8h307mOT5fLc3mPUSsNV9HUT3aPwf5crNpYbvGHlG2azj+5Zrrp5mKFHBAI9CNx/iak8vTubpwBAEAQDtPCekLk5WHiON0yczFx3H8pbkVVMP7VyJ8zfZi3wTfRHdRh26kI8ZRXk5IzREf6mPPXTSAIB1/iPQa8yjIwrVD05NFuPYrAFWrsrat1YHyIKsRsf2nMXZpo+ZR7UXF77rqYW2xHrJqsHG2smu1T6rapKWKf8OCP6mxvfNHj1nH2XqsnfW6yOVpGr241teVRY9ORS4sqtrPF67B6Mp/2NiCGBIIYMQeGlJWaujsp1JU5KcHZrQyZdK/U3X4ipONdwq1fGQNkVL5JkVbhfe8cE/wDgWKq1e5NFjKD8ttLPm8ThnSd17r0+35qej7N2hHFQs8prVfVcv6J4kIuBAKtdWnV8uj89I090fVeP/wCi8hXq05CvIcg26PmMpDCpgVqUrZaCGqrussLhPSe3P3f7/wCOf4s9tTaXd16On77/APXn48EU58OYl+RremrrRyHbJzdPbI9+LvZZjW21vUlgs5FMe4OqmshVrrscca9jtcSaVKXotydrcVr58zH04znioLFXd3G/a17L08E3u5vJEveGeobX/Cuq2YmttbbjX3NflUu7ZC1VW2OTlaZZuzDHrIbbGXZOFbV9qmwfLElh6Venelqsl4rc+fP6FtT2hicHiHDEu8W7u+ii8lKObtHL3fH/AC1tn1AdReJ4exVvJW/MyEJwcVWG9x2G1zkb8MVNwTbt83kqhmYCVVDDyqytot7/ADeanG46GFh2nm37q4/8c/qVr/4/fZ9k5Obm+J7+Xa430V2soVcrNuuW3LtT+RQUNZKjj3L2QHlRYqWOPqJRVJcvJJWRnth4epKpLE1FqnZ8XJ3b8MuG/LQvdKQ2ZqB/qAYXfFmkLjZWZiINkxszKx0H8JVkW1KP6VAJsIPtRT4pPqjyKtDsVJx4SkvJSdjq59HSIAgCAdp4T1dcbKw8tzsmNmYuQ5/hKsiq1j/SoTPma7UWuKa6o7qM+xUhLhKL8lJXM0RP+pjz100gCAIBjA6x/Y9ZpGq35KofcdSssy8ewA8Vvcl8rHJ3OzrazXAeQNVq8d+3Zx0mDrKpTS3rLy3P6HnG18I6FdzS9mWa/c9V9fPkQTJxRnf+AfHeRpOXj6pjHa/GsDhd+K2p6W0WHY/p31lqidiVDchsyqR8VIKpFxlo/wAv5EjD15UKiqw1X8revMy++DfFtOo4uNqNDcsfKprvrJ8iFZQeLD1Dod0KnzVlI/aZKcXCTi9UerUqkasFOLumk14M8T1L+0uzRdHzdRp8skKlGO2wPC+6xKUt2PkezzN3E7g8NtjvO7D01UqKL03+CzIe0MQ8Ph5VI66Lxbsv7Ks9D3ThTqG/iXOBvSvJsGHTae4L8lWDXZ2QzMzXMt7MoWzzNyW2PzPaYWeNxDj+nDLLPw4dPsZ7Y+CVb/ua3tO7tfitZPzyS5XJS6zOlu3XAmrYSh9Rpq7N2OzKozMYF3RUZyEXIqZ325lVtVyrMOFUjYPEql7MtP6f2J+1tmvE2qU/fWWusfo1/P8AVWfbjruoWabpFGrl/wD5Wq/UOyMhO3mV6QFxaU98BCuzW5dNxW2wcraqeZawku1pQjFVJOn7uWmna1y8uhmMdUqOhSjiPfTlr73o0rXfi1k96V7nq/YP0n6lr99OdqgysfS6qqKw2QbK8rKx6kWrHxcdG2toxlrUA3lU+Q71c3ta+rpr4qFJONOzlnpom9/N8vpkTMBsyriZKeITUEla+rSyUbapLyvzeZkT0fR6saqvFprSmilFrqqrUJXXWo2VEUABVUDbYSgbbd3qbyMVFWSskcucH0ag/wCoBhd8WauuTlZmWh3TIzMrIQ/yluRbap/tXBmwguzFLgkuiPIq0+3UnLjKT8nJ2Orn0dIgCAIBtdAQQfQjY/4nIauZXulr2nDWNHw8kvyyaKxh5e/Hl71SqozsF8h307eQB5fLcvkPQZbE0vR1Gt2q8H+WPUNm4nvGHjK92spfuWT66+ZLMilmIAgHm/aL4ExtVxL9PyaVvptRtkb1WwA9uyths1dqNsRYhDKf39Z905uElKLszor0YVoOE1dP86mH7R/DORdi5OeKz2sI4iZZIKtU+Q11dPJSvl+rS1ZBIKsyDY7krrXJKSjxvbyzPKY0ZuMprSNlLim21p4rPh1t6fA9ieq34Ka1RhW5OA7XKbMcC6ypq7DU/doT9cLyBPNK7ECglmT0nW60FLsN2fPnnroSI4KvKl6aMLxz0zeTavbW3hfy3Wq/4+fbVQKbPDd9wW7vWZGnK2wW2l17l9FTehsS0W5PA/M62uV5CqzhV4+i7+kS5Px4/T8z02wcXHsvDyed24+DzaXg7u3PLLSderP2f3arombi0KXyEFWVVWBu1jU2pc1SD93sqWxAP3dlkHC1FCqm9NOuRd7ToOvhpwjrk14xadv4K7dEPU5gYOI2iZ+RXiql1l2Hk2fJjtVae5ZVbaSUrsW42WB7O2jpYqg8k+exxuGnKXbgr8eOWXmUGxtpUqdP0FV9m12m9Gm72/8AFp8dfEmb22dZmlaXjv7nk42pag4K0U49q3U1t5fqZV1LFErTfl2g4st/8VCjnZXDo4Oc37ScVvv9L/iLXG7Xo0IfpyU57kndeLa0X8vRcq59OnsAzPFWY3iTVmezBa3uMbQOWo2qdhSibcUwa+IrPEBSq9pB/wBjV2GIrxoR9HT1/r/6M/s7A1MbU7ziHeN75/5tbuUF/Oml28h0oDfCAIBE/VL7TRo+j5uSr8cm6s4eJtx5e9XKyK6hvJuwncyCPP5aW8j6GVhqXpKiW7V+C/LFZtLE93w8pXzeUf3PJdNfIxQIgAAHoBsP8TUnl6VjdOAIAgCAIBNPSx1BHw5mE3c20zL4JmIoZjUQT28uusblmp5EMiDlZUTsHaulDDxWH9NHL3lp9i62Xj+61Pa9yWvJ/F9+XgZRNN1Ku+uvIqsS2m1FsqtrZXrsrYBkdHUlWVlIIYEggzNNNOzPR4yUkpRd081bRp7zkTg+jUQCH9Q8FeJjnNdVrmImmPx/QfTKXuqAVOXa2ZeTO5tAe29hWq1bpeS8lKdLs2cH2v3Zfn5kVjpYr0t1VXY4djNaaZ+OumWpGh9j2vaVi6pp+NVpep4+ouxQXY9ZzMnKybbGy8rVbNsHENdKMdiot2Raa0pbtjud/pac5RlK6a4PJJaJasivD4inCcIdmSle11m3JttyeStn/RJ/sG8A6no2LgaTaultiY+MwuuxmzUyDlFue4rek1XGxmd3yWspLvuwoTnskevONSTkr58bafm7dxJuDpVaNONOXZsln2b6+evjv4I6jVejTRLMp9TqTLw8xrRkV24eVZT7vkcuZtorKvUjM25KMj1+Z2RdzOxYuoo9l2a5rVcOJGnsnDubqxTjLVOMmrPilnG/k1yJxrXYAbkkADkdtyf5OwA3Pr5AD+APSQi5K7e1zod0nVrnzanu07KtZnuOMK3x7rWO7WPjuNlsY7sWoenmzMzB2YtLCljZ012XmuevUoMVsWhXk5puEnra1m+Nnl0tffmeY8Df8dum49iXZmZkZ4Q79gImJjv/AALQj23Mv/qt6BvRuQJU9lTaE5K0Vb+X9iNQ2BRg71JOfKyUemb/AJ/gtXhYSVIlNaLXVWqpXWiqqIigBURVACqoAAUAAASrbvmzTpJKy0PtByIBx9R1KuiuzItsSqmpGsttsZUrrrUFnd3YhVVVBJYkAATlJt2R8ykopyk7JZtvRJbzF31T9QR8R5gNPNdMxOSYaMGQ2kkdzLsrOxVruICo45V1AbhGsuQaXC4f0Mc/eev2PONqY7vVT2fcjpzfxfbl4kLSYUogCAIAgCAIBNvTz1VZvh0+7FTl6Wz8mxGfi1DE72WYdhBFZYkuaGHasfc/os9lrQ8RhY1s9JcePj9/7LrAbUnhPYt2ocN68Pto+W+/fsv6ktG1oKuNmVrkEbnDyCKMtTsOQFTkd0LuB3KGtr39HMoquHqU/eWXFaG4wu0KGJX6cs+DykvJ6+KuuZJxEjFiaQBAEAQBAEAQBANQIBGHtR6ktG0UMuTmVtkAbjDxyt+Wx2PEGpG/SDcSO5kNTXv6uJJpYepV91ZcXoV2K2hQwy/UlnwWcn5bvF2XMoL1DdVWb4iPuwU4mlq/JcRX5NewO9dmZYABYVIDilR2q32P6rJXat7h8LGjnrLjw8Pv/Rh8ftSpi/Yt2YcL5vx+2i5kJSYUogCAIAgCAIAgCAbLqFYcWAZT6hgCD/R8pyOZ6HT/AGg6lQorp1PU6EXyVMfUdSoUD9gFpykAA/gCdUqUJaxXREuli69JWhUkv9n9Tl/FvWfreufetb/PnX3el8C6Hf6yxXzX1Hxb1n63rn3rW/z47vS+BdB6yxXzX1Hxb1n63rn3rW/z47vS+BdB6yxXzX1Hxb1n63rn3rW/z47vS+BdB6yxXzX1Hxb1n63rn3rW/wA+O70vgXQessV819R8W9Z+t65961v8+O70vgXQessV819R8W9Z+t65961v8+O70vgXQessV819R8W9Z+t65961v8+O70vgXQessV819Tiah7QdRvU13anqd6N5MmRqOpXqR+4K3ZTgg/wROyNKEdIrojoqYuvVVp1JP/Z/TU89TQqjioCgegAAA/oeU7SJzN84AgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgCAIAgH/9k=", }, }, { type: "text", text: "What is this a logo for?" }, ], }), ]); // console.log(res); }); test("Stream tokens", async () => { const model = new ChatAnthropic({ model: "claude-3-haiku-20240307", temperature: 0, maxTokens: 10, }); let res: AIMessageChunk | null = null; for await (const chunk of await model.stream( "Why is the sky blue? Be concise." )) { if (!res) { res = chunk; } else { res = res.concat(chunk); } } // console.log(res); expect(res?.usage_metadata).toBeDefined(); if (!res?.usage_metadata) { return; } expect(res.usage_metadata.input_tokens).toBeGreaterThan(1); expect(res.usage_metadata.output_tokens).toBeGreaterThan(1); expect(res.usage_metadata.total_tokens).toBe( res.usage_metadata.input_tokens + res.usage_metadata.output_tokens ); }); test("id is supplied when invoking", async () => { const model = new ChatAnthropic(); const result = await model.invoke("Hello"); expect(result.id).toBeDefined(); expect(result.id).not.toEqual(""); }); test("id is supplied when streaming", async () => { const model = new ChatAnthropic(); let finalChunk: AIMessageChunk | undefined; for await (const chunk of await model.stream("Hello")) { finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk); } expect(finalChunk).toBeDefined(); if (!finalChunk) return; expect(finalChunk.id).toBeDefined(); expect(finalChunk.id).not.toEqual(""); }); const CACHED_TEXT = `## Components LangChain provides standard, extendable interfaces and external integrations for various components useful for building with LLMs. Some components LangChain implements, some components we rely on third-party integrations for, and others are a mix. ### Chat models <span data-heading-keywords="chat model,chat models"></span> Language models that use a sequence of messages as inputs and return chat messages as outputs (as opposed to using plain text). These are generally newer models (older models are generally \`LLMs\`, see below). Chat models support the assignment of distinct roles to conversation messages, helping to distinguish messages from the AI, users, and instructions such as system messages. Although the underlying models are messages in, message out, the LangChain wrappers also allow these models to take a string as input. This gives them the same interface as LLMs (and simpler to use). When a string is passed in as input, it will be converted to a \`HumanMessage\` under the hood before being passed to the underlying model. LangChain does not host any Chat Models, rather we rely on third party integrations. We have some standardized parameters when constructing ChatModels: - \`model\`: the name of the model Chat Models also accept other parameters that are specific to that integration. :::important Some chat models have been fine-tuned for **tool calling** and provide a dedicated API for it. Generally, such models are better at tool calling than non-fine-tuned models, and are recommended for use cases that require tool calling. Please see the [tool calling section](/docs/concepts/#functiontool-calling) for more information. ::: For specifics on how to use chat models, see the [relevant how-to guides here](/docs/how_to/#chat-models). #### Multimodality Some chat models are multimodal, accepting images, audio and even video as inputs. These are still less common, meaning model providers haven't standardized on the "best" way to define the API. Multimodal outputs are even less common. As such, we've kept our multimodal abstractions fairly light weight and plan to further solidify the multimodal APIs and interaction patterns as the field matures. In LangChain, most chat models that support multimodal inputs also accept those values in OpenAI's content blocks format. So far this is restricted to image inputs. For models like Gemini which support video and other bytes input, the APIs also support the native, model-specific representations. For specifics on how to use multimodal models, see the [relevant how-to guides here](/docs/how_to/#multimodal). ### LLMs <span data-heading-keywords="llm,llms"></span> :::caution Pure text-in/text-out LLMs tend to be older or lower-level. Many popular models are best used as [chat completion models](/docs/concepts/#chat-models), even for non-chat use cases. You are probably looking for [the section above instead](/docs/concepts/#chat-models). ::: Language models that takes a string as input and returns a string. These are traditionally older models (newer models generally are [Chat Models](/docs/concepts/#chat-models), see above). Although the underlying models are string in, string out, the LangChain wrappers also allow these models to take messages as input. This gives them the same interface as [Chat Models](/docs/concepts/#chat-models). When messages are passed in as input, they will be formatted into a string under the hood before being passed to the underlying model. LangChain does not host any LLMs, rather we rely on third party integrations. For specifics on how to use LLMs, see the [relevant how-to guides here](/docs/how_to/#llms). ### Message types Some language models take an array of messages as input and return a message. There are a few different types of messages. All messages have a \`role\`, \`content\`, and \`response_metadata\` property. The \`role\` describes WHO is saying the message. LangChain has different message classes for different roles. The \`content\` property describes the content of the message. This can be a few different things: - A string (most models deal this type of content) - A List of objects (this is used for multi-modal input, where the object contains information about that input type and that input location) #### HumanMessage This represents a message from the user. #### AIMessage This represents a message from the model. In addition to the \`content\` property, these messages also have: **\`response_metadata\`** The \`response_metadata\` property contains additional metadata about the response. The data here is often specific to each model provider. This is where information like log-probs and token usage may be stored. **\`tool_calls\`** These represent a decision from an language model to call a tool. They are included as part of an \`AIMessage\` output. They can be accessed from there with the \`.tool_calls\` property. This property returns a list of \`ToolCall\`s. A \`ToolCall\` is an object with the following arguments: - \`name\`: The name of the tool that should be called. - \`args\`: The arguments to that tool. - \`id\`: The id of that tool call. #### SystemMessage This represents a system message, which tells the model how to behave. Not every model provider supports this. #### ToolMessage This represents the result of a tool call. In addition to \`role\` and \`content\`, this message has: - a \`tool_call_id\` field which conveys the id of the call to the tool that was called to produce this result. - an \`artifact\` field which can be used to pass along arbitrary artifacts of the tool execution which are useful to track but which should not be sent to the model. #### (Legacy) FunctionMessage This is a legacy message type, corresponding to OpenAI's legacy function-calling API. \`ToolMessage\` should be used instead to correspond to the updated tool-calling API. This represents the result of a function call. In addition to \`role\` and \`content\`, this message has a \`name\` parameter which conveys the name of the function that was called to produce this result. ### Prompt templates <span data-heading-keywords="prompt,prompttemplate,chatprompttemplate"></span> Prompt templates help to translate user input and parameters into instructions for a language model. This can be used to guide a model's response, helping it understand the context and generate relevant and coherent language-based output. Prompt Templates take as input an object, where each key represents a variable in the prompt template to fill in. Prompt Templates output a PromptValue. This PromptValue can be passed to an LLM or a ChatModel, and can also be cast to a string or an array of messages. The reason this PromptValue exists is to make it easy to switch between strings and messages. There are a few different types of prompt templates: #### String PromptTemplates These prompt templates are used to format a single string, and generally are used for simpler inputs. For example, a common way to construct and use a PromptTemplate is as follows: \`\`\`typescript import { PromptTemplate } from "@langchain/core/prompts"; const promptTemplate = PromptTemplate.fromTemplate( "Tell me a joke about {topic}" ); await promptTemplate.invoke({ topic: "cats" }); \`\`\` #### ChatPromptTemplates These prompt templates are used to format an array of messages. These "templates" consist of an array of templates themselves. For example, a common way to construct and use a ChatPromptTemplate is as follows: \`\`\`typescript import { ChatPromptTemplate } from "@langchain/core/prompts"; const promptTemplate = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["user", "Tell me a joke about {topic}"], ]); await promptTemplate.invoke({ topic: "cats" }); \`\`\` In the above example, this ChatPromptTemplate will construct two messages when called. The first is a system message, that has no variables to format. The second is a HumanMessage, and will be formatted by the \`topic\` variable the user passes in. #### MessagesPlaceholder <span data-heading-keywords="messagesplaceholder"></span> This prompt template is responsible for adding an array of messages in a particular place. In the above ChatPromptTemplate, we saw how we could format two messages, each one a string. But what if we wanted the user to pass in an array of messages that we would slot into a particular spot? This is how you use MessagesPlaceholder. \`\`\`typescript import { ChatPromptTemplate, MessagesPlaceholder, } from "@langchain/core/prompts"; import { HumanMessage } from "@langchain/core/messages"; const promptTemplate = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], new MessagesPlaceholder("msgs"), ]); promptTemplate.invoke({ msgs: [new HumanMessage({ content: "hi!" })] }); \`\`\` This will produce an array of two messages, the first one being a system message, and the second one being the HumanMessage we passed in. If we had passed in 5 messages, then it would have produced 6 messages in total (the system message plus the 5 passed in). This is useful for letting an array of messages be slotted into a particular spot. An alternative way to accomplish the same thing without using the \`MessagesPlaceholder\` class explicitly is: \`\`\`typescript const promptTemplate = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["placeholder", "{msgs}"], // <-- This is the changed part ]); \`\`\` For specifics on how to use prompt templates, see the [relevant how-to guides here](/docs/how_to/#prompt-templates). ### Example Selectors One common prompting technique for achieving better performance is to include examples as part of the prompt. This gives the language model concrete examples of how it should behave. Sometimes these examples are hardcoded into the prompt, but for more advanced situations it may be nice to dynamically select them. Example Selectors are classes responsible for selecting and then formatting examples into prompts. For specifics on how to use example selectors, see the [relevant how-to guides here](/docs/how_to/#example-selectors). ### Output parsers <span data-heading-keywords="output parser"></span> :::note The information here refers to parsers that take a text output from a model try to parse it into a more structured representation. More and more models are supporting function (or tool) calling, which handles this automatically. It is recommended to use function/tool calling rather than output parsing. See documentation for that [here](/docs/concepts/#function-tool-calling). ::: Responsible for taking the output of a model and transforming it to a more suitable format for downstream tasks. Useful when you are using LLMs to generate structured data, or to normalize output from chat models and LLMs. There are two main methods an output parser must implement: - "Get format instructions": A method which returns a string containing instructions for how the output of a language model should be formatted. - "Parse": A method which takes in a string (assumed to be the response from a language model) and parses it into some structure. And then one optional one: - "Parse with prompt": A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Output parsers accept a string or \`BaseMessage\` as input and can return an arbitrary type. LangChain has many different types of output parsers. This is a list of output parsers LangChain supports. The table below has various pieces of information: **Name**: The name of the output parser **Supports Streaming**: Whether the output parser supports streaming. **Input Type**: Expected input type. Most output parsers work on both strings and messages, but some (like OpenAI Functions) need a message with specific arguments. **Output Type**: The output type of the object returned by the parser. **Description**: Our commentary on this output parser and when to use it. The current date is ${new Date().toISOString()}`; test("system prompt caching", async () => { const model = new ChatAnthropic({ model: "claude-3-haiku-20240307", clientOptions: { defaultHeaders: { "anthropic-beta": "prompt-caching-2024-07-31", }, }, }); const messages = [ new SystemMessage({ content: [ { type: "text", text: `You are a pirate. Always respond in pirate dialect.\nUse the following as context when answering questions: ${CACHED_TEXT}`, cache_control: { type: "ephemeral" }, }, ], }), new HumanMessage({ content: "What types of messages are supported in LangChain?", }), ]; const res = await model.invoke(messages); expect( res.response_metadata.usage.cache_creation_input_tokens ).toBeGreaterThan(0); expect(res.response_metadata.usage.cache_read_input_tokens).toBe(0); const res2 = await model.invoke(messages); expect(res2.response_metadata.usage.cache_creation_input_tokens).toBe(0); expect(res2.response_metadata.usage.cache_read_input_tokens).toBeGreaterThan( 0 ); }); // TODO: Add proper test with long tool content test.skip("tool caching", async () => { const model = new ChatAnthropic({ model: "claude-3-haiku-20240307", clientOptions: { defaultHeaders: { "anthropic-beta": "prompt-caching-2024-07-31", }, }, }).bindTools([ { name: "get_weather", description: "Get the weather for a specific location", input_schema: { type: "object", properties: { location: { type: "string", description: "Location to get the weather for", }, unit: { type: "string", description: "Temperature unit to return", }, }, required: ["location"], }, cache_control: { type: "ephemeral" }, }, ]); const messages = [ new HumanMessage({ content: "What is the weather in Regensburg?", }), ]; const res = await model.invoke(messages); console.log(res); expect( res.response_metadata.usage.cache_creation_input_tokens ).toBeGreaterThan(0); expect(res.response_metadata.usage.cache_read_input_tokens).toBe(0); const res2 = await model.invoke(messages); expect(res2.response_metadata.usage.cache_creation_input_tokens).toBe(0); expect(res2.response_metadata.usage.cache_read_input_tokens).toBeGreaterThan( 0 ); }); test.skip("Test ChatAnthropic with custom client", async () => { const client = new AnthropicVertex(); const chat = new ChatAnthropic({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, createClient: () => client, }); const message = new HumanMessage("Hello!"); const res = await chat.invoke([message]); // console.log({ res }); expect(res.response_metadata.usage).toBeDefined(); }); test("human message caching", async () => { const model = new ChatAnthropic({ model: "claude-3-haiku-20240307", clientOptions: { defaultHeaders: { "anthropic-beta": "prompt-caching-2024-07-31", }, }, }); const messages = [ new SystemMessage({ content: [ { type: "text", text: `You are a pirate. Always respond in pirate dialect.\nUse the following as context when answering questions: ${CACHED_TEXT}`, }, ], }), new HumanMessage({ content: [ { type: "text", text: "What types of messages are supported in LangChain?", cache_control: { type: "ephemeral" }, }, ], }), ]; const res = await model.invoke(messages); expect( res.response_metadata.usage.cache_creation_input_tokens ).toBeGreaterThan(0); expect(res.response_metadata.usage.cache_read_input_tokens).toBe(0); const res2 = await model.invoke(messages); expect(res2.response_metadata.usage.cache_creation_input_tokens).toBe(0); expect(res2.response_metadata.usage.cache_read_input_tokens).toBeGreaterThan( 0 ); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/chat_models-tools.int.test.ts
/* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { expect, test } from "@jest/globals"; import { AIMessage, AIMessageChunk, HumanMessage, ToolMessage, } from "@langchain/core/messages"; import { StructuredTool, tool } from "@langchain/core/tools"; import { concat } from "@langchain/core/utils/stream"; import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; import { RunnableLambda } from "@langchain/core/runnables"; import { ChatAnthropic } from "../chat_models.js"; import { AnthropicToolResponse } from "../types.js"; const zodSchema = z .object({ location: z.string().describe("The name of city to get the weather for."), }) .describe( "Get the weather of a specific location and return the temperature in Celsius." ); class WeatherTool extends StructuredTool { schema = z.object({ location: z.string().describe("The name of city to get the weather for."), }); description = "Get the weather of a specific location and return the temperature in Celsius."; name = "get_weather"; async _call(input: z.infer<typeof this.schema>) { return `The weather in ${input.location} is 25°C`; } } const model = new ChatAnthropic({ modelName: "claude-3-haiku-20240307", temperature: 0, }); const anthropicTool = { name: "get_weather", description: "Get the weather of a specific location and return the temperature in Celsius.", input_schema: { type: "object", properties: { location: { type: "string", description: "The name of city to get the weather for.", }, }, required: ["location"], }, }; test("Few shotting with tool calls", async () => { const chat = model.bindTools([new WeatherTool()]); const res = await chat.invoke([ new HumanMessage("What is the weather in SF?"), new AIMessage({ content: "Let me look up the current weather.", tool_calls: [ { id: "toolu_feiwjf9u98r389u498", name: "get_weather", args: { location: "SF", }, }, ], }), new ToolMessage({ tool_call_id: "toolu_feiwjf9u98r389u498", content: "It is currently 24 degrees with hail in San Francisco.", }), new AIMessage( "It is currently 24 degrees in San Francisco with hail in San Francisco." ), new HumanMessage("What did you say the weather was?"), ]); expect(res.content).toContain("24"); }); test("Multipart ToolMessage", async () => { const chat = model.bindTools([new WeatherTool()]); const res = await chat.invoke([ new HumanMessage("What is the weather in SF?"), new AIMessage({ content: "Let me look up the current weather.", tool_calls: [ { id: "toolu_feiwjf9u98r389u498", name: "get_weather", args: { location: "SF", }, }, ], }), new ToolMessage({ tool_call_id: "toolu_feiwjf9u98r389u498", content: [ { type: "text", text: "It is currently 24 degrees with hail in San Francisco.", }, { type: "image_url", image_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAA5QAAAOUBj+WbPAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAH0SURBVFiFzZcxSytBEMd/E+PL2aVNKomFpBP1K4iFvEIQrN6neGAZEUWw8xMIthZaSAR5rzPwGi0t9APIK0RBCxMsxiKzst7lLpszeA4Mt7c785//DLs7d6Kq5BURaQOo6kpujLwERKQCdO01UtVeHpxSrujGIWX8ZQTGIgkCItIQkZaI1McVRETqhtlILKrqBwV2AAVugXp8PWbbATpDbOqGpUArsT7E4QaoZYALtpFT1muGkZpQFmvneA2Us7JMwSibr0tkYDWzAGoG8ARUvfk5YA/4CzwC98A5sAs0Pbuq+V5nVjEgi6qNJ4Et4NWyGqRdYAOY8EhkVi+0nD+Af16gQ2ANmAZmgHXgyFv/A5SCsAMJbBvwf2A5w24VeDDb32MhAMx7ZV8KsF8z2xdgdhwE9g3wYIQTcGw+m8NsS9BvLCISOeWjLNjzhHBxtov+pB/DmhkAbZK7uUP/kikBzzaXepQGVKBpPnf2LoYZj9MuvBk5xhUgchrL5oI+258jVOCX+ZzG5iNPK+97QFV7qtp1GuN4Zc/VEfJytpexZLue9t4r8K2PoRZ9ERlwMVcxRTYjimzHFPlBQtGfZHyDj9IG0AoIHnmbLwog0QIa8bXP/JpF9C8bgClN3qBBUngz+gwBTRmPJOXc0VV7InLmxnlx3gDvLHwSZKNszAAAAABJRU5ErkJggg==", }, ], }), new AIMessage( "It is currently 24 degrees in San Francisco with hail in San Francisco." ), new HumanMessage("What did you say the weather was?"), ]); expect(res.content).toContain("24"); }); test("Invalid tool calls should throw an appropriate error", async () => { const chat = model.bindTools([new WeatherTool()]); let error; try { await chat.invoke([ new HumanMessage("What is the weather in SF?"), new AIMessage({ content: "Let me look up the current weather.", tool_calls: [ { id: "toolu_feiwjf9u98r389u498", name: "get_weather", args: { location: "SF", }, }, ], }), new ToolMessage({ tool_call_id: "badbadbad", content: "It is currently 24 degrees with hail in San Francisco.", }), ]); } catch (e) { error = e; } expect(error).toBeDefined(); expect((error as any).lc_error_code).toEqual("INVALID_TOOL_RESULTS"); }); test("Can bind & invoke StructuredTools", async () => { const tools = [new WeatherTool()]; const modelWithTools = model.bindTools(tools); const result = await modelWithTools.invoke( "What is the weather in SF today?" ); expect(Array.isArray(result.content)).toBeTruthy(); if (!Array.isArray(result.content)) { throw new Error("Content is not an array"); } let toolCall: AnthropicToolResponse | undefined; result.content.forEach((item) => { if (item.type === "tool_use") { toolCall = item as AnthropicToolResponse; } }); if (!toolCall) { throw new Error("No tool call found"); } expect(toolCall).toBeTruthy(); const { name, input } = toolCall; expect(input).toEqual(result.tool_calls?.[0].args); expect(name).toBe("get_weather"); expect(input).toBeTruthy(); expect(input.location).toBeTruthy(); const result2 = await modelWithTools.invoke([ new HumanMessage("What is the weather in SF today?"), result, new ToolMessage({ tool_call_id: result.tool_calls?.[0].id ?? "", content: "The weather in San Francisco is currently 59 degrees and sunny.", }), new AIMessage( "The weather in San Francisco is currently 59 degrees and sunny." ), new HumanMessage("What did you say the weather was?"), ]); // This should work, but Anthorpic is too skeptical expect(result2.content).toContain("59"); }); test("Can bind & invoke AnthropicTools", async () => { const modelWithTools = model.bind({ tools: [anthropicTool], }); const result = await modelWithTools.invoke( "What is the weather in London today?" ); expect(Array.isArray(result.content)).toBeTruthy(); if (!Array.isArray(result.content)) { throw new Error("Content is not an array"); } let toolCall: AnthropicToolResponse | undefined; result.content.forEach((item) => { if (item.type === "tool_use") { toolCall = item as AnthropicToolResponse; } }); if (!toolCall) { throw new Error("No tool call found"); } expect(toolCall).toBeTruthy(); const { name, input } = toolCall; expect(name).toBe("get_weather"); expect(input).toBeTruthy(); expect(input.location).toBeTruthy(); }); test("Can bind & stream AnthropicTools", async () => { const modelWithTools = model.bind({ tools: [anthropicTool], tool_choice: { type: "tool", name: "get_weather", }, }); const result = await modelWithTools.stream( "What is the weather in London today?" ); let finalMessage: AIMessageChunk | undefined; for await (const item of result) { if (!finalMessage) { finalMessage = item; } else { finalMessage = concat(finalMessage, item); } } expect(finalMessage).toBeDefined(); if (!finalMessage) { throw new Error("No final message returned"); } expect(Array.isArray(finalMessage.content)).toBeTruthy(); if (!Array.isArray(finalMessage.content)) { throw new Error("Content is not an array"); } // eslint-disable-next-line @typescript-eslint/no-explicit-any const toolCall = finalMessage.tool_calls?.[0]; if (toolCall === undefined) { throw new Error("No tool call found"); } expect(toolCall).toBeTruthy(); const { name, args } = toolCall; expect(name).toBe("get_weather"); expect(args).toBeTruthy(); expect(args.location).toBeTruthy(); }); test("stream events with no tool calls has string message content", async () => { const wrapper = RunnableLambda.from(async (_, config) => { const res = await model.invoke( "What is the weather in London today?", config ); return res; }); const eventStream = await wrapper.streamEvents( "What is the weather in London today?", { version: "v2", } ); const chatModelStreamEvents = []; for await (const event of eventStream) { if (event.event === "on_chat_model_stream") { chatModelStreamEvents.push(event); } } expect(chatModelStreamEvents.length).toBeGreaterThan(0); expect( chatModelStreamEvents.every( (event) => typeof event.data.chunk.content === "string" ) ).toBe(true); }); test("stream events with tool calls has raw message content", async () => { const modelWithTools = model.bind({ tools: [anthropicTool], tool_choice: { type: "tool", name: "get_weather", }, }); const wrapper = RunnableLambda.from(async (_, config) => { const res = await modelWithTools.invoke( "What is the weather in London today?", config ); return res; }); const eventStream = await wrapper.streamEvents( "What is the weather in London today?", { version: "v2", } ); const chatModelStreamEvents = []; for await (const event of eventStream) { if (event.event === "on_chat_model_stream") { console.log(event); chatModelStreamEvents.push(event); } } expect(chatModelStreamEvents.length).toBeGreaterThan(0); expect( chatModelStreamEvents.every((event) => Array.isArray(event.data.chunk.content) ) ).toBe(true); }); test("withStructuredOutput with zod schema", async () => { const modelWithTools = model.withStructuredOutput<{ location: string }>( zodSchema, { name: "get_weather", } ); const result = await modelWithTools.invoke( "What is the weather in London today?" ); expect(typeof result.location).toBe("string"); }); test("withStructuredOutput with AnthropicTool", async () => { const modelWithTools = model.withStructuredOutput<{ location: string }>( anthropicTool, { name: anthropicTool.name, } ); const result = await modelWithTools.invoke( "What is the weather in London today?" ); expect(typeof result.location).toBe("string"); }); test("withStructuredOutput JSON Schema only", async () => { const jsonSchema = zodToJsonSchema(zodSchema); const modelWithTools = model.withStructuredOutput<{ location: string }>( jsonSchema, { name: "get_weather", } ); const result = await modelWithTools.invoke( "What is the weather in London today?" ); expect(typeof result.location).toBe("string"); }); test("Can pass tool_choice", async () => { const tool1 = { name: "get_weather", description: "Get the weather of a specific location and return the temperature in Celsius.", input_schema: { type: "object", properties: { location: { type: "string", description: "The name of city to get the weather for.", }, }, required: ["location"], }, }; const tool2 = { name: "calculator", description: "Calculate any math expression and return the result.", input_schema: { type: "object", properties: { expression: { type: "string", description: "The math expression to calculate.", }, }, required: ["expression"], }, }; const tools = [tool1, tool2]; const modelWithTools = model.bindTools(tools, { tool_choice: { type: "tool", name: "get_weather", }, }); const result = await modelWithTools.invoke( "What is the sum of 272818 and 281818?" ); expect(Array.isArray(result.content)).toBeTruthy(); if (!Array.isArray(result.content)) { throw new Error("Content is not an array"); } let toolCall: AnthropicToolResponse | undefined; result.content.forEach((item) => { if (item.type === "tool_use") { toolCall = item as AnthropicToolResponse; } }); if (!toolCall) { throw new Error("No tool call found"); } expect(toolCall).toBeTruthy(); const { name, input } = toolCall; expect(input).toEqual(result.tool_calls?.[0].args); expect(name).toBe("get_weather"); expect(input).toBeTruthy(); expect(input.location).toBeTruthy(); }); test("bindTools accepts openai formatted tool", async () => { const openaiTool = { type: "function", function: { name: "get_weather", description: "Get the weather of a specific location and return the temperature in Celsius.", parameters: zodToJsonSchema(zodSchema), }, }; const modelWithTools = model.bindTools([openaiTool]); const response = await modelWithTools.invoke( "Whats the weather like in san francisco?" ); expect(response.tool_calls).toHaveLength(1); const { tool_calls } = response; if (!tool_calls) { return; } expect(tool_calls[0].name).toBe("get_weather"); }); test("withStructuredOutput will always force tool usage", async () => { const weatherTool = z .object({ location: z.string().describe("The name of city to get the weather for."), }) .describe( "Get the weather of a specific location and return the temperature in Celsius." ); const modelWithTools = model.withStructuredOutput(weatherTool, { name: "get_weather", includeRaw: true, }); const response = await modelWithTools.invoke( "What is the sum of 271623 and 281623? It is VERY important you use a calculator tool to give me the answer." ); if (!("tool_calls" in response.raw)) { throw new Error("Tool call not found in response"); } const castMessage = response.raw as AIMessage; expect(castMessage.tool_calls).toHaveLength(1); expect(castMessage.tool_calls?.[0].name).toBe("get_weather"); }); test("Can stream tool calls", async () => { const weatherTool = tool((_) => "no-op", { name: "get_weather", description: zodSchema.description, schema: zodSchema, }); const modelWithTools = model.bindTools([weatherTool], { tool_choice: { type: "tool", name: "get_weather", }, }); const stream = await modelWithTools.stream( "What is the weather in San Francisco CA?" ); let realToolCallChunkStreams = 0; let prevToolCallChunkArgs = ""; let finalChunk: AIMessageChunk | undefined; for await (const chunk of stream) { if (!finalChunk) { finalChunk = chunk; } else { finalChunk = concat(finalChunk, chunk); } if (chunk.tool_call_chunks?.[0]?.args) { // Check if the args have changed since the last chunk. // This helps count the number of unique arg updates in the stream, // ensuring we're receiving multiple chunks with different arg content. if ( !prevToolCallChunkArgs || prevToolCallChunkArgs !== chunk.tool_call_chunks[0].args ) { realToolCallChunkStreams += 1; } prevToolCallChunkArgs = chunk.tool_call_chunks[0].args; } } expect(finalChunk?.tool_calls?.[0]).toBeDefined(); expect(finalChunk?.tool_calls?.[0].name).toBe("get_weather"); expect(finalChunk?.tool_calls?.[0].args.location).toBeDefined(); expect(realToolCallChunkStreams).toBeGreaterThan(1); }); test("llm token callbacks can handle tool calls", async () => { const weatherTool = tool((_) => "no-op", { name: "get_weather", description: zodSchema.description, schema: zodSchema, }); const modelWithTools = model.bindTools([weatherTool], { tool_choice: { type: "tool", name: "get_weather", }, }); let tokens = ""; const stream = await modelWithTools.stream("What is the weather in SF?", { callbacks: [ { handleLLMNewToken: (tok) => { tokens += tok; }, }, ], }); let finalChunk: AIMessageChunk | undefined; for await (const chunk of stream) { finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk); } expect(finalChunk?.tool_calls?.[0]).toBeDefined(); expect(finalChunk?.tool_calls?.[0].name).toBe("get_weather"); expect(finalChunk?.tool_calls?.[0].args).toBeDefined(); const args = finalChunk?.tool_calls?.[0].args; if (!args) return; expect(args).toEqual(JSON.parse(tokens)); }); test("streaming with structured output", async () => { const stream = await model .withStructuredOutput(zodSchema) .stream("weather in london"); // Currently, streaming yields a single chunk let finalChunk; for await (const chunk of stream) { finalChunk = chunk; } expect(typeof finalChunk).toEqual("object"); const stream2 = await model .withStructuredOutput(zodToJsonSchema(zodSchema)) .stream("weather in london"); // Currently, streaming yields a single chunk let finalChunk2; for await (const chunk of stream2) { finalChunk2 = chunk; } expect(typeof finalChunk2).toEqual("object"); }); test("Can bound and invoke different tool types", async () => { const langchainTool = { name: "get_weather_lc", description: "Get the weather of a specific location.", schema: zodSchema, }; const openaiTool = { type: "function", function: { name: "get_weather_oai", description: "Get the weather of a specific location.", parameters: zodToJsonSchema(zodSchema), }, }; const anthropicTool = { name: "get_weather_ant", description: "Get the weather of a specific location.", input_schema: zodToJsonSchema(zodSchema), }; const tools = [langchainTool, openaiTool, anthropicTool]; const modelWithTools = model.bindTools(tools); const result = await modelWithTools.invoke( "Whats the current weather in san francisco?" ); expect(result.tool_calls?.length).toBeGreaterThanOrEqual(1); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/tests/chat_models.test.ts
import { jest, test } from "@jest/globals"; import { AIMessage, HumanMessage, ToolMessage } from "@langchain/core/messages"; import { z } from "zod"; import { OutputParserException } from "@langchain/core/output_parsers"; import { ChatAnthropic } from "../chat_models.js"; import { _convertMessagesToAnthropicPayload } from "../utils/message_inputs.js"; test("withStructuredOutput with output validation", async () => { const model = new ChatAnthropic({ modelName: "claude-3-haiku-20240307", temperature: 0, anthropicApiKey: "testing", }); jest // eslint-disable-next-line @typescript-eslint/no-explicit-any .spyOn(model as any, "invoke") .mockResolvedValue( new AIMessage({ content: [ { type: "tool_use", id: "notreal", name: "Extractor", input: "Incorrect string tool call input", }, ], }) ); const schema = z.object({ alerts: z .array( z.object({ description: z.string().describe("A description of the alert."), severity: z .enum(["HIGH", "MEDIUM", "LOW"]) .describe("How severe the alert is."), }) ) .describe( "Important security or infrastructure alerts present in the given text." ), }); const modelWithStructuredOutput = model.withStructuredOutput(schema, { name: "Extractor", }); await expect(async () => { await modelWithStructuredOutput.invoke(` Enumeration of Kernel Modules via Proc Prompt for Credentials with OSASCRIPT User Login Modification of Standard Authentication Module Suspicious Automator Workflows Execution `); }).rejects.toThrowError(OutputParserException); }); test("withStructuredOutput with proper output", async () => { const model = new ChatAnthropic({ modelName: "claude-3-haiku-20240307", temperature: 0, anthropicApiKey: "testing", }); jest // eslint-disable-next-line @typescript-eslint/no-explicit-any .spyOn(model as any, "invoke") .mockResolvedValue( new AIMessage({ content: [ { type: "tool_use", id: "notreal", name: "Extractor", input: { alerts: [{ description: "test", severity: "LOW" }] }, }, ], }) ); const schema = z.object({ alerts: z .array( z.object({ description: z.string().describe("A description of the alert."), severity: z .enum(["HIGH", "MEDIUM", "LOW"]) .describe("How severe the alert is."), }) ) .describe( "Important security or infrastructure alerts present in the given text." ), }); const modelWithStructuredOutput = model.withStructuredOutput(schema, { name: "Extractor", }); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const result = await modelWithStructuredOutput.invoke(` Enumeration of Kernel Modules via Proc Prompt for Credentials with OSASCRIPT User Login Modification of Standard Authentication Module Suspicious Automator Workflows Execution `); // console.log(result); }); test("Can properly format anthropic messages when given two tool results", async () => { const messageHistory = [ new HumanMessage("What is the weather in SF? Also, what is 2 + 2?"), new AIMessage({ content: "", tool_calls: [ { name: "get_weather", id: "weather_call", args: { location: "SF", }, }, { name: "calculator", id: "calculator_call", args: { expression: "2 + 2", }, }, ], }), new ToolMessage({ name: "get_weather", tool_call_id: "weather_call", content: "It is currently 24 degrees with hail in San Francisco.", }), new ToolMessage({ name: "calculator", tool_call_id: "calculator_call", content: "2 + 2 = 4", }), ]; const formattedMessages = _convertMessagesToAnthropicPayload(messageHistory); expect(formattedMessages).toEqual({ messages: [ { role: "user", content: "What is the weather in SF? Also, what is 2 + 2?", }, { role: "assistant", content: [ { type: "tool_use", id: "weather_call", name: "get_weather", input: { location: "SF" }, }, { type: "tool_use", id: "calculator_call", name: "calculator", input: { expression: "2 + 2" }, }, ], }, // We passed two separate `ToolMessage`s, but Anthropic expects them to // be combined into a single `user` message { role: "user", content: [ { type: "tool_result", content: "It is currently 24 degrees with hail in San Francisco.", tool_use_id: "weather_call", }, { type: "tool_result", content: "2 + 2 = 4", tool_use_id: "calculator_call", }, ], }, ], system: undefined, }); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental/tool_calling.ts
import { XMLParser } from "fast-xml-parser"; import { AIMessage, BaseMessage, BaseMessageLike, SystemMessage, coerceMessageLikeToMessage, } from "@langchain/core/messages"; import type { ChatGenerationChunk, ChatResult, LLMResult, } from "@langchain/core/outputs"; import { BaseChatModel, BaseChatModelParams, } from "@langchain/core/language_models/chat_models"; import { CallbackManagerForLLMRun, Callbacks, } from "@langchain/core/callbacks/manager"; import { BasePromptTemplate } from "@langchain/core/prompts"; import type { BaseLanguageModelCallOptions, BaseLanguageModelInput, StructuredOutputMethodParams, StructuredOutputMethodOptions, ToolDefinition, FunctionDefinition, } from "@langchain/core/language_models/base"; import { Runnable, RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables"; import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_tools"; import type { BaseLLMOutputParser } from "@langchain/core/output_parsers"; import { JsonSchema7ObjectType, zodToJsonSchema } from "zod-to-json-schema"; import { z } from "zod"; import { ChatAnthropic, type AnthropicInput } from "../chat_models.js"; import { DEFAULT_TOOL_SYSTEM_PROMPT, ToolInvocation, formatAsXMLRepresentation, fixArrayXMLParameters, } from "./utils/tool_calling.js"; export interface ChatAnthropicToolsCallOptions extends BaseLanguageModelCallOptions { tools?: ToolDefinition[]; tool_choice?: | "auto" | { function: { name: string; }; type: "function"; }; } export type ChatAnthropicToolsInput = Partial<AnthropicInput> & BaseChatModelParams & { llm?: BaseChatModel; systemPromptTemplate?: BasePromptTemplate; }; /** * Experimental wrapper over Anthropic chat models that adds support for * a function calling interface. * @deprecated Prefer traditional tool use through ChatAnthropic. */ export class ChatAnthropicTools extends BaseChatModel<ChatAnthropicToolsCallOptions> { llm: BaseChatModel; stopSequences?: string[]; systemPromptTemplate: BasePromptTemplate; lc_namespace = ["langchain", "experimental", "chat_models"]; static lc_name(): string { return "ChatAnthropicTools"; } constructor(fields?: ChatAnthropicToolsInput) { if (fields?.cache !== undefined) { throw new Error("Caching is not supported for this model."); } super(fields ?? {}); this.llm = fields?.llm ?? new ChatAnthropic(fields); this.systemPromptTemplate = fields?.systemPromptTemplate ?? DEFAULT_TOOL_SYSTEM_PROMPT; this.stopSequences = fields?.stopSequences ?? (this.llm as ChatAnthropic).stopSequences; } invocationParams() { return this.llm.invocationParams(); } /** @ignore */ _identifyingParams() { return this.llm._identifyingParams(); } async *_streamResponseChunks( messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun ): AsyncGenerator<ChatGenerationChunk> { yield* this.llm._streamResponseChunks(messages, options, runManager); } async _prepareAndParseToolCall({ messages, options, systemPromptTemplate = DEFAULT_TOOL_SYSTEM_PROMPT, stopSequences, }: { messages: BaseMessage[]; options: ChatAnthropicToolsCallOptions; systemPromptTemplate?: BasePromptTemplate; stopSequences: string[]; }): Promise<ChatResult> { let promptMessages = messages; let forced = false; let toolCall: string | undefined; const tools = options.tools === undefined ? [] : [...options.tools]; if (options.tools !== undefined && options.tools.length > 0) { const content = await systemPromptTemplate.format({ tools: `<tools>\n${options.tools .map(formatAsXMLRepresentation) .join("\n\n")}</tools>`, }); if (promptMessages.length && promptMessages[0]._getType() !== "system") { const systemMessage = new SystemMessage({ content }); promptMessages = [systemMessage].concat(promptMessages); } else { const systemMessage = new SystemMessage({ content: `${content}\n\n${promptMessages[0].content}`, }); promptMessages = [systemMessage].concat(promptMessages.slice(1)); } // eslint-disable-next-line no-param-reassign options.stop = stopSequences.concat(["</function_calls>"]); if (options.tool_choice && options.tool_choice !== "auto") { toolCall = options.tool_choice.function.name; forced = true; const matchingFunction = options.tools.find( // eslint-disable-next-line @typescript-eslint/no-explicit-any (tool) => tool.function.name === toolCall ); if (!matchingFunction) { throw new Error( `No matching function found for passed "tool_choice"` ); } promptMessages = promptMessages.concat([ new AIMessage({ content: `<function_calls>\n<invoke><tool_name>${toolCall}</tool_name>`, }), ]); // eslint-disable-next-line no-param-reassign delete options.tool_choice; } // eslint-disable-next-line no-param-reassign delete options.tools; } else if (options.tool_choice !== undefined) { throw new Error(`If "tool_choice" is provided, "tools" must also be.`); } const chatResult = await this.llm .withConfig({ runName: "ChatAnthropicTools" }) .invoke(promptMessages, options); const chatGenerationContent = chatResult.content; if (typeof chatGenerationContent !== "string") { throw new Error("AnthropicFunctions does not support non-string output."); } if (forced) { const parser = new XMLParser(); const result = parser.parse( `<function_calls>\n<invoke><tool_name>${toolCall}</tool_name>${chatGenerationContent}</function_calls>` ); if (toolCall === undefined) { throw new Error(`Could not parse called function from model output.`); } const invocations: ToolInvocation[] = Array.isArray( result.function_calls?.invoke ?? [] ) ? result.function_calls.invoke : [result.function_calls.invoke]; const responseMessageWithFunctions = new AIMessage({ content: "", additional_kwargs: { tool_calls: invocations.map((toolInvocation, i) => { const calledTool = tools.find( (tool) => tool.function.name === toolCall ); if (calledTool === undefined) { throw new Error( `Called tool "${toolCall}" did not match an existing tool.` ); } return { id: i.toString(), type: "function", function: { name: toolInvocation.tool_name, arguments: JSON.stringify( fixArrayXMLParameters( calledTool.function.parameters as JsonSchema7ObjectType, toolInvocation.parameters ) ), }, }; }), }, }); return { generations: [{ message: responseMessageWithFunctions, text: "" }], }; } else if (chatGenerationContent.includes("<function_calls>")) { const parser = new XMLParser(); const result = parser.parse(`${chatGenerationContent}</function_calls>`); const invocations: ToolInvocation[] = Array.isArray( result.function_calls?.invoke ?? [] ) ? result.function_calls.invoke : [result.function_calls.invoke]; const responseMessageWithFunctions = new AIMessage({ content: chatGenerationContent.split("<function_calls>")[0], additional_kwargs: { tool_calls: invocations.map((toolInvocation, i) => { const calledTool = tools.find( (tool) => tool.function.name === toolInvocation.tool_name ); if (calledTool === undefined) { throw new Error( `Called tool "${toolCall}" did not match an existing tool.` ); } return { id: i.toString(), type: "function", function: { name: toolInvocation.tool_name, arguments: JSON.stringify( fixArrayXMLParameters( calledTool.function.parameters as JsonSchema7ObjectType, toolInvocation.parameters ) ), }, }; }), }, }); return { generations: [{ message: responseMessageWithFunctions, text: "" }], }; } return { generations: [{ message: chatResult, text: "" }] }; } async generate( messages: BaseMessageLike[][], parsedOptions?: ChatAnthropicToolsCallOptions, callbacks?: Callbacks ): Promise<LLMResult> { const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage) ); // generate results const chatResults = await Promise.all( baseMessages.map((messageList) => this._prepareAndParseToolCall({ messages: messageList, options: { callbacks, ...parsedOptions }, systemPromptTemplate: this.systemPromptTemplate, stopSequences: this.stopSequences ?? [], }) ) ); // create combined output const output: LLMResult = { generations: chatResults.map((chatResult) => chatResult.generations), }; return output; } async _generate( _messages: BaseMessage[], _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun | undefined ): Promise<ChatResult> { throw new Error("Unused."); } _llmType(): string { return "anthropic_tool_calling"; } withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | StructuredOutputMethodParams<RunOutput, false> | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<false> & { force?: boolean } ): Runnable<BaseLanguageModelInput, RunOutput>; withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | StructuredOutputMethodParams<RunOutput, true> | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<true> & { force?: boolean } ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>; withStructuredOutput< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( outputSchema: | StructuredOutputMethodParams<RunOutput, boolean> | z.ZodType<RunOutput> // eslint-disable-next-line @typescript-eslint/no-explicit-any | Record<string, any>, config?: StructuredOutputMethodOptions<boolean> & { force?: boolean } ): | Runnable<BaseLanguageModelInput, RunOutput> | Runnable< BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput } > { // eslint-disable-next-line @typescript-eslint/no-explicit-any let schema: z.ZodType<RunOutput> | Record<string, any>; let name; let method; let includeRaw; let force; if (isStructuredOutputMethodParams(outputSchema)) { schema = outputSchema.schema; name = outputSchema.name; method = outputSchema.method; includeRaw = outputSchema.includeRaw; } else { schema = outputSchema; name = config?.name; method = config?.method; includeRaw = config?.includeRaw; force = config?.force ?? false; } if (method === "jsonMode") { throw new Error(`Anthropic only supports "functionCalling" as a method.`); } let functionName = name ?? "extract"; let outputParser: BaseLLMOutputParser<RunOutput>; let tools: ToolDefinition[]; if (isZodSchema(schema)) { const jsonSchema = zodToJsonSchema(schema); tools = [ { type: "function" as const, function: { name: functionName, description: jsonSchema.description, parameters: jsonSchema, }, }, ]; outputParser = new JsonOutputKeyToolsParser({ returnSingle: true, keyName: functionName, zodSchema: schema, }); } else { let openAIFunctionDefinition: FunctionDefinition; if ( typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null ) { openAIFunctionDefinition = schema as FunctionDefinition; functionName = schema.name; } else { openAIFunctionDefinition = { name: functionName, description: schema.description ?? "", parameters: schema, }; } tools = [ { type: "function" as const, function: openAIFunctionDefinition, }, ]; outputParser = new JsonOutputKeyToolsParser<RunOutput>({ returnSingle: true, keyName: functionName, }); } const llm = this.bind({ tools, tool_choice: force ? { type: "function", function: { name: functionName, }, } : "auto", }); if (!includeRaw) { return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput", }) as Runnable<BaseLanguageModelInput, RunOutput>; } const parserAssign = RunnablePassthrough.assign({ // eslint-disable-next-line @typescript-eslint/no-explicit-any parsed: (input: any, config) => outputParser.invoke(input.raw, config), }); const parserNone = RunnablePassthrough.assign({ parsed: () => null, }); const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone], }); return RunnableSequence.from< BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput } >([ { raw: llm, }, parsedWithFallback, ]).withConfig({ runName: "StructuredOutputRunnable", }); } } function isZodSchema< // eslint-disable-next-line @typescript-eslint/no-explicit-any RunOutput extends Record<string, any> = Record<string, any> >( // eslint-disable-next-line @typescript-eslint/no-explicit-any input: z.ZodType<RunOutput> | Record<string, any> ): input is z.ZodType<RunOutput> { // Check for a characteristic method of Zod schemas return typeof (input as z.ZodType<RunOutput>)?.parse === "function"; } function isStructuredOutputMethodParams( x: unknown // eslint-disable-next-line @typescript-eslint/no-explicit-any ): x is StructuredOutputMethodParams<Record<string, any>> { return ( x !== undefined && // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof (x as StructuredOutputMethodParams<Record<string, any>>).schema === "object" ); }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental/index.ts
export * from "./tool_calling.js";
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental/tests/tool_calling.int.test.ts
/* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { test } from "@jest/globals"; import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; import { BaseMessageChunk, HumanMessage } from "@langchain/core/messages"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { ChatAnthropicTools } from "../tool_calling.js"; test.skip("Test ChatAnthropicTools", async () => { const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const message = new HumanMessage("Hello!"); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const res = await chat.invoke([message]); // console.log(JSON.stringify(res)); }); test.skip("Test ChatAnthropicTools streaming", async () => { const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const message = new HumanMessage("Hello!"); const stream = await chat.stream([message]); const chunks: BaseMessageChunk[] = []; for await (const chunk of stream) { // console.log(chunk); chunks.push(chunk); } expect(chunks.length).toBeGreaterThan(1); }); test.skip("Test ChatAnthropicTools with tools", async () => { const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", temperature: 0.1, maxRetries: 0, }).bind({ tools: [ { type: "function", function: { name: "get_current_weather", description: "Get the current weather in a given location", parameters: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, unit: { type: "string", enum: ["celsius", "fahrenheit"], }, }, required: ["location"], }, }, }, ], }); const message = new HumanMessage("What is the weather in San Francisco?"); const res = await chat.invoke([message]); // console.log(JSON.stringify(res)); expect(res.additional_kwargs.tool_calls).toBeDefined(); expect(res.additional_kwargs.tool_calls?.[0].function.name).toEqual( "get_current_weather" ); }); test.skip("Test ChatAnthropicTools with a forced function call", async () => { const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", temperature: 0.1, maxRetries: 0, }).bind({ tools: [ { type: "function", function: { name: "extract_data", description: "Return information about the input", parameters: { type: "object", properties: { sentiment: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, aggressiveness: { type: "integer", description: "How aggressive the input is from 1 to 10", }, language: { type: "string", description: "The language the input is in", }, }, required: ["sentiment", "aggressiveness"], }, }, }, ], tool_choice: { type: "function", function: { name: "extract_data" } }, }); const message = new HumanMessage( "Extract the desired information from the following passage:\n\nthis is really cool" ); const res = await chat.invoke([message]); // console.log(JSON.stringify(res)); expect(res.additional_kwargs.tool_calls).toBeDefined(); expect(res.additional_kwargs.tool_calls?.[0]?.function.name).toEqual( "extract_data" ); }); test.skip("ChatAnthropicTools with Zod schema", async () => { const schema = z.object({ people: z.array( z.object({ name: z.string().describe("The name of a person"), height: z.number().describe("The person's height"), hairColor: z.optional(z.string()).describe("The person's hair color"), }) ), }); const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", temperature: 0.1, maxRetries: 0, }).bind({ tools: [ { type: "function", function: { name: "information_extraction", description: "Extracts the relevant information from the passage.", parameters: zodToJsonSchema(schema), }, }, ], tool_choice: { type: "function", function: { name: "information_extraction", }, }, }); const message = new HumanMessage( "Alex is 5 feet tall. Claudia is 1 foot taller than Alex and jumps higher than him. Claudia is a brunette and Alex is blonde." ); const res = await chat.invoke([message]); // console.log(JSON.stringify(res)); expect(res.additional_kwargs.tool_calls).toBeDefined(); expect(res.additional_kwargs.tool_calls?.[0]?.function.name).toEqual( "information_extraction" ); expect( JSON.parse(res.additional_kwargs.tool_calls?.[0]?.function.arguments ?? "") ).toEqual({ people: expect.arrayContaining([ { name: "Alex", height: 5, hairColor: "blonde" }, { name: "Claudia", height: 6, hairColor: "brunette" }, ]), }); }); test.skip("ChatAnthropicTools with parallel tool calling", async () => { const schema = z.object({ name: z.string().describe("The name of a person"), height: z.number().describe("The person's height"), hairColor: z.optional(z.string()).describe("The person's hair color"), }); const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", temperature: 0.1, maxRetries: 0, }).bind({ tools: [ { type: "function", function: { name: "person", description: "A person mentioned in the passage.", parameters: zodToJsonSchema(schema), }, }, ], tool_choice: { type: "function", function: { name: "person", }, }, }); // console.log(zodToJsonSchema(schema)); const message = new HumanMessage( "Alex is 5 feet tall. Claudia is 1 foot taller than Alex and jumps higher than him. Claudia is a brunette and Alex is blonde." ); const res = await chat.invoke([message]); // console.log(JSON.stringify(res)); expect(res.additional_kwargs.tool_calls).toBeDefined(); expect( res.additional_kwargs.tool_calls?.map((toolCall) => JSON.parse(toolCall.function.arguments ?? "") ) ).toEqual( expect.arrayContaining([ { name: "Alex", height: 5, hairColor: "blonde" }, { name: "Claudia", height: 6, hairColor: "brunette" }, ]) ); }); test.skip("Test ChatAnthropic withStructuredOutput", async () => { const runnable = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }).withStructuredOutput( z.object({ name: z.string().describe("The name of a person"), height: z.number().describe("The person's height"), hairColor: z.optional(z.string()).describe("The person's hair color"), }), { name: "person", } ); const message = new HumanMessage("Alex is 5 feet tall. Alex is blonde."); const res = await runnable.invoke([message]); // console.log(JSON.stringify(res, null, 2)); expect(res).toEqual({ name: "Alex", height: 5, hairColor: "blonde" }); }); test.skip("Test ChatAnthropic withStructuredOutput on a single array item", async () => { const runnable = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }).withStructuredOutput( z.object({ people: z.array( z.object({ name: z.string().describe("The name of a person"), height: z.number().describe("The person's height"), hairColor: z.optional(z.string()).describe("The person's hair color"), }) ), }) ); const message = new HumanMessage("Alex is 5 feet tall. Alex is blonde."); const res = await runnable.invoke([message]); // console.log(JSON.stringify(res, null, 2)); expect(res).toEqual({ people: [{ hairColor: "blonde", height: 5, name: "Alex" }], }); }); test.skip("Test ChatAnthropic withStructuredOutput on a single array item", async () => { const runnable = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }).withStructuredOutput( z.object({ sender: z .optional(z.string()) .describe("The sender's name, if available"), sender_phone_number: z .optional(z.string()) .describe("The sender's phone number, if available"), sender_address: z .optional(z.string()) .describe("The sender's address, if available"), action_items: z .array(z.string()) .describe("A list of action items requested by the email"), topic: z .string() .describe("High level description of what the email is about"), tone: z.enum(["positive", "negative"]).describe("The tone of the email."), }), { name: "Email", } ); const prompt = ChatPromptTemplate.fromMessages([ [ "human", "What can you tell me about the following email? Make sure to answer in the correct format: {email}", ], ]); const extractionChain = prompt.pipe(runnable); const response = await extractionChain.invoke({ email: "From: Erick. The email is about the new project. The tone is positive. The action items are to send the report and to schedule a meeting.", }); // console.log(JSON.stringify(response, null, 2)); expect(response).toEqual({ sender: "Erick", action_items: [expect.any(String), expect.any(String)], topic: expect.any(String), tone: "positive", }); }); test.skip("Test ChatAnthropicTools", async () => { const chat = new ChatAnthropicTools({ modelName: "claude-3-sonnet-20240229", maxRetries: 0, }); const structured = chat.withStructuredOutput( z.object({ nested: z.array(z.number()), }), { force: false } ); const res = await structured.invoke( "What are the first five natural numbers?" ); // console.log(res); expect(res).toEqual({ nested: [1, 2, 3, 4, 5], }); });
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental
lc_public_repos/langchainjs/libs/langchain-anthropic/src/experimental/utils/tool_calling.ts
import { XMLBuilder } from "fast-xml-parser"; import { JsonSchema7ObjectType } from "zod-to-json-schema"; import { PromptTemplate } from "@langchain/core/prompts"; import { ToolDefinition } from "@langchain/core/language_models/base"; export const DEFAULT_TOOL_SYSTEM_PROMPT = /* #__PURE__ */ PromptTemplate.fromTemplate(`In this environment you have access to a set of tools you can use to answer the user's question. You may call them like this: <function_calls> <invoke> <tool_name>$TOOL_NAME</tool_name> <parameters> <$PARAMETER_NAME>$PARAMETER_VALUE</$PARAMETER_NAME> ... </parameters> </invoke> </function_calls> Here are the tools available: {tools} If the schema above contains a property typed as an enum, you must only return values matching an allowed value for that enum.`); export type ToolInvocation = { tool_name: string; parameters: Record<string, unknown>; }; export function formatAsXMLRepresentation(tool: ToolDefinition) { const builder = new XMLBuilder(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const toolParamProps = (tool.function.parameters as any)?.properties; const parameterXml = Object.keys(toolParamProps) .map((key) => { const parameterData = toolParamProps[key]; let xml = `<parameter> <name>${key}</name> <type>${parameterData.type}</type>`; if (parameterData.description) { xml += `\n<description>${parameterData.description}</description>`; } if (parameterData.type === "array" && parameterData.items) { xml += `\n<items>${builder.build( parameterData.items.properties )}</items>`; } if (parameterData.properties) { xml += `\n<properties>\n${builder.build( parameterData.properties )}\n</properties>`; } return `${xml}\n</parameter>`; }) .join("\n"); return `<tool_description> <tool_name>${tool.function.name}</tool_name> <description>${tool.function.description}</description> <parameters> ${parameterXml} </parameters> </tool_description>`; } export function fixArrayXMLParameters( schema: JsonSchema7ObjectType, // eslint-disable-next-line @typescript-eslint/no-explicit-any xmlParameters: Record<string, any> // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Record<string, any> { // eslint-disable-next-line @typescript-eslint/no-explicit-any const fixedParameters: Record<string, any> = {}; for (const key of Object.keys(xmlParameters)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const schemaType = (schema.properties[key] as any).type; // Crawl for lists indistinguishable from single items if (schema.properties && schema.properties[key] && schemaType === "array") { const value = xmlParameters[key]; if (Array.isArray(value)) { fixedParameters[key] = value; } else if (typeof value === "string") { if (value.startsWith("[") && value.endsWith("]")) { fixedParameters[key] = JSON.parse(value); } else { fixedParameters[key] = value.split(","); } } else { fixedParameters[key] = [value]; } // Crawl for objects like {"item": "my string"} that should really just be "my string" if ( schemaType !== "object" && typeof xmlParameters[key] === "object" && !Array.isArray(xmlParameters[key]) && Object.keys(xmlParameters[key]).length === 1 ) { // eslint-disable-next-line prefer-destructuring fixedParameters[key] = Object.values(xmlParameters[key])[0]; } } else if ( typeof xmlParameters[key] === "object" && xmlParameters[key] !== null ) { fixedParameters[key] = fixArrayXMLParameters( { ...schema.properties[key], // eslint-disable-next-line @typescript-eslint/no-explicit-any definitions: (schema as any).definitions, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, xmlParameters[key] ); } else { fixedParameters[key] = xmlParameters[key]; } } return fixedParameters; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/utils/tools.ts
import type { MessageCreateParams } from "@anthropic-ai/sdk/resources/index.mjs"; import { AnthropicToolChoice } from "../types.js"; export function handleToolChoice( toolChoice?: AnthropicToolChoice ): | MessageCreateParams.ToolChoiceAuto | MessageCreateParams.ToolChoiceAny | MessageCreateParams.ToolChoiceTool | undefined { if (!toolChoice) { return undefined; } else if (toolChoice === "any") { return { type: "any", }; } else if (toolChoice === "auto") { return { type: "auto", }; } else if (typeof toolChoice === "string") { return { type: "tool", name: toolChoice, }; } else { return toolChoice; } }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/utils/errors.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable no-param-reassign */ // Duplicate of core // TODO: Remove once we stop supporting 0.2.x core versions export type LangChainErrorCodes = | "INVALID_PROMPT_INPUT" | "INVALID_TOOL_RESULTS" | "MESSAGE_COERCION_FAILURE" | "MODEL_AUTHENTICATION" | "MODEL_NOT_FOUND" | "MODEL_RATE_LIMIT" | "OUTPUT_PARSING_FAILURE"; export function addLangChainErrorFields( error: any, lc_error_code: LangChainErrorCodes ) { (error as any).lc_error_code = lc_error_code; error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; return error; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function wrapAnthropicClientError(e: any) { let error; if (e.status === 400 && e.message.includes("tool")) { error = addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); } else if (e.status === 401) { error = addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); } else if (e.status === 404) { error = addLangChainErrorFields(e, "MODEL_NOT_FOUND"); } else if (e.status === 429) { error = addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); } else { error = e; } return error; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/utils/message_inputs.ts
/** * This util file contains functions for converting LangChain messages to Anthropic messages. */ import { BaseMessage, SystemMessage, HumanMessage, AIMessage, ToolMessage, MessageContent, isAIMessage, } from "@langchain/core/messages"; import { ToolCall } from "@langchain/core/messages/tool"; import { AnthropicMessageCreateParams, AnthropicToolResponse, } from "../types.js"; function _formatImage(imageUrl: string) { const regex = /^data:(image\/.+);base64,(.+)$/; const match = imageUrl.match(regex); if (match === null) { throw new Error( [ "Anthropic only supports base64-encoded images currently.", "Example: data:image/png;base64,/9j/4AAQSk...", ].join("\n\n") ); } return { type: "base64", media_type: match[1] ?? "", data: match[2] ?? "", // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; } function _ensureMessageContents( messages: BaseMessage[] ): (SystemMessage | HumanMessage | AIMessage)[] { // Merge runs of human/tool messages into single human messages with content blocks. const updatedMsgs = []; for (const message of messages) { if (message._getType() === "tool") { if (typeof message.content === "string") { const previousMessage = updatedMsgs[updatedMsgs.length - 1]; if ( previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result" ) { // If the previous message was a tool result, we merge this tool message into it. previousMessage.content.push({ type: "tool_result", content: message.content, tool_use_id: (message as ToolMessage).tool_call_id, }); } else { // If not, we create a new human message with the tool result. updatedMsgs.push( new HumanMessage({ content: [ { type: "tool_result", content: message.content, tool_use_id: (message as ToolMessage).tool_call_id, }, ], }) ); } } else { updatedMsgs.push( new HumanMessage({ content: [ { type: "tool_result", content: _formatContent(message.content), tool_use_id: (message as ToolMessage).tool_call_id, }, ], }) ); } } else { updatedMsgs.push(message); } } return updatedMsgs; } export function _convertLangChainToolCallToAnthropic( toolCall: ToolCall ): AnthropicToolResponse { if (toolCall.id === undefined) { throw new Error(`Anthropic requires all tool calls to have an "id".`); } return { type: "tool_use", id: toolCall.id, name: toolCall.name, input: toolCall.args, }; } function _formatContent(content: MessageContent) { const toolTypes = ["tool_use", "tool_result", "input_json_delta"]; const textTypes = ["text", "text_delta"]; if (typeof content === "string") { return content; } else { const contentBlocks = content.map((contentPart) => { const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : undefined; if (contentPart.type === "image_url") { let source; if (typeof contentPart.image_url === "string") { source = _formatImage(contentPart.image_url); } else { source = _formatImage(contentPart.image_url.url); } return { type: "image" as const, // Explicitly setting the type as "image" source, ...(cacheControl ? { cache_control: cacheControl } : {}), }; } else if ( textTypes.find((t) => t === contentPart.type) && "text" in contentPart ) { // Assuming contentPart is of type MessageContentText here return { type: "text" as const, // Explicitly setting the type as "text" text: contentPart.text, ...(cacheControl ? { cache_control: cacheControl } : {}), }; } else if (toolTypes.find((t) => t === contentPart.type)) { const contentPartCopy = { ...contentPart }; if ("index" in contentPartCopy) { // Anthropic does not support passing the index field here, so we remove it. delete contentPartCopy.index; } if (contentPartCopy.type === "input_json_delta") { // `input_json_delta` type only represents yielding partial tool inputs // and is not a valid type for Anthropic messages. contentPartCopy.type = "tool_use"; } if ("input" in contentPartCopy) { // Anthropic tool use inputs should be valid objects, when applicable. try { contentPartCopy.input = JSON.parse(contentPartCopy.input); } catch { // no-op } } // TODO: Fix when SDK types are fixed return { ...contentPartCopy, ...(cacheControl ? { cache_control: cacheControl } : {}), // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; } else { throw new Error("Unsupported message content format"); } }); return contentBlocks; } } /** * Formats messages as a prompt for the model. * Used in LangSmith, export is important here. * @param messages The base messages to format as a prompt. * @returns The formatted prompt. */ export function _convertMessagesToAnthropicPayload( messages: BaseMessage[] ): AnthropicMessageCreateParams { const mergedMessages = _ensureMessageContents(messages); let system; if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") { system = messages[0].content; } const conversationMessages = system !== undefined ? mergedMessages.slice(1) : mergedMessages; const formattedMessages = conversationMessages.map((message) => { let role; if (message._getType() === "human") { role = "user" as const; } else if (message._getType() === "ai") { role = "assistant" as const; } else if (message._getType() === "tool") { role = "user" as const; } else if (message._getType() === "system") { throw new Error( "System messages are only permitted as the first passed message." ); } else { throw new Error(`Message type "${message._getType()}" is not supported.`); } if (isAIMessage(message) && !!message.tool_calls?.length) { if (typeof message.content === "string") { if (message.content === "") { return { role, content: message.tool_calls.map( _convertLangChainToolCallToAnthropic ), }; } else { return { role, content: [ { type: "text", text: message.content }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic), ], }; } } else { const { content } = message; const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find( (contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta") && contentPart.id === toolCall.id ) ); if (hasMismatchedToolCalls) { console.warn( `The "tool_calls" field on a message is only respected if content is a string.` ); } return { role, content: _formatContent(message.content), }; } } else { return { role, content: _formatContent(message.content), }; } }); return { messages: formattedMessages, system, } as AnthropicMessageCreateParams; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/utils/message_outputs.ts
/** * This util file contains functions for converting Anthropic messages to LangChain messages. */ import Anthropic from "@anthropic-ai/sdk"; import { AIMessage, AIMessageChunk, UsageMetadata, } from "@langchain/core/messages"; import { ChatGeneration } from "@langchain/core/outputs"; import { AnthropicMessageResponse } from "../types.js"; import { extractToolCalls } from "../output_parsers.js"; export function _makeMessageChunkFromAnthropicEvent( data: Anthropic.Messages.RawMessageStreamEvent, fields: { streamUsage: boolean; coerceContentToString: boolean; } ): { chunk: AIMessageChunk; } | null { if (data.type === "message_start") { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { content, usage, ...additionalKwargs } = data.message; // eslint-disable-next-line @typescript-eslint/no-explicit-any const filteredAdditionalKwargs: Record<string, any> = {}; for (const [key, value] of Object.entries(additionalKwargs)) { if (value !== undefined && value !== null) { filteredAdditionalKwargs[key] = value; } } const usageMetadata: UsageMetadata = { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, total_tokens: usage.input_tokens + usage.output_tokens, }; return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? "" : [], additional_kwargs: filteredAdditionalKwargs, usage_metadata: fields.streamUsage ? usageMetadata : undefined, id: data.message.id, }), }; } else if (data.type === "message_delta") { const usageMetadata: UsageMetadata = { input_tokens: 0, output_tokens: data.usage.output_tokens, total_tokens: data.usage.output_tokens, }; return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? "" : [], additional_kwargs: { ...data.delta }, usage_metadata: fields.streamUsage ? usageMetadata : undefined, }), }; } else if ( data.type === "content_block_start" && data.content_block.type === "tool_use" ) { const toolCallContentBlock = data.content_block as Anthropic.Messages.ToolUseBlock; return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? "" : [ { index: data.index, ...data.content_block, input: "", }, ], additional_kwargs: {}, tool_call_chunks: [ { id: toolCallContentBlock.id, index: data.index, name: toolCallContentBlock.name, args: "", }, ], }), }; } else if ( data.type === "content_block_delta" && data.delta.type === "text_delta" ) { const content = data.delta?.text; if (content !== undefined) { return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? content : [ { index: data.index, ...data.delta, }, ], additional_kwargs: {}, }), }; } } else if ( data.type === "content_block_delta" && data.delta.type === "input_json_delta" ) { return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? "" : [ { index: data.index, input: data.delta.partial_json, type: data.delta.type, }, ], additional_kwargs: {}, tool_call_chunks: [ { index: data.index, args: data.delta.partial_json, }, ], }), }; } else if ( data.type === "content_block_start" && data.content_block.type === "text" ) { const content = data.content_block?.text; if (content !== undefined) { return { chunk: new AIMessageChunk({ content: fields.coerceContentToString ? content : [ { index: data.index, ...data.content_block, }, ], additional_kwargs: {}, }), }; } } return null; } export function anthropicResponseToChatMessages( messages: AnthropicMessageResponse[], additionalKwargs: Record<string, unknown> ): ChatGeneration[] { const usage: Record<string, number> | null | undefined = additionalKwargs.usage as Record<string, number> | null | undefined; const usageMetadata = usage != null ? { input_tokens: usage.input_tokens ?? 0, output_tokens: usage.output_tokens ?? 0, total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0), } : undefined; if (messages.length === 1 && messages[0].type === "text") { return [ { text: messages[0].text, message: new AIMessage({ content: messages[0].text, additional_kwargs: additionalKwargs, usage_metadata: usageMetadata, response_metadata: additionalKwargs, id: additionalKwargs.id as string, }), }, ]; } else { const toolCalls = extractToolCalls(messages); const generations: ChatGeneration[] = [ { text: "", message: new AIMessage({ // eslint-disable-next-line @typescript-eslint/no-explicit-any content: messages as any, additional_kwargs: additionalKwargs, tool_calls: toolCalls, usage_metadata: usageMetadata, response_metadata: additionalKwargs, id: additionalKwargs.id as string, }), }, ]; return generations; } }
0
lc_public_repos/langchainjs/libs/langchain-anthropic/src
lc_public_repos/langchainjs/libs/langchain-anthropic/src/utils/prompts.ts
import type { BasePromptValue } from "@langchain/core/prompt_values"; import Anthropic from "@anthropic-ai/sdk"; import { _convertMessagesToAnthropicPayload } from "./message_inputs.js"; /** * Convert a formatted LangChain prompt (e.g. pulled from the hub) into * a format expected by Anthropic's JS SDK. * * Requires the "@langchain/anthropic" package to be installed in addition * to the Anthropic SDK. * * @example * ```ts * import { convertPromptToAnthropic } from "langsmith/utils/hub/anthropic"; * import { pull } from "langchain/hub"; * * import Anthropic from '@anthropic-ai/sdk'; * * const prompt = await pull("jacob/joke-generator"); * const formattedPrompt = await prompt.invoke({ * topic: "cats", * }); * * const { system, messages } = convertPromptToAnthropic(formattedPrompt); * * const anthropicClient = new Anthropic({ * apiKey: 'your_api_key', * }); * * const anthropicResponse = await anthropicClient.messages.create({ * model: "claude-3-5-sonnet-20240620", * max_tokens: 1024, * stream: false, * system, * messages, * }); * ``` * @param formattedPrompt * @returns A partial Anthropic payload. */ export function convertPromptToAnthropic( formattedPrompt: BasePromptValue ): Anthropic.Messages.MessageCreateParams { const messages = formattedPrompt.toChatMessages(); const anthropicBody = _convertMessagesToAnthropicPayload(messages); if (anthropicBody.messages === undefined) { anthropicBody.messages = []; } return anthropicBody; }
0
lc_public_repos/langchainjs/libs/langchain-anthropic
lc_public_repos/langchainjs/libs/langchain-anthropic/scripts/jest-setup-after-env.js
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises"; import { afterAll, jest } from "@jest/globals"; afterAll(awaitAllCallbacks); // Allow console.log to be disabled in tests if (process.env.DISABLE_CONSOLE_LOGS === "true") { console.log = jest.fn(); }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/tsconfig.json
{ "extends": "@tsconfig/recommended", "compilerOptions": { "outDir": "../dist", "rootDir": "./src", "target": "ES2021", "lib": ["ES2021", "ES2022.Object", "DOM"], "module": "ES2020", "moduleResolution": "nodenext", "esModuleInterop": true, "declaration": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUnusedLocals": true, "noUnusedParameters": true, "useDefineForClassFields": true, "strictPropertyInitialization": false, "allowJs": true, "strict": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "docs"] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/LICENSE
The MIT License Copyright (c) 2023 LangChain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/jest.config.cjs
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: "ts-jest/presets/default-esm", testEnvironment: "./jest.env.cjs", modulePathIgnorePatterns: ["dist/", "docs/"], moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", }, transform: { "^.+\\.tsx?$": ["@swc/jest"], }, transformIgnorePatterns: [ "/node_modules/", "\\.pnp\\.[^\\/]+$", "./scripts/jest-setup-after-env.js", ], setupFiles: ["dotenv/config"], testTimeout: 20_000, passWithNoTests: true, collectCoverageFrom: ["src/**/*.ts"], };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/jest.env.cjs
const { TestEnvironment } = require("jest-environment-node"); class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment { constructor(config, context) { // Make `instanceof Float32Array` return true in tests // to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549 super(config, context); this.global.Float32Array = Float32Array; } } module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/README.md
# @langchain/pinecone This package contains the LangChain.js integrations for through their SDK. ## Installation ```bash npm2yarn npm install @langchain/pinecone @langchain/core ``` ## Development To develop the Pinecone package, you'll need to follow these instructions: ### Install dependencies ```bash yarn install ``` ### Build the package ```bash yarn build ``` Or from the repo root: ```bash yarn build --filter=@langchain/pinecone ``` ### Run tests Test files should live within a `tests/` file in the `src/` folder. Unit tests should end in `.test.ts` and integration tests should end in `.int.test.ts`: ```bash $ yarn test $ yarn test:int ``` ### Lint & Format Run the linter & formatter to ensure your code is up to standard: ```bash yarn lint && yarn format ``` ### Adding new entrypoints If you add a new file to be exported, either import & re-export from `src/index.ts`, or add it to the `entrypoints` field in the `config` variable located inside `langchain.config.js` and run `yarn build` to generate the new entrypoint.
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/.release-it.json
{ "github": { "release": true, "autoGenerate": true, "tokenRef": "GITHUB_TOKEN_RELEASE" }, "npm": { "versionArgs": [ "--workspaces-update=false" ] } }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/.eslintrc.cjs
module.exports = { extends: [ "airbnb-base", "eslint:recommended", "prettier", "plugin:@typescript-eslint/recommended", ], parserOptions: { ecmaVersion: 12, parser: "@typescript-eslint/parser", project: "./tsconfig.json", sourceType: "module", }, plugins: ["@typescript-eslint", "no-instanceof"], ignorePatterns: [ ".eslintrc.cjs", "scripts", "node_modules", "dist", "dist-cjs", "*.js", "*.cjs", "*.d.ts", ], rules: { "no-process-env": 2, "no-instanceof/no-instanceof": 2, "@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/no-empty-function": 0, "@typescript-eslint/no-shadow": 0, "@typescript-eslint/no-empty-interface": 0, "@typescript-eslint/no-use-before-define": ["error", "nofunc"], "@typescript-eslint/no-unused-vars": ["warn", { args: "none" }], "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-misused-promises": "error", camelcase: 0, "class-methods-use-this": 0, "import/extensions": [2, "ignorePackages"], "import/no-extraneous-dependencies": [ "error", { devDependencies: ["**/*.test.ts"] }, ], "import/no-unresolved": 0, "import/prefer-default-export": 0, "keyword-spacing": "error", "max-classes-per-file": 0, "max-len": 0, "no-await-in-loop": 0, "no-bitwise": 0, "no-console": 0, "no-restricted-syntax": 0, "no-shadow": 0, "no-continue": 0, "no-void": 0, "no-underscore-dangle": 0, "no-use-before-define": 0, "no-useless-constructor": 0, "no-return-await": 0, "consistent-return": 0, "no-else-return": 0, "func-names": 0, "no-lonely-if": 0, "prefer-rest-params": 0, "new-cap": ["error", { properties: false, capIsNew: false }], }, overrides: [ { files: ['**/*.test.ts'], rules: { '@typescript-eslint/no-unused-vars': 'off' } } ] };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/langchain.config.js
import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; /** * @param {string} relativePath * @returns {string} */ function abs(relativePath) { return resolve(dirname(fileURLToPath(import.meta.url)), relativePath); } export const config = { internals: [/node\:/, /@langchain\/core\//], entrypoints: { index: "index", }, tsConfigPath: resolve("./tsconfig.json"), cjsSource: "./dist-cjs", cjsDestination: "./dist", abs, }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/package.json
{ "name": "@langchain/pinecone", "version": "0.1.3", "description": "LangChain integration for Pinecone's vector database", "type": "module", "engines": { "node": ">=18" }, "main": "./index.js", "types": "./index.d.ts", "repository": { "type": "git", "url": "git@github.com:langchain-ai/langchainjs.git" }, "homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-pinecone/", "scripts": { "build": "yarn turbo:command build:internal --filter=@langchain/pinecone", "build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking", "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/", "lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts", "lint": "yarn lint:eslint && yarn lint:dpdm", "lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm", "clean": "rm -rf .turbo dist/", "prepack": "yarn build", "test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%", "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts", "test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000", "test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%", "format": "prettier --config .prettierrc --write \"src\"", "format:check": "prettier --config .prettierrc --check \"src\"" }, "author": "Pinecone, Inc", "license": "MIT", "dependencies": { "@pinecone-database/pinecone": "^4.0.0", "flat": "^5.0.2", "uuid": "^10.0.0" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" }, "devDependencies": { "@faker-js/faker": "^8.3.1", "@jest/globals": "^29.5.0", "@langchain/core": "workspace:*", "@langchain/openai": "workspace:*", "@langchain/scripts": ">=0.1.0 <0.2.0", "@swc/core": "^1.3.90", "@swc/jest": "^0.2.29", "@tsconfig/recommended": "^1.0.3", "@typescript-eslint/eslint-plugin": "^6.12.0", "@typescript-eslint/parser": "^6.12.0", "dotenv": "^16.3.1", "dpdm": "^3.12.0", "eslint": "^8.33.0", "eslint-config-airbnb-base": "^15.0.0", "eslint-config-prettier": "^8.6.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-no-instanceof": "^1.0.1", "eslint-plugin-prettier": "^4.2.1", "jest": "^29.5.0", "jest-environment-node": "^29.6.4", "langchain": "workspace:*", "prettier": "^2.8.3", "release-it": "^17.6.0", "rollup": "^4.5.2", "ts-jest": "^29.1.0", "typescript": "<5.2.0" }, "publishConfig": { "access": "public" }, "exports": { ".": { "types": { "import": "./index.d.ts", "require": "./index.d.cts", "default": "./index.d.ts" }, "import": "./index.js", "require": "./index.cjs" }, "./package.json": "./package.json" }, "files": [ "dist/", "index.cjs", "index.js", "index.d.ts", "index.d.cts" ] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/tsconfig.cjs.json
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "declaration": false }, "exclude": ["node_modules", "dist", "docs", "**/tests"] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/turbo.json
{ "extends": ["//"], "pipeline": { "build": { "outputs": ["**/dist/**"] }, "build:internal": { "dependsOn": ["^build:internal"] } } }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-pinecone/.prettierrc
{ "$schema": "https://json.schemastore.org/prettierrc", "printWidth": 80, "tabWidth": 2, "useTabs": false, "semi": true, "singleQuote": false, "quoteProps": "as-needed", "jsxSingleQuote": false, "trailingComma": "es5", "bracketSpacing": true, "arrowParens": "always", "requirePragma": false, "insertPragma": false, "proseWrap": "preserve", "htmlWhitespaceSensitivity": "css", "vueIndentScriptAndStyle": false, "endOfLine": "lf" }
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/src/vectorstores.ts
import * as uuid from "uuid"; import flatten from "flat"; import { RecordMetadata, PineconeRecord, Index as PineconeIndex, ScoredPineconeRecord, } from "@pinecone-database/pinecone"; import type { EmbeddingsInterface } from "@langchain/core/embeddings"; import { VectorStore, type MaxMarginalRelevanceSearchOptions, } from "@langchain/core/vectorstores"; import { Document, type DocumentInterface } from "@langchain/core/documents"; import { AsyncCaller, AsyncCallerParams, } from "@langchain/core/utils/async_caller"; import { chunkArray } from "@langchain/core/utils/chunk_array"; import { maximalMarginalRelevance } from "@langchain/core/utils/math"; // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any type PineconeMetadata = Record<string, any>; type HTTPHeaders = { [key: string]: string; }; /** * Database config for your vectorstore. */ export interface PineconeStoreParams extends AsyncCallerParams { /** * The Pinecone index to use. * Either this or pineconeConfig must be provided. */ pineconeIndex?: PineconeIndex; textKey?: string; namespace?: string; filter?: PineconeMetadata; /** * Configuration for the Pinecone index. * Either this or pineconeIndex must be provided. */ pineconeConfig?: { indexName: ConstructorParameters<typeof PineconeIndex>[0]; config: ConstructorParameters<typeof PineconeIndex>[1]; namespace?: string; indexHostUrl?: string; additionalHeaders?: HTTPHeaders; }; } /** * Type that defines the parameters for the delete operation in the * PineconeStore class. It includes ids, filter, deleteAll flag, and namespace. */ export type PineconeDeleteParams = { ids?: string[]; deleteAll?: boolean; filter?: object; namespace?: string; }; /** * Pinecone vector store integration. * * Setup: * Install `@langchain/pinecone` and `@pinecone-database/pinecone` to pass a client in. * * ```bash * npm install @langchain/pinecone @pinecone-database/pinecone * ``` * * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_pinecone.PineconeStore.html#constructor) * * <details open> * <summary><strong>Instantiate</strong></summary> * * ```typescript * import { PineconeStore } from '@langchain/pinecone'; * // Or other embeddings * import { OpenAIEmbeddings } from '@langchain/openai'; * * import { Pinecone as PineconeClient } from "@pinecone-database/pinecone"; * * const pinecone = new PineconeClient(); * * // Will automatically read the PINECONE_API_KEY env var * const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX!); * * const embeddings = new OpenAIEmbeddings({ * model: "text-embedding-3-small", * }); * * const vectorStore = await PineconeStore.fromExistingIndex(embeddings, { * pineconeIndex, * // Maximum number of batch requests to allow at once. Each batch is 1000 vectors. * maxConcurrency: 5, * // You can pass a namespace here too * // namespace: "foo", * }); * ``` * </details> * * <br /> * * <details> * <summary><strong>Add documents</strong></summary> * * ```typescript * import type { Document } from '@langchain/core/documents'; * * const document1 = { pageContent: "foo", metadata: { baz: "bar" } }; * const document2 = { pageContent: "thud", metadata: { bar: "baz" } }; * const document3 = { pageContent: "i will be deleted :(", metadata: {} }; * * const documents: Document[] = [document1, document2, document3]; * const ids = ["1", "2", "3"]; * await vectorStore.addDocuments(documents, { ids }); * ``` * </details> * * <br /> * * <details> * <summary><strong>Delete documents</strong></summary> * * ```typescript * await vectorStore.delete({ ids: ["3"] }); * ``` * </details> * * <br /> * * <details> * <summary><strong>Similarity search</strong></summary> * * ```typescript * const results = await vectorStore.similaritySearch("thud", 1); * for (const doc of results) { * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`); * } * // Output: * thud [{"baz":"bar"}] * ``` * </details> * * <br /> * * * <details> * <summary><strong>Similarity search with filter</strong></summary> * * ```typescript * const resultsWithFilter = await vectorStore.similaritySearch("thud", 1, { baz: "bar" }); * * for (const doc of resultsWithFilter) { * console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`); * } * // Output: * foo [{"baz":"bar"}] * ``` * </details> * * <br /> * * * <details> * <summary><strong>Similarity search with score</strong></summary> * * ```typescript * const resultsWithScore = await vectorStore.similaritySearchWithScore("qux", 1); * for (const [doc, score] of resultsWithScore) { * console.log(`* [SIM=${score.toFixed(6)}] ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`); * } * // Output: * [SIM=0.000000] qux [{"bar":"baz","baz":"bar"}] * ``` * </details> * * <br /> * * <details> * <summary><strong>As a retriever</strong></summary> * * ```typescript * const retriever = vectorStore.asRetriever({ * searchType: "mmr", // Leave blank for standard similarity search * k: 1, * }); * const resultAsRetriever = await retriever.invoke("thud"); * console.log(resultAsRetriever); * * // Output: [Document({ metadata: { "baz":"bar" }, pageContent: "thud" })] * ``` * </details> * * <br /> */ export class PineconeStore extends VectorStore { declare FilterType: PineconeMetadata; textKey: string; namespace?: string; pineconeIndex: PineconeIndex; filter?: PineconeMetadata; caller: AsyncCaller; _vectorstoreType(): string { return "pinecone"; } constructor(embeddings: EmbeddingsInterface, params: PineconeStoreParams) { super(embeddings, params); this.embeddings = embeddings; const { namespace, pineconeIndex, textKey, filter, pineconeConfig, ...asyncCallerArgs } = params; this.namespace = namespace; if (!pineconeIndex && !pineconeConfig) { throw new Error("pineconeConfig or pineconeIndex must be provided."); } if (pineconeIndex && pineconeConfig) { throw new Error( "Only one of pineconeConfig or pineconeIndex can be provided." ); } if (pineconeIndex) { this.pineconeIndex = pineconeIndex; } else if (pineconeConfig) { this.pineconeIndex = new PineconeIndex( pineconeConfig.indexName, { ...pineconeConfig.config, sourceTag: "langchainjs", }, pineconeConfig.namespace, pineconeConfig.indexHostUrl, pineconeConfig.additionalHeaders ); } this.textKey = textKey ?? "text"; this.filter = filter; this.caller = new AsyncCaller(asyncCallerArgs); } /** * Method that adds documents to the Pinecone database. * * @param documents Array of documents to add to the Pinecone database. * @param options Optional ids for the documents. * @returns Promise that resolves with the ids of the added documents. */ async addDocuments( documents: Document[], options?: { ids?: string[]; namespace?: string } | string[] ): Promise<string[]> { const texts = documents.map(({ pageContent }) => pageContent); return this.addVectors( await this.embeddings.embedDocuments(texts), documents, options ); } /** * Method that adds vectors to the Pinecone database. * * @param vectors Array of vectors to add to the Pinecone database. * @param documents Array of documents associated with the vectors. * @param options Optional ids for the vectors. * @returns Promise that resolves with the ids of the added vectors. */ async addVectors( vectors: number[][], documents: Document[], options?: { ids?: string[]; namespace?: string } | string[] ) { const ids = Array.isArray(options) ? options : options?.ids; const documentIds = ids == null ? documents.map(() => uuid.v4()) : ids; const pineconeVectors = vectors.map((values, idx) => { // Pinecone doesn't support nested objects, so we flatten them const documentMetadata = { ...documents[idx].metadata }; // preserve string arrays which are allowed const stringArrays: Record<string, string[]> = {}; for (const key of Object.keys(documentMetadata)) { if ( Array.isArray(documentMetadata[key]) && // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any documentMetadata[key].every((el: any) => typeof el === "string") ) { stringArrays[key] = documentMetadata[key]; delete documentMetadata[key]; } } const metadata: { [key: string]: string | number | boolean | string[] | null; } = { ...flatten(documentMetadata), ...stringArrays, [this.textKey]: documents[idx].pageContent, }; // Pinecone doesn't support null values, so we remove them for (const key of Object.keys(metadata)) { if (metadata[key] == null) { delete metadata[key]; } else if ( typeof metadata[key] === "object" && Object.keys(metadata[key] as unknown as object).length === 0 ) { delete metadata[key]; } } return { id: documentIds[idx], metadata, values, } as PineconeRecord<RecordMetadata>; }); const optionsNamespace = !Array.isArray(options) && options?.namespace ? options.namespace : this.namespace; const namespace = this.pineconeIndex.namespace(optionsNamespace ?? ""); // Pinecone recommends a limit of 100 vectors per upsert request const chunkSize = 100; const chunkedVectors = chunkArray(pineconeVectors, chunkSize); const batchRequests = chunkedVectors.map((chunk) => this.caller.call(async () => namespace.upsert(chunk)) ); await Promise.all(batchRequests); return documentIds; } /** * Method that deletes vectors from the Pinecone database. * @param params Parameters for the delete operation. * @returns Promise that resolves when the delete operation is complete. */ async delete(params: PineconeDeleteParams): Promise<void> { const { deleteAll, ids, filter } = params; const optionsNamespace = params.namespace ?? this.namespace; const namespace = this.pineconeIndex.namespace(optionsNamespace ?? ""); if (deleteAll) { await namespace.deleteAll(); } else if (ids) { const batchSize = 1000; for (let i = 0; i < ids.length; i += batchSize) { const batchIds = ids.slice(i, i + batchSize); await namespace.deleteMany(batchIds); } } else if (filter) { await namespace.deleteMany(filter); } else { throw new Error("Either ids or delete_all must be provided."); } } protected async _runPineconeQuery( query: number[], k: number, filter?: PineconeMetadata, options?: { includeValues: boolean } ) { if (filter && this.filter) { throw new Error("cannot provide both `filter` and `this.filter`"); } const _filter = filter ?? this.filter; let optionsNamespace = this.namespace ?? ""; if (_filter && "namespace" in _filter) { optionsNamespace = _filter.namespace; delete _filter.namespace; } const namespace = this.pineconeIndex.namespace(optionsNamespace ?? ""); const results = await namespace.query({ includeMetadata: true, topK: k, vector: query, filter: _filter, ...options, }); return results; } /** * Format the matching results from the Pinecone query. * @param matches Matching results from the Pinecone query. * @returns An array of arrays, where each inner array contains a document and its score. */ private _formatMatches( matches: ScoredPineconeRecord<RecordMetadata>[] = [] ): [Document, number][] { const documentsWithScores: [Document, number][] = []; for (const record of matches) { const { id, score, metadata: { [this.textKey]: pageContent, ...metadata } = { [this.textKey]: "", }, } = record; if (score) { documentsWithScores.push([ new Document({ id, pageContent: pageContent?.toString() ?? "", metadata, }), score, ]); } } return documentsWithScores; } /** * Method that performs a similarity search in the Pinecone database and * returns the results along with their scores. * @param query Query vector for the similarity search. * @param k Number of top results to return. * @param filter Optional filter to apply to the search. * @returns Promise that resolves with an array of documents and their scores. */ async similaritySearchVectorWithScore( query: number[], k: number, filter?: PineconeMetadata ): Promise<[Document, number][]> { const { matches = [] } = await this._runPineconeQuery(query, k, filter); const records = this._formatMatches(matches); return records; } /** * 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=20 - Number of documents to fetch before passing to the MMR algorithm. * @param {number} options.lambda=0.5 - 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 {PineconeMetadata} options.filter - Optional filter to apply to the search. * * @returns {Promise<DocumentInterface[]>} - List of documents selected by maximal marginal relevance. */ async maxMarginalRelevanceSearch( query: string, options: MaxMarginalRelevanceSearchOptions<this["FilterType"]> ): Promise<DocumentInterface[]> { const queryEmbedding = await this.embeddings.embedQuery(query); const results = await this._runPineconeQuery( queryEmbedding, options.fetchK ?? 20, options.filter, { includeValues: true } ); const { matches = [] } = results; const embeddingList = matches.map((match) => match.values); const mmrIndexes = maximalMarginalRelevance( queryEmbedding, embeddingList, options.lambda, options.k ); const topMmrMatches = mmrIndexes.map((idx) => matches[idx]); const records = this._formatMatches(topMmrMatches); return records.map(([doc, _score]) => doc); } /** * Static method that creates a new instance of the PineconeStore class * from texts. * @param texts Array of texts to add to the Pinecone database. * @param metadatas Metadata associated with the texts. * @param embeddings Embeddings to use for the texts. * @param dbConfig Configuration for the Pinecone database. * @returns Promise that resolves with a new instance of the PineconeStore class. */ static async fromTexts( texts: string[], metadatas: object[] | object, embeddings: EmbeddingsInterface, dbConfig: | { pineconeIndex: PineconeIndex; textKey?: string; namespace?: string | undefined; } | PineconeStoreParams ): Promise<PineconeStore> { const docs: Document[] = []; for (let i = 0; i < texts.length; i += 1) { const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; const newDoc = new Document({ pageContent: texts[i], metadata, }); docs.push(newDoc); } const args: PineconeStoreParams = { pineconeIndex: dbConfig.pineconeIndex, textKey: dbConfig.textKey, namespace: dbConfig.namespace, }; return PineconeStore.fromDocuments(docs, embeddings, args); } /** * Static method that creates a new instance of the PineconeStore class * from documents. * @param docs Array of documents to add to the Pinecone database. * @param embeddings Embeddings to use for the documents. * @param dbConfig Configuration for the Pinecone database. * @returns Promise that resolves with a new instance of the PineconeStore class. */ static async fromDocuments( docs: Document[], embeddings: EmbeddingsInterface, dbConfig: PineconeStoreParams ): Promise<PineconeStore> { const args = dbConfig; args.textKey = dbConfig.textKey ?? "text"; const instance = new this(embeddings, args); await instance.addDocuments(docs); return instance; } /** * Static method that creates a new instance of the PineconeStore class * from an existing index. * @param embeddings Embeddings to use for the documents. * @param dbConfig Configuration for the Pinecone database. * @returns Promise that resolves with a new instance of the PineconeStore class. */ static async fromExistingIndex( embeddings: EmbeddingsInterface, dbConfig: PineconeStoreParams ): Promise<PineconeStore> { const instance = new this(embeddings, dbConfig); return instance; } }
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/src/client.ts
import { Pinecone, PineconeConfiguration } from "@pinecone-database/pinecone"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; export function getPineconeClient(config?: PineconeConfiguration): Pinecone { if ( getEnvironmentVariable("PINECONE_API_KEY") === undefined || getEnvironmentVariable("PINECONE_API_KEY") === "" ) { throw new Error("PINECONE_API_KEY must be set in environment"); } if (!config) { return new Pinecone(); } else { return new Pinecone(config); } }
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/src/index.ts
export * from "./vectorstores.js"; export * from "./translator.js"; export * from "./embeddings.js";
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/src/embeddings.ts
/* eslint-disable arrow-body-style */ import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings"; import { EmbeddingsList, Pinecone, PineconeConfiguration, } from "@pinecone-database/pinecone"; import { getPineconeClient } from "./client.js"; /* PineconeEmbeddingsParams holds the optional fields a user can pass to a Pinecone embedding model. * @param model - Model to use to generate embeddings. Default is "multilingual-e5-large". * @param params - Additional parameters to pass to the embedding model. Note: parameters are model-specific. Read * more about model-specific parameters in the [Pinecone * documentation](https://docs.pinecone.io/guides/inference/understanding-inference#model-specific-parameters). * */ export interface PineconeEmbeddingsParams extends EmbeddingsParams { model?: string; // Model to use to generate embeddings params?: Record<string, string>; // Additional parameters to pass to the embedding model } /* PineconeEmbeddings generates embeddings using the Pinecone Inference API. */ export class PineconeEmbeddings extends Embeddings implements PineconeEmbeddingsParams { client: Pinecone; model: string; params: Record<string, string>; constructor( fields?: Partial<PineconeEmbeddingsParams> & Partial<PineconeConfiguration> ) { const defaultFields = { maxRetries: 3, ...fields }; super(defaultFields); if (defaultFields.apiKey) { const config = { apiKey: defaultFields.apiKey, controllerHostUrl: defaultFields.controllerHostUrl, fetchApi: defaultFields.fetchApi, additionalHeaders: defaultFields.additionalHeaders, sourceTag: defaultFields.sourceTag, } as PineconeConfiguration; this.client = getPineconeClient(config); } else { this.client = getPineconeClient(); } if (!defaultFields.model) { this.model = "multilingual-e5-large"; } else { this.model = defaultFields.model; } const defaultParams = { inputType: "passage" }; if (defaultFields.params) { this.params = { ...defaultFields.params, ...defaultParams }; } else { this.params = defaultParams; } } /* Generate embeddings for a list of input strings using a specified embedding model. * * @param texts - List of input strings for which to generate embeddings. * */ async embedDocuments(texts: string[]): Promise<number[][]> { if (texts.length === 0) { throw new Error( "At least one document is required to generate embeddings" ); } let embeddings; if (this.params) { embeddings = await this.caller.call(async () => { const result: EmbeddingsList = await this.client.inference.embed( this.model, texts, this.params ); return result; }); } else { embeddings = await this.caller.call(async () => { const result: EmbeddingsList = await this.client.inference.embed( this.model, texts, {} ); return result; }); } const embeddingsList: number[][] = []; for (let i = 0; i < embeddings.length; i += 1) { if (embeddings[i].values) { embeddingsList.push(embeddings[i].values as number[]); } } return embeddingsList; } /* Generate embeddings for a given query string using a specified embedding model. * @param text - Query string for which to generate embeddings. * */ async embedQuery(text: string): Promise<number[]> { // Change inputType to query-specific param for multilingual-e5-large embedding model this.params.inputType = "query"; if (!text) { throw new Error("No query passed for which to generate embeddings"); } let embeddings: EmbeddingsList; if (this.params) { embeddings = await this.caller.call(async () => { return await this.client.inference.embed( this.model, [text], this.params ); }); } else { embeddings = await this.caller.call(async () => { return await this.client.inference.embed(this.model, [text], {}); }); } if (embeddings[0].values) { return embeddings[0].values as number[]; } else { return []; } } }
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/src/translator.ts
import type { VectorStoreInterface } from "@langchain/core/vectorstores"; import { BasicTranslator, Comparators, Operators, } from "@langchain/core/structured_query"; /** * Specialized translator class that extends the BasicTranslator. It is * designed to work with PineconeStore, a type of vector store in * LangChain. The class is initialized with a set of allowed operators and * comparators, which are used in the translation process to construct * queries and compare results. * @example * ```typescript * const selfQueryRetriever = SelfQueryRetriever.fromLLM({ * llm: new ChatOpenAI(), * vectorStore: new PineconeStore(), * documentContents: "Brief summary of a movie", * attributeInfo: [], * structuredQueryTranslator: new PineconeTranslator(), * }); * * const queryResult = await selfQueryRetriever.getRelevantDocuments( * "Which movies are directed by Greta Gerwig?", * ); * ``` */ export class PineconeTranslator< T extends VectorStoreInterface > extends BasicTranslator<T> { constructor() { super({ allowedOperators: [Operators.and, Operators.or], allowedComparators: [ Comparators.eq, Comparators.ne, Comparators.gt, Comparators.gte, Comparators.lt, Comparators.lte, ], }); } }
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/translator.int.test.ts
/* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable no-promise-executor-return */ import { test } from "@jest/globals"; import { Document } from "@langchain/core/documents"; import { OpenAIEmbeddings, OpenAI } from "@langchain/openai"; import { AttributeInfo } from "langchain/chains/query_constructor"; import { SelfQueryRetriever } from "langchain/retrievers/self_query"; import { PineconeStore } from "../vectorstores.js"; import { PineconeTranslator } from "../translator.js"; describe("Pinecone self query", () => { const testIndexName = process.env.PINECONE_INDEX!; test("Pinecone Store Self Query Retriever Test With Default Filter Or Merge Operator", async () => { const docs = [ new Document({ pageContent: "A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata: { year: 1993, rating: 7.7, genre: "science fiction", type: "movie", }, }), new Document({ pageContent: "Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata: { year: 2010, director: "Christopher Nolan", rating: 8.2, type: "movie", }, }), new Document({ pageContent: "A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata: { year: 2006, director: "Satoshi Kon", rating: 8.6, type: "movie", }, }), new Document({ pageContent: "A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata: { year: 2019, director: "Greta Gerwig", rating: 8.3, type: "movie", }, }), new Document({ pageContent: "Toys come alive and have a blast doing so", metadata: { year: 1995, genre: "animated", type: "movie" }, }), new Document({ pageContent: "Three men walk into the Zone, three men walk out of the Zone", metadata: { year: 1979, director: "Andrei Tarkovsky", genre: "science fiction", rating: 9.9, type: "movie", }, }), new Document({ pageContent: "10x the previous gecs", metadata: { year: 2023, title: "10000 gecs", artist: "100 gecs", rating: 9.9, type: "album", }, }), ]; const attributeInfo: AttributeInfo[] = [ { name: "genre", description: "The genre of the movie", type: "string or array of strings", }, { name: "year", description: "The year the movie was released", type: "number", }, { name: "director", description: "The director of the movie", type: "string", }, { name: "rating", description: "The rating of the movie (1-10)", type: "number", }, { name: "length", description: "The length of the movie in minutes", type: "number", }, ]; if (!process.env.PINECONE_API_KEY || !testIndexName) { throw new Error("PINECONE_API_KEY and PINECONE_INDEX must be set"); } const embeddings = new OpenAIEmbeddings(); const llm = new OpenAI({ model: "gpt-3.5-turbo-instruct", temperature: 0 }); const documentContents = "Brief summary of a movie"; const vectorStore = await PineconeStore.fromDocuments(docs, embeddings, { pineconeConfig: { indexName: testIndexName, config: { apiKey: process.env.PINECONE_API_KEY!, }, }, }); const selfQueryRetriever = SelfQueryRetriever.fromLLM({ llm, vectorStore, documentContents, attributeInfo, structuredQueryTranslator: new PineconeTranslator(), searchParams: { filter: { type: "movie", }, mergeFiltersOperator: "or", }, }); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query1 = await selfQueryRetriever.getRelevantDocuments( "Which movies are less than 90 minutes?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query2 = await selfQueryRetriever.getRelevantDocuments( "Which movies are rated higher than 8.5?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query3 = await selfQueryRetriever.getRelevantDocuments( "Which movies are directed by Greta Gerwig?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query4 = await selfQueryRetriever.getRelevantDocuments( "Which movies are either comedy or drama and are less than 90 minutes?" ); const query5 = await selfQueryRetriever.getRelevantDocuments( "Awawawawa hello hello hello huh where am i?" ); // console.log(query1, query2, query3, query4, query5); // query 5 should return documents expect(query5.length).toBeGreaterThan(0); }); test("Pinecone Store Self Query Retriever Test With Default Filter And Merge Operator With Force Default Filter", async () => { const docs = [ new Document({ pageContent: "A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata: { year: 1993, rating: 7.7, genre: "science fiction", type: "movie", }, }), new Document({ pageContent: "Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata: { year: 2010, director: "Christopher Nolan", rating: 8.2, type: "movie", }, }), new Document({ pageContent: "A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata: { year: 2006, director: "Satoshi Kon", rating: 8.6, type: "movie", }, }), new Document({ pageContent: "A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata: { year: 2019, director: "Greta Gerwig", rating: 8.3, type: "movie", }, }), new Document({ pageContent: "Toys come alive and have a blast doing so", metadata: { year: 1995, genre: "animated", type: "movie" }, }), new Document({ pageContent: "Three men walk into the Zone, three men walk out of the Zone", metadata: { year: 1979, director: "Andrei Tarkovsky", genre: "science fiction", rating: 9.9, type: "movie", }, }), new Document({ pageContent: "10x the previous gecs", metadata: { year: 2023, title: "10000 gecs", artist: "100 gecs", rating: 9.9, type: "album", }, }), ]; const attributeInfo: AttributeInfo[] = [ { name: "genre", description: "The genre of the movie", type: "string or array of strings", }, { name: "year", description: "The year the movie was released", type: "number", }, { name: "director", description: "The director of the movie", type: "string", }, { name: "rating", description: "The rating of the movie (1-10)", type: "number", }, { name: "length", description: "The length of the movie in minutes", type: "number", }, ]; if (!process.env.PINECONE_API_KEY || !testIndexName) { throw new Error("PINECONE_API_KEY and PINECONE_INDEX must be set"); } const embeddings = new OpenAIEmbeddings(); const llm = new OpenAI({ model: "gpt-3.5-turbo-instruct", temperature: 0 }); const documentContents = "Brief summary of a movie"; const vectorStore = await PineconeStore.fromDocuments(docs, embeddings, { pineconeConfig: { indexName: testIndexName, config: { apiKey: process.env.PINECONE_API_KEY!, }, }, }); const selfQueryRetriever = SelfQueryRetriever.fromLLM({ llm, vectorStore, documentContents, attributeInfo, structuredQueryTranslator: new PineconeTranslator(), searchParams: { filter: { type: "movie", }, mergeFiltersOperator: "and", forceDefaultFilter: true, }, }); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query1 = await selfQueryRetriever.getRelevantDocuments( "Which movies are less than 90 minutes?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query2 = await selfQueryRetriever.getRelevantDocuments( "Which movies are rated higher than 8.5?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query3 = await selfQueryRetriever.getRelevantDocuments( "Which movies are directed by Greta Gerwig?" ); // @eslint-disable-next-line/@typescript-eslint/ban-ts-comment // @ts-expect-error unused var const query4 = await selfQueryRetriever.getRelevantDocuments( "Which movies are either comedy or drama and are less than 90 minutes?" ); const query5 = await selfQueryRetriever.getRelevantDocuments( "Awawawawa hello hello hello huh where am i?" ); // console.log(query1, query2, query3, query4, query5); // query 5 should return documents expect(query5.length).toBeGreaterThan(0); }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/client.test.ts
import { getPineconeClient } from "../client.js"; describe("Tests for getPineconeClient", () => { test("Confirm getPineconeClient throws error when PINECONE_API_KEY is not set", async () => { /* eslint-disable-next-line no-process-env */ process.env.PINECONE_API_KEY = ""; const errorThrown = async () => { getPineconeClient(); }; await expect(errorThrown).rejects.toThrow(Error); await expect(errorThrown).rejects.toThrow( "PINECONE_API_KEY must be set in environment" ); }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/client.int.test.ts
import { Pinecone } from "@pinecone-database/pinecone"; import { getPineconeClient } from "../client.js"; describe("Tests for getPineconeClient", () => { test("Happy path for getPineconeClient with and without `config` obj passed", async () => { const client = getPineconeClient(); expect(client).toBeInstanceOf(Pinecone); expect(client).toHaveProperty("config"); // Config is always set to *at least* the user's api key const clientWithConfig = getPineconeClient({ // eslint-disable-next-line no-process-env apiKey: process.env.PINECONE_API_KEY!, additionalHeaders: { header: "value" }, }); expect(clientWithConfig).toBeInstanceOf(Pinecone); expect(client).toHaveProperty("config"); // Unfortunately cannot assert on contents of config b/c it's a private // attribute of the Pinecone class }); test("Unhappy path: expect getPineconeClient to throw error if reset PINECONE_API_KEY to empty string", async () => { // eslint-disable-next-line no-process-env const originalApiKey = process.env.PINECONE_API_KEY; try { // eslint-disable-next-line no-process-env process.env.PINECONE_API_KEY = ""; const errorThrown = async () => { getPineconeClient(); }; await expect(errorThrown).rejects.toThrow(Error); await expect(errorThrown).rejects.toThrow( "PINECONE_API_KEY must be set in environment" ); } finally { // Restore the original value of PINECONE_API_KEY // eslint-disable-next-line no-process-env process.env.PINECONE_API_KEY = originalApiKey; } }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/embeddings.int.test.ts
import { PineconeEmbeddings } from "../embeddings.js"; describe("Integration tests for Pinecone embeddings", () => { test("Happy path: defaults for both embedDocuments and embedQuery", async () => { const model = new PineconeEmbeddings(); expect(model.model).toBe("multilingual-e5-large"); expect(model.params).toEqual({ inputType: "passage" }); const docs = ["hello", "world"]; const embeddings = await model.embedDocuments(docs); expect(embeddings.length).toBe(docs.length); const query = "hello"; const queryEmbedding = await model.embedQuery(query); expect(queryEmbedding.length).toBeGreaterThan(0); }); test("Happy path: custom `params` obj passed to embedDocuments and embedQuery", async () => { const model = new PineconeEmbeddings({ params: { customParam: "value" }, }); expect(model.model).toBe("multilingual-e5-large"); expect(model.params).toEqual({ inputType: "passage", customParam: "value", }); const docs = ["hello", "world"]; const embeddings = await model.embedDocuments(docs); expect(embeddings.length).toBe(docs.length); expect(embeddings[0].length).toBe(1024); // Assert correct dims on random doc expect(model.model).toBe("multilingual-e5-large"); expect(model.params).toEqual({ inputType: "passage", // Maintain default inputType for docs customParam: "value", }); const query = "hello"; const queryEmbedding = await model.embedQuery(query); expect(model.model).toBe("multilingual-e5-large"); expect(queryEmbedding.length).toBe(1024); expect(model.params).toEqual({ inputType: "query", // Change inputType for query customParam: "value", }); }); test("Unhappy path: embedDocuments and embedQuery throw when empty objs are passed", async () => { const model = new PineconeEmbeddings(); await expect(model.embedDocuments([])).rejects.toThrow(); await expect(model.embedQuery("")).rejects.toThrow(); }); test("Unhappy path: PineconeEmbeddings throws when invalid model is passed", async () => { const model = new PineconeEmbeddings({ model: "invalid-model" }); await expect(model.embedDocuments([])).rejects.toThrow(); await expect(model.embedQuery("")).rejects.toThrow(); }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/vectorstores.test.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { expect, jest, test } from "@jest/globals"; import { FakeEmbeddings } from "@langchain/core/utils/testing"; import { PineconeStore } from "../vectorstores.js"; test("PineconeStore with external ids", async () => { const upsert = jest.fn(); const client = { namespace: jest.fn<any>().mockReturnValue({ upsert, query: jest.fn<any>().mockResolvedValue({ matches: [], }), }), }; const embeddings = new FakeEmbeddings(); const store = new PineconeStore(embeddings, { pineconeIndex: client as any }); expect(store).toBeDefined(); await store.addDocuments( [ { pageContent: "hello", metadata: { a: 1, b: { nested: [1, { a: 4 }] }, }, }, ], ["id1"] ); expect(upsert).toHaveBeenCalledTimes(1); expect(upsert).toHaveBeenCalledWith([ { id: "id1", metadata: { a: 1, "b.nested.0": 1, "b.nested.1.a": 4, text: "hello" }, values: [0.1, 0.2, 0.3, 0.4], }, ]); const results = await store.similaritySearch("hello", 1); expect(results).toHaveLength(0); }); test("PineconeStore with generated ids", async () => { const upsert = jest.fn(); const client = { namespace: jest.fn<any>().mockReturnValue({ upsert, query: jest.fn<any>().mockResolvedValue({ matches: [], }), }), }; const embeddings = new FakeEmbeddings(); const store = new PineconeStore(embeddings, { pineconeIndex: client as any }); expect(store).toBeDefined(); await store.addDocuments([{ pageContent: "hello", metadata: { a: 1 } }]); expect(upsert).toHaveBeenCalledTimes(1); const results = await store.similaritySearch("hello", 1); expect(results).toHaveLength(0); }); test("PineconeStore with string arrays", async () => { const upsert = jest.fn(); const client = { namespace: jest.fn<any>().mockReturnValue({ upsert, query: jest.fn<any>().mockResolvedValue({ matches: [], }), }), }; const embeddings = new FakeEmbeddings(); const store = new PineconeStore(embeddings, { pineconeIndex: client as any }); await store.addDocuments( [ { pageContent: "hello", metadata: { a: 1, b: { nested: [1, { a: 4 }] }, c: ["some", "string", "array"], d: [1, { nested: 2 }, "string"], }, }, ], ["id1"] ); expect(upsert).toHaveBeenCalledWith([ { id: "id1", metadata: { a: 1, "b.nested.0": 1, "b.nested.1.a": 4, c: ["some", "string", "array"], "d.0": 1, "d.1.nested": 2, "d.2": "string", text: "hello", }, values: [0.1, 0.2, 0.3, 0.4], }, ]); }); describe("PineconeStore with null pageContent", () => { it("should handle null pageContent correctly in _formatMatches", async () => { const mockQueryResponse = { matches: [ { id: "1", score: 0.9, metadata: { textKey: null, otherKey: "value" }, }, ], }; const client = { namespace: jest.fn<any>().mockReturnValue({ query: jest.fn<any>().mockResolvedValue(mockQueryResponse), }), }; const embeddings = new FakeEmbeddings(); const store = new PineconeStore(embeddings, { pineconeIndex: client as any, }); const results = await store.similaritySearchVectorWithScore([], 0); expect(results[0][0].pageContent).toEqual(""); }); }); test("PineconeStore can instantiate without passing in client", async () => { const embeddings = new FakeEmbeddings(); const store = new PineconeStore(embeddings, { pineconeConfig: { indexName: "indexName", config: { apiKey: "apiKey", }, }, }); expect(store.pineconeIndex).toBeDefined(); }); test("PineconeStore throws when no config or index is passed", async () => { const embeddings = new FakeEmbeddings(); expect(() => new PineconeStore(embeddings, {})).toThrow(); }); test("PineconeStore throws when config and index is passed", async () => { const upsert = jest.fn(); const client = { namespace: jest.fn<any>().mockReturnValue({ upsert, query: jest.fn<any>().mockResolvedValue({ matches: [], }), }), }; const embeddings = new FakeEmbeddings(); expect( () => new PineconeStore(embeddings, { pineconeIndex: client as any, pineconeConfig: { indexName: "indexName", config: { apiKey: "apiKey", }, }, }) ).toThrow(); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/vectorstores.int.test.ts
/* eslint-disable no-process-env */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable no-promise-executor-return */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { describe, expect, test } from "@jest/globals"; import { faker } from "@faker-js/faker"; import { Pinecone } from "@pinecone-database/pinecone"; import * as uuid from "uuid"; import { SyntheticEmbeddings } from "@langchain/core/utils/testing"; import { Document } from "@langchain/core/documents"; import { PineconeStoreParams, PineconeStore } from "../vectorstores.js"; const PINECONE_SLEEP_LENGTH = 40000; function sleep(ms: number) { // eslint-disable-next-line no-promise-executor-return return new Promise((resolve) => setTimeout(resolve, ms)); } describe("PineconeStore", () => { let pineconeStore: PineconeStore; const testIndexName = process.env.PINECONE_INDEX!; let namespaces: string[] = []; beforeAll(async () => { const embeddings = new SyntheticEmbeddings({ vectorSize: 1536, }); const pinecone = new Pinecone({ apiKey: process.env.PINECONE_API_KEY!, }); const pineconeIndex = pinecone.Index(testIndexName); const pineconeArgs: PineconeStoreParams = { pineconeIndex, }; pineconeStore = new PineconeStore(embeddings, pineconeArgs); }); afterEach(async () => { if (namespaces.length) { const delAllPromise = namespaces.map((namespace) => pineconeStore.delete({ deleteAll: true, namespace }) ); await Promise.all(delAllPromise); } else { await pineconeStore.delete({ deleteAll: true }); } namespaces = []; }); test("user-provided ids", async () => { const documentId = uuid.v4(); const pageContent = faker.lorem.sentence(5); await pineconeStore.addDocuments( [{ pageContent, metadata: {} }], [documentId] ); await sleep(PINECONE_SLEEP_LENGTH); const results = await pineconeStore.similaritySearch(pageContent, 1); expect(results).toEqual([ new Document({ metadata: {}, pageContent, id: documentId }), ]); await pineconeStore.addDocuments( [{ pageContent: `${pageContent} upserted`, metadata: {} }], [documentId] ); await sleep(PINECONE_SLEEP_LENGTH); const results2 = await pineconeStore.similaritySearch(pageContent, 1); expect(results2).toEqual([ new Document({ metadata: {}, pageContent: `${pageContent} upserted`, id: documentId, }), ]); }); test("auto-generated ids", async () => { const pageContent = faker.lorem.sentence(5); await pineconeStore.addDocuments([ { pageContent, metadata: { foo: "bar" } }, ]); await sleep(PINECONE_SLEEP_LENGTH); const results = await pineconeStore.similaritySearch(pageContent, 1); expect(results).toEqual([ new Document({ metadata: { foo: "bar" }, pageContent, id: expect.any(String) as any, }), ]); }); test("metadata filtering", async () => { const pageContent = faker.lorem.sentence(5); const id = uuid.v4(); await pineconeStore.addDocuments([ { pageContent, metadata: { foo: "bar" } }, { pageContent, metadata: { foo: id } }, { pageContent, metadata: { foo: "qux" } }, ]); await sleep(PINECONE_SLEEP_LENGTH); // If the filter wasn't working, we'd get all 3 documents back const results = await pineconeStore.similaritySearch(pageContent, 3, { foo: id, }); expect(results).toEqual([ new Document({ metadata: { foo: id }, pageContent, id: expect.any(String) as any, }), ]); }); test("max marginal relevance", async () => { const pageContent = faker.lorem.sentence(5); const id = uuid.v4(); await pineconeStore.addDocuments([ { pageContent, metadata: { foo: id } }, { pageContent, metadata: { foo: id } }, { pageContent, metadata: { foo: id } }, ]); await sleep(PINECONE_SLEEP_LENGTH); // If the filter wasn't working, we'd get all 3 documents back const results = await pineconeStore.maxMarginalRelevanceSearch( pageContent, { k: 5, fetchK: 20, filter: { foo: id }, } ); expect(results.length).toEqual(3); }); test("delete by id", async () => { const pageContent = faker.lorem.sentence(5); const id = uuid.v4(); const ids = await pineconeStore.addDocuments([ { pageContent, metadata: { foo: id } }, { pageContent, metadata: { foo: id } }, ]); await sleep(PINECONE_SLEEP_LENGTH); const results = await pineconeStore.similaritySearch(pageContent, 2, { foo: id, }); expect(results.length).toEqual(2); await pineconeStore.delete({ ids: ids.slice(0, 1), }); const results2 = await pineconeStore.similaritySearch(pageContent, 2, { foo: id, }); expect(results2.length).toEqual(1); }); test("delete all", async () => { const pageContent = faker.lorem.sentence(5); const id = uuid.v4(); const id2 = uuid.v4(); await pineconeStore.addDocuments( [ { pageContent, metadata: { foo: id } }, { pageContent, metadata: { foo: id } }, ], { ids: [id, id2], } ); await sleep(PINECONE_SLEEP_LENGTH); const indexStats = await pineconeStore.pineconeIndex.describeIndexStats(); expect(indexStats.namespaces).toHaveProperty(""); expect(indexStats.namespaces?.[""].recordCount).toEqual(2); const totalRecords = indexStats.totalRecordCount ?? 0; expect(totalRecords).toBeGreaterThanOrEqual(2); await pineconeStore.delete({ deleteAll: true, }); await sleep(PINECONE_SLEEP_LENGTH); const indexStats2 = await pineconeStore.pineconeIndex.describeIndexStats(); expect(indexStats2.namespaces).not.toHaveProperty(""); // The new total records should be less than the previous total records const newTotalRecords = indexStats2.totalRecordCount ?? 0; expect(newTotalRecords).toBeLessThan(totalRecords); }); test("query based on passed namespace", async () => { const pageContent = "Can we make namespaces work!"; const id1 = uuid.v4(); const id2 = uuid.v4(); namespaces = ["test-1", "test-2"]; await pineconeStore.addDocuments( [{ pageContent, metadata: { foo: id1 } }], { namespace: namespaces[0], } ); await pineconeStore.addDocuments( [{ pageContent, metadata: { foo: id2 } }], { namespace: namespaces[1], } ); await sleep(PINECONE_SLEEP_LENGTH); const results = await pineconeStore.similaritySearch(pageContent, 1, { namespace: namespaces[0], }); expect(results.length).toEqual(1); expect(results[0].metadata.foo).toBe(id1); }); test("auto instantiated pinecone index class", async () => { const documentId = uuid.v4(); const pageContent = faker.lorem.sentence(5); const embeddings = new SyntheticEmbeddings({ vectorSize: 1536, }); const store = new PineconeStore(embeddings, { pineconeConfig: { indexName: testIndexName, config: { apiKey: process.env.PINECONE_API_KEY!, }, }, }); await store.addDocuments([{ pageContent, metadata: {} }], [documentId]); await sleep(PINECONE_SLEEP_LENGTH); const results = await store.similaritySearch(pageContent, 1); expect(results).toEqual([ new Document({ metadata: {}, pageContent, id: documentId }), ]); await store.addDocuments( [{ pageContent: `${pageContent} upserted`, metadata: {} }], [documentId] ); await sleep(PINECONE_SLEEP_LENGTH); const results2 = await store.similaritySearch(pageContent, 1); expect(results2).toEqual([ new Document({ metadata: {}, pageContent: `${pageContent} upserted`, id: documentId, }), ]); }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone/src
lc_public_repos/langchainjs/libs/langchain-pinecone/src/tests/embeddings.test.ts
import { PineconeEmbeddings } from "../embeddings.js"; beforeAll(() => { // eslint-disable-next-line no-process-env process.env.PINECONE_API_KEY = "test-api-key"; }); describe("Tests for the PineconeEmbeddings class", () => { test("Confirm embedDocuments method throws error when an empty array is passed", async () => { const model = new PineconeEmbeddings(); const errorThrown = async () => { await model.embedDocuments([]); }; await expect(errorThrown).rejects.toThrow(Error); await expect(errorThrown).rejects.toThrowError( "At least one document is required to generate embeddings" ); }); test("Confirm embedQuery method throws error when an empty string is passed", async () => { const model = new PineconeEmbeddings(); const errorThrown = async () => { await model.embedQuery(""); }; await expect(errorThrown).rejects.toThrow(Error); await expect(errorThrown).rejects.toThrowError( "No query passed for which to generate embeddings" ); }); test("Confirm instance defaults are set when no args are passed", async () => { const model = new PineconeEmbeddings(); expect(model.model).toBe("multilingual-e5-large"); expect(model.params).toEqual({ inputType: "passage" }); }); test("Confirm instance sets custom model and params when provided", () => { const customModel = new PineconeEmbeddings({ model: "custom-model", params: { customParam: "value" }, }); expect(customModel.model).toBe("custom-model"); expect(customModel.params).toEqual({ inputType: "passage", customParam: "value", }); }); });
0
lc_public_repos/langchainjs/libs/langchain-pinecone
lc_public_repos/langchainjs/libs/langchain-pinecone/scripts/jest-setup-after-env.js
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises"; import { afterAll, jest } from "@jest/globals"; afterAll(awaitAllCallbacks); // Allow console.log to be disabled in tests if (process.env.DISABLE_CONSOLE_LOGS === "true") { console.log = jest.fn(); }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/tsconfig.json
{ "extends": "@tsconfig/recommended", "compilerOptions": { "outDir": "../dist", "rootDir": "./src", "target": "ES2021", "lib": ["ES2021", "ES2022.Object", "DOM"], "module": "ES2020", "moduleResolution": "nodenext", "esModuleInterop": true, "declaration": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUnusedLocals": true, "noUnusedParameters": true, "useDefineForClassFields": true, "strictPropertyInitialization": false, "allowJs": true, "strict": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "docs"] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/LICENSE
The MIT License Copyright (c) 2023 LangChain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/jest.config.cjs
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: "ts-jest/presets/default-esm", testEnvironment: "./jest.env.cjs", modulePathIgnorePatterns: ["dist/", "docs/"], moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", }, transform: { "^.+\\.tsx?$": ["@swc/jest"], }, transformIgnorePatterns: [ "/node_modules/", "\\.pnp\\.[^\\/]+$", "./scripts/jest-setup-after-env.js", ], setupFiles: ["dotenv/config"], testTimeout: 20_000, passWithNoTests: true, };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/jest.env.cjs
const { TestEnvironment } = require("jest-environment-node"); class AdjustedTestEnvironmentToSupportFloat32Array extends TestEnvironment { constructor(config, context) { // Make `instanceof Float32Array` return true in tests // to avoid https://github.com/xenova/transformers.js/issues/57 and https://github.com/jestjs/jest/issues/2549 super(config, context); this.global.Float32Array = Float32Array; } } module.exports = AdjustedTestEnvironmentToSupportFloat32Array;
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/README.md
# @langchain/baidu-qianfan This package contains the LangChain.js integrations for Baidu Qianfan via the qianfan/sdk package. ## Installation ```bash npm2yarn npm install @langchain/baidu-qianfan @langchain/core ``` ## Chat models This package adds support for Qianfan chat model inference. Set the necessary environment variable (or pass it in via the constructor): ```bash export QIANFAN_AK="" export QIANFAN_SK="" export QIANFAN_ACCESS_KEY="" export QIANFAN_SECRET_KEY="" ``` ```typescript import { ChatBaiduQianfan } from "@langchain/baidu-qianfan"; import { HumanMessage } from "@langchain/core/messages"; const chat = new ChatBaiduQianfan({ model: 'ERNIE-Lite-8K' }); const message = new HumanMessage("北京天气"); const res = await chat.invoke([message]); ``` ```typescript import { BaiduQianfanEmbeddings } from "@langchain/baidu-qianfan"; const embeddings = new BaiduQianfanEmbeddings(); const res = await embeddings.embedQuery("Introduce the city Beijing"); ```
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/.release-it.json
{ "github": { "release": true, "autoGenerate": true, "tokenRef": "GITHUB_TOKEN_RELEASE" }, "npm": { "versionArgs": [ "--workspaces-update=false" ] } }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/.eslintrc.cjs
module.exports = { extends: [ "airbnb-base", "eslint:recommended", "prettier", "plugin:@typescript-eslint/recommended", ], parserOptions: { ecmaVersion: 12, parser: "@typescript-eslint/parser", project: "./tsconfig.json", sourceType: "module", }, plugins: ["@typescript-eslint", "no-instanceof"], ignorePatterns: [ ".eslintrc.cjs", "scripts", "node_modules", "dist", "dist-cjs", "*.js", "*.cjs", "*.d.ts", ], rules: { "no-process-env": 2, "no-instanceof/no-instanceof": 2, "@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/no-empty-function": 0, "@typescript-eslint/no-shadow": 0, "@typescript-eslint/no-empty-interface": 0, "@typescript-eslint/no-use-before-define": ["error", "nofunc"], "@typescript-eslint/no-unused-vars": ["warn", { args: "none" }], "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-misused-promises": "error", "arrow-body-style": 0, camelcase: 0, "class-methods-use-this": 0, "import/extensions": [2, "ignorePackages"], "import/no-extraneous-dependencies": [ "error", { devDependencies: ["**/*.test.ts"] }, ], "import/no-unresolved": 0, "import/prefer-default-export": 0, "keyword-spacing": "error", "max-classes-per-file": 0, "max-len": 0, "no-await-in-loop": 0, "no-bitwise": 0, "no-console": 0, "no-restricted-syntax": 0, "no-shadow": 0, "no-continue": 0, "no-void": 0, "no-underscore-dangle": 0, "no-use-before-define": 0, "no-useless-constructor": 0, "no-return-await": 0, "consistent-return": 0, "no-else-return": 0, "func-names": 0, "no-lonely-if": 0, "prefer-rest-params": 0, "new-cap": ["error", { properties: false, capIsNew: false }], }, overrides: [ { files: ['**/*.test.ts'], rules: { '@typescript-eslint/no-unused-vars': 'off' } } ] };
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/langchain.config.js
import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; /** * @param {string} relativePath * @returns {string} */ function abs(relativePath) { return resolve(dirname(fileURLToPath(import.meta.url)), relativePath); } export const config = { internals: [/node\:/, /@langchain\/core\//], entrypoints: { index: "index", }, tsConfigPath: resolve("./tsconfig.json"), cjsSource: "./dist-cjs", cjsDestination: "./dist", abs, }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/package.json
{ "name": "@langchain/baidu-qianfan", "version": "0.1.0", "description": "Baidu Qianfan integration for LangChain.js", "type": "module", "engines": { "node": ">=18" }, "main": "./index.js", "types": "./index.d.ts", "repository": { "type": "git", "url": "git@github.com:langchain-ai/langchainjs.git" }, "homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-baidu-qianfan/", "scripts": { "build": "yarn turbo:command build:internal --filter=@langchain/baidu-qianfan", "build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking", "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/", "lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts", "lint": "yarn lint:eslint && yarn lint:dpdm", "lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm", "clean": "rm -rf .turbo dist/", "prepack": "yarn build", "test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%", "test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%", "test:embeddings": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.embeddings\\.test.ts --testTimeout 100000 --maxWorkers=50%", "format": "prettier --config .prettierrc --write \"src\"", "format:check": "prettier --config .prettierrc --check \"src\"" }, "author": "LangChain", "license": "MIT", "dependencies": { "@baiducloud/qianfan": "^0.1.6", "@langchain/openai": "~0.3.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.5" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" }, "devDependencies": { "@jest/globals": "^29.5.0", "@langchain/core": "workspace:*", "@langchain/openai": "~0.3.0", "@langchain/scripts": ">=0.1.0 <0.2.0", "@swc/core": "^1.3.90", "@swc/jest": "^0.2.29", "@tsconfig/recommended": "^1.0.3", "@types/uuid": "^9", "@typescript-eslint/eslint-plugin": "^6.12.0", "@typescript-eslint/parser": "^6.12.0", "dotenv": "^16.3.1", "dpdm": "^3.12.0", "eslint": "^8.33.0", "eslint-config-airbnb-base": "^15.0.0", "eslint-config-prettier": "^8.6.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-no-instanceof": "^1.0.1", "eslint-plugin-prettier": "^4.2.1", "jest": "^29.5.0", "jest-environment-node": "^29.6.4", "prettier": "^2.8.3", "release-it": "^17.6.0", "rollup": "^4.5.2", "ts-jest": "^29.1.0", "typescript": "<5.2.0" }, "publishConfig": { "access": "public" }, "exports": { ".": { "types": { "import": "./index.d.ts", "require": "./index.d.cts", "default": "./index.d.ts" }, "import": "./index.js", "require": "./index.cjs" }, "./package.json": "./package.json" }, "files": [ "dist/", "index.cjs", "index.js", "index.d.ts", "index.d.cts" ] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/tsconfig.cjs.json
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "declaration": false }, "exclude": ["node_modules", "dist", "docs", "**/tests"] }
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/example.env
# 鉴权相关 ## AK 与 SK 分别对应于千帆平台上 **应用** 的 API Key 与 Secret Key ## 主要用于模型相关 API 鉴权 ## 获取位置:https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application # QIANFAN_AK="" # QIANFAN_SK="" ## Access Key 与 Secret Key 对应于 [百度智能云控制台-安全认证] ## 中的 Access Key 与 Secret Key ## 获取位置:https://console.bce.baidu.com/iam/#/iam/accesslist ## 主要用于非模型相关的、管控类的 API 鉴权 ## 注意与 AK 与 SK 的使用范围进行区分,详细参见文档 # QIANFAN_ACCESS_KEY="" # QIANFAN_SECRET_KEY=""
0
lc_public_repos/langchainjs/libs
lc_public_repos/langchainjs/libs/langchain-baidu-qianfan/turbo.json
{ "extends": ["//"], "pipeline": { "build": { "outputs": ["**/dist/**"] }, "build:internal": { "dependsOn": ["^build:internal"] } } }