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 门户中免费部署一个实例。
当你启动实例后,请确保你已获取连接字符串。如果你使用的是托管身份(Managed Identity),则需要确保拥有终结点。你可以在 Azure 门户中实例的 "Settings / Keys" 部分找到这些信息。
info
当使用 Azure 托管身份(Managed Identity)和基于角色的访问控制(RBAC)时,你必须提前创建好数据库和容器。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: {}
}
*/
API Reference:
- AzureCosmosDBNoSQLConfig from
@langchain/azure-cosmosdb - AzureCosmosDBNoSQLSemanticCache from
@langchain/azure-cosmosdb - ChatOpenAI from
@langchain/openai - OpenAIEmbeddings from
@langchain/openai