跳到主要内容
语义缓存功能支持与 Azure Cosmos DB for NoSQL 集成,使用户能够根据用户输入与之前缓存结果之间的语义相似性检索缓存响应。它利用 AzureCosmosDBNoSQLVectorStore,该存储存储缓存提示的向量嵌入。这些嵌入支持基于相似性的搜索,允许系统检索相关的缓存结果。
如果您没有 Azure 帐户,您可以创建一个免费帐户来开始使用。

设置

您首先需要安装 @langchain/azure-cosmosdb 包。
有关安装 LangChain 软件包的一般说明,请参阅此部分
npm
npm install @langchain/azure-cosmosdb @langchain/core
您还需要运行一个 Azure Cosmos DB for NoSQL 实例。您可以按照本指南在 Azure 门户上免费部署一个版本。 一旦您的实例运行起来,请确保您有连接字符串。如果您正在使用托管标识,您需要有终结点。您可以在 Azure 门户中,在您的实例的“设置/密钥”部分下找到它们。
当使用 Azure 托管标识和基于角色的访问控制时,您必须确保数据库和容器已经提前创建。RBAC 不提供创建数据库和容器的权限。您可以在 Azure Cosmos DB 文档中获取有关权限模型的更多信息。

使用示例

import {
  AzureCosmosDBNoSQLConfig,
  AzureCosmosDBNoSQLSemanticCache,
} from "@langchain/azure-cosmosdb";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";

const embeddings = new OpenAIEmbeddings();
const config: AzureCosmosDBNoSQLConfig = {
  databaseName: "<DATABASE_NAME>",
  containerName: "<CONTAINER_NAME>",
  // use endpoint to initiate client with managed identity
  connectionString: "<CONNECTION_STRING>",
};

/**
 * Sets the threshold similarity score for returning cached results based on vector distance.
 * Cached output is returned only if the similarity score meets or exceeds this threshold;
 * otherwise, a new result is generated. Default is 0.6, adjustable via the constructor
 * to suit various distance functions and use cases.
 * (see: https://aka.ms/CosmosVectorSearch).
 */

const similarityScoreThreshold = 0.5;
const cache = new AzureCosmosDBNoSQLSemanticCache(
  embeddings,
  config,
  similarityScoreThreshold
);

const model = new ChatOpenAI({ model: "gpt-4o-mini", cache });

// Invoke the model to perform an action
const response1 = await model.invoke("Do something random!");
console.log(response1);
/*
  AIMessage {
    content: "Sure! I'll generate a random number for you: 37",
    additional_kwargs: {}
  }
*/

const response2 = await model.invoke("Do something random!");
console.log(response2);
/*
  AIMessage {
    content: "Sure! I'll generate a random number for you: 37",
    additional_kwargs: {}
  }
*/

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.