我有一个简单的问题:我正在使用带有 LangChain 的 Chroma 矢量存储。
我用 Chroma.from_texts 提出了一个简单的文档搜索。我最初非常困惑,因为我认为对于接近答案的查询,similarity_score_with_score 会更高,但从我的测试看来,事实恰恰相反。这是因为它在搜索时返回两个向量之间的“距离”吗?我正在查看文档,但它只说“与查询最相似的文档列表以及每个文档的分数”,但没有解释“分数”是什么
文档参考https://python.langchain.com/en/latest/reference/modules/vectorstores.html?highlight=similarity_search#langchain.vectorstores.Annoy.similarity_search_with_score还可以提供有关我使用的(小开始)数据集的更多信息和我测试过的查询。
我正在使用 langchain 库将我公司的信息保存在矢量数据库中,当我查询信息时,结果很好,但也需要一种方法来恢复信息的来源 - 例如来源:“www.site.txt”。 com/about”或至少“文档 156”。你们有人知道该怎么做吗?
编辑:目前,我正在使用docsearch.similarity_search(query),只返回 page_content,但元数据为空
我正在吸收这段代码,但我完全愿意改变。
db = ElasticVectorSearch.from_documents(
documents,
embeddings,
elasticsearch_url="http://localhost:9200",
index_name="elastic-index",
)
Run Code Online (Sandbox Code Playgroud) 由于上下文大小有限,无法将长文档直接传递到 ChatGPT。因此,例如,乍一看不可能回答问题或总结长文档。我已经了解了 ChatGPT 原则上如何“了解”更大的上下文 - 基本上是通过从聊天历史中总结一系列先前的上下文 - 但这是否足以检测很长一段时间内的真正的远程依赖关系(带有“含义”)文本?
LangChain 似乎提供了一个解决方案,利用 OpenAI 的 API 和 矢量存储。我正在寻找一个高级描述,当 LangChain 将长文档甚至长文档语料库提供给 ChatGPT,然后通过巧妙的自动提示(例如问答或摘要)来利用 ChatGPT 的 NLP 功能时,会发生什么情况。我们假设文档已经格式化为 LangChain Document 对象。
使用 peft 和 lora微调模型 ( https://huggingface.co/decapoda-research/llama-7b-hf ) 并保存为https://huggingface.co/lucas0/empath-llama-7b。Pipeline cannot infer suitable model classes from现在,当我尝试将它与 langchain 和 chroma vectordb 一起使用时,我得到:
from langchain.embeddings import HuggingFaceHubEmbeddings
from langchain import PromptTemplate, HuggingFaceHub, LLMChain
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
from langchain.vectorstores import Chroma
repo_id = "sentence-transformers/all-mpnet-base-v2"
embedder = HuggingFaceHubEmbeddings(
repo_id=repo_id,
task="feature-extraction",
huggingfacehub_api_token="XXXXX",
)
comments = ["foo", "bar"]
embeddings = embedder.embed_documents(texts=comments)
docsearch = Chroma.from_texts(comments, embedder).as_retriever()
#docsearch = Chroma.from_documents(texts, embeddings)
llm = HuggingFaceHub(repo_id='lucas0/empath-llama-7b', huggingfacehub_api_token='XXXXX')
qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=docsearch, return_source_documents=False) …Run Code Online (Sandbox Code Playgroud) python huggingface-transformers langchain large-language-model chromadb
我正在 Langchain 和 OpenAI 中创建一个项目,除了当我尝试跟踪每个链运行的代币使用情况和成本时,一切都正常工作。
在 python 中,Langchain.py 的 Callback 部分中有一个方法 get_openai_callback() ,但我在 JS 框架上找不到等效的方法。
Langchain 聊天机器人给了我正确的答案。它只是给了我 JS 框架中不存在的功能。
有谁知道如何跟踪每次链运行中的代币使用情况和产生的成本?欢迎任何帮助。
PD。我将 ConversationalRetrievalQAChain 与 BufferMemory 和矢量搜索结合使用。
我尝试使用 langchain 聊天机器人给我的这段代码
const { Chain } = require("langchain");
async function getChainRunCost(chainRunId) {
const chain = new Chain();
const callback = await chain.getOpenAICallback(chainRunId);
const cost = callback.cost;
return cost;
}
// Usage
const chainRunId = "your-chain-run-id";
const cost = await getChainRunCost(chainRunId);
console.log(cost);
Run Code Online (Sandbox Code Playgroud)
但框架中不存在这个功能:
const callback = await chain.getOpenAICallback(chainRunId);
有没有真正的方法可以在每次链运行中返还成本?
我正在尝试LangChain的AgentType.CHAT_ZERO_SHOT_REACT代理。从它的名字来看,我认为这是一个用于聊天的代理,我已经给了它内存,但它似乎无法访问它的内存。我还需要做什么才能访问它的内存?或者我是否错误地认为该代理可以处理聊天?
这是我的代码和示例输出:
llm = ChatOpenAI(model_name="gpt-4",
temperature=0)
tools = load_tools(["llm-math", "wolfram-alpha", "wikipedia"], llm=llm)
memory = ConversationBufferMemory(memory_key="chat_history")
agent_test = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
memory=memory,
verbose=True
)
Run Code Online (Sandbox Code Playgroud)
>>> agent_test.run("What is the height of the empire state building?")
'The Empire State Building stands a total of 1,454 feet tall, including its antenna.'
>>> agent_test.run("What was the last question I asked?")
"I'm sorry, but I can't provide the information you're looking for."
Run Code Online (Sandbox Code Playgroud) 我想创建一个基于langchain. 在对话的第一条消息中,我想传递初始上下文。
有什么方法可以做到呢?我正在努力解决这个问题,因为从我看来,我可以使用提示模板。从他们的例子来看:
template = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
{history}
Human: {input}
AI Assistant:"""
PROMPT = PromptTemplate(input_variables=["history", "input"], template=template)
conversation = ConversationChain(
prompt=PROMPT,
llm=llm,
verbose=True,
memory=ConversationBufferMemory(ai_prefix="AI Assistant"),
)
Run Code Online (Sandbox Code Playgroud)
但问题是,我处理模型的常用方法是使用SystemMessage,它为机器人提供了上下文和指导。我不确定此模板是否是langchain处理系统消息的推荐方法。如果不是,能否请您说明正确的方法?
from langchain.document_loaders import TextLoader
# Create the TextLoader object using the file path
Loader = tl('data.txt')
Run Code Online (Sandbox Code Playgroud)
我想使用带有字符串的 langchain 而不是 txt 文件,这可能吗?
def get_response(query):
#print(query)
result = index.query(query)
result = str(result)
Run Code Online (Sandbox Code Playgroud) 如LangChain 快速入门所示,我正在尝试以下 Python 代码:
from langchain.prompts.chat import ChatPromptTemplate
template = "You are a helpful assistant that translates {input_language} to {output_language}."
human_template = "{text}"
chat_prompt = ChatPromptTemplate.from_messages([
("system", template),
("human", human_template),
])
chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")
Run Code Online (Sandbox Code Playgroud)
但是当我运行上面的代码时,出现以下错误:
Traceback (most recent call last):
File "/home/yser364/Projets/SinappsIrdOpenaiQA/promptWorkout.py", line 6, in <module>
chat_prompt = ChatPromptTemplate.from_messages([
File "/home/yser364/.local/lib/python3.10/site-packages/langchain/prompts/chat.py", line 220, in from_messages
return cls(input_variables=list(input_vars), messages=messages)
File "/home/yser364/.local/lib/python3.10/site-packages/langchain/load/serializable.py", line 64, in __init__
super().__init__(**kwargs)
File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 4 validation errors for ChatPromptTemplate …Run Code Online (Sandbox Code Playgroud) import os
from langchain.llms import OpenAI
import bs4
import langchain
from langchain import hub
from langchain.document_loaders import UnstructuredFileLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
os.environ["OPENAI_API_KEY"] = "KEY"
loader = UnstructuredFileLoader(
'path_to_file'
)
docs = loader.load()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000, chunk_overlap=200, add_start_index=True
)
all_splits = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 6})
retrieved_docs = retriever.get_relevant_documents(
"What is X?"
)
Run Code Online (Sandbox Code Playgroud)
这将返回:
[Document(page_content="...", metadata={'source': 'path_to_text', 'start_index': 16932}),
Document(page_content="...", metadata={'source': 'path_to_text', 'start_index': 16932}),
Document(page_content="...", metadata={'source': …Run Code Online (Sandbox Code Playgroud) langchain ×10
python ×4
chromadb ×3
openai-api ×2
py-langchain ×2
chatbot ×1
document ×1
javascript ×1
python-3.x ×1
string ×1