Azure Cosmos DB NoSQL 语义缓存
语义缓存功能通过 Azure Cosmos DB for NoSQL 集成提供支持,使用户能够根据用户输入和先前缓存结果之间的语义相似性来检索缓存的响应。它利用 AzureCosmosDBNoSQLVectorStore,后者存储缓存提示的向量嵌入。这些嵌入支持基于相似性的搜索,允许系统检索相关的缓存结果。
如果您没有 Azure 帐户,您可以创建一个免费帐户以开始使用。
设置
您首先需要安装 @langchain/azure-cosmosdb
包
提示
有关安装集成包的一般说明,请参阅此部分。
- npm
- Yarn
- pnpm
npm install @langchain/azure-cosmosdb @langchain/core
yarn add @langchain/azure-cosmosdb @langchain/core
pnpm add @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({ 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: {}
}
*/
API 参考
- AzureCosmosDBNoSQLConfig 来自
@langchain/azure-cosmosdb
- AzureCosmosDBNoSQLSemanticCache 来自
@langchain/azure-cosmosdb
- ChatOpenAI 来自
@langchain/openai
- OpenAIEmbeddings 来自
@langchain/openai