当前位置: 首页 > news >正文

相亲网站上做it的骗术商城网站开发技术

相亲网站上做it的骗术,商城网站开发技术,网站建设职位要求,郴州宸轩网络科技有限公司最近在使用LangChain来做一个LLMs和KBs结合的小Demo玩玩#xff0c;也就是RAG#xff08;Retrieval Augmented Generation#xff09;。 这部分的内容其实在LangChain的官网已经给出了流程图。 我这里就直接偷懒了#xff0c;准备对Webui的项目进行复刻练习#xff0c;那么…最近在使用LangChain来做一个LLMs和KBs结合的小Demo玩玩也就是RAGRetrieval Augmented Generation。 这部分的内容其实在LangChain的官网已经给出了流程图。 我这里就直接偷懒了准备对Webui的项目进行复刻练习那么接下来就是照着葫芦画瓢就行。 那么我卡在了Retrieve这一步。先放有疑惑地方的代码 if web_content:prompt_template f基于以下已知信息简洁和专业的来回答用户的问题。如果无法从中得到答案请说 根据已知信息无法回答该问题 或 没有提供足够的相关信息不允许在答案中添加编造成分答案请使用中文。已知网络检索内容{web_content} 已知内容:{context}问题:{question}else:prompt_template 基于以下已知信息请简洁并专业地回答用户的问题。如果无法从中得到答案请说 根据已知信息无法回答该问题 或 没有提供足够的相关信息。不允许在答案中添加编造成分。另外答案请使用中文。已知内容:{context}问题:{question}prompt PromptTemplate(templateprompt_template,input_variables[context, question])......knowledge_chain RetrievalQA.from_llm(llmself.llm,retrievervector_store.as_retriever(search_kwargs{k: self.top_k}),promptprompt)knowledge_chain.combine_documents_chain.document_prompt PromptTemplate(input_variables[page_content], template{page_content})knowledge_chain.return_source_documents Trueresult knowledge_chain({query: query})return result我对prompt_template、knowledge_chain.combine_documents_chain.document_prompt和 result knowledge_chain({query: query})这三个地方的input_key不明白为啥一定要这样设置。虽然我也看了LangChain的API文档。但是我并未得到详细的答案那么只能一行行看源码是到底怎么设置的了。 注意由于LangChain是一层层封装的那么result knowledge_chain({query: query})可以认为是最外层那么我们先看最外层。 result knowledge_chain({“query”: query}) 其实这部分是直接与用户的输入问题做对接的我们只需要定位到RetrievalQA这个类就可以了下面是RetrievalQA这个类的实现 class RetrievalQA(BaseRetrievalQA):Chain for question-answering against an index.Example:.. code-block:: pythonfrom langchain.llms import OpenAIfrom langchain.chains import RetrievalQAfrom langchain.vectorstores import FAISSfrom langchain.schema.vectorstore import VectorStoreRetrieverretriever VectorStoreRetriever(vectorstoreFAISS(...))retrievalQA RetrievalQA.from_llm(llmOpenAI(), retrieverretriever)retriever: BaseRetriever Field(excludeTrue)def _get_docs(self,question: str,*,run_manager: CallbackManagerForChainRun,) - List[Document]:Get docs.return self.retriever.get_relevant_documents(question, callbacksrun_manager.get_child())async def _aget_docs(self,question: str,*,run_manager: AsyncCallbackManagerForChainRun,) - List[Document]:Get docs.return await self.retriever.aget_relevant_documents(question, callbacksrun_manager.get_child())propertydef _chain_type(self) - str:Return the chain type.return retrieval_qa可以看到其继承了BaseRetrievalQA这个父类同时对_get_docs这个抽象方法进行了实现。 这里要扩展的说一下_get_docs这个方法就是利用向量相似性在vector Base中选择与embedding之后的query最近似的Document结果。然后作为RetrievalQA的上下文。具体只需要看BaseRetrievalQA这个方法的_call和就可以了。 接下来我们只需要看BaseRetrievalQA这个类的属性就可以了。 class BaseRetrievalQA(Chain):Base class for question-answering chains.combine_documents_chain: BaseCombineDocumentsChainChain to use to combine the documents.input_key: str query #: :meta private:output_key: str result #: :meta private:return_source_documents: bool FalseReturn the source documents or not.……def _call(self,inputs: Dict[str, Any],run_manager: Optional[CallbackManagerForChainRun] None,) - Dict[str, Any]:Run get_relevant_text and llm on input query.If chain has return_source_documents as True, returnsthe retrieved documents as well under the key source_documents.Example:.. code-block:: pythonres indexqa({query: This is my query})answer, docs res[result], res[source_documents]_run_manager run_manager or CallbackManagerForChainRun.get_noop_manager()question inputs[self.input_key]accepts_run_manager (run_manager in inspect.signature(self._get_docs).parameters)if accepts_run_manager:docs self._get_docs(question, run_manager_run_manager)else:docs self._get_docs(question) # type: ignore[call-arg]answer self.combine_documents_chain.run(input_documentsdocs, questionquestion, callbacks_run_manager.get_child())if self.return_source_documents:return {self.output_key: answer, source_documents: docs}else:return {self.output_key: answer}可以看到其有input_key这个属性默认值是query。到这里我们就可以看到result knowledge_chain({query: query})是调用的BaseRetrievalQA的_call这里的question inputs[self.input_key]就是其体现。 knowledge_chain.combine_documents_chain.document_prompt 这个地方一开始我很奇怪为什么会重新定义呢 我们可以先定位到combine_documents_chain这个参数的位置其是StuffDocumentsChain的方法。 classmethod def from_llm(cls,llm: BaseLanguageModel,prompt: Optional[PromptTemplate] None,callbacks: Callbacks None,**kwargs: Any, ) - BaseRetrievalQA:Initialize from LLM._prompt prompt or PROMPT_SELECTOR.get_prompt(llm)llm_chain LLMChain(llmllm, prompt_prompt, callbackscallbacks)document_prompt PromptTemplate(input_variables[page_content], templateContext:\n{page_content})combine_documents_chain StuffDocumentsChain(llm_chainllm_chain,document_variable_namecontext,document_promptdocument_prompt,callbackscallbacks,)return cls(combine_documents_chaincombine_documents_chain,callbackscallbacks,**kwargs,)可以看到原始的document_prompt中PromptTemplate的template是“Context:\n{page_content}”。因为这个项目是针对中文的所以需要将英文的Context去掉。 扩展 这里PromptTemplate(input_variables[“page_content”], template“Context:\n{page_content}”)的input_variables和template为什么要这样定义呢其实是根据Document这个数据对象来定义使用的我们可以看到其数据格式为Document(page_content‘……’, metadata{‘source’: ‘……’, ‘row’: ……}) 那么input_variables的输入就是Document的page_content。StuffDocumentsChain中有一个参数是document_variable_name。那么这个类是这样定义的This chain takes a list of documents and first combines them into a single string. It does this by formatting each document into a string with the document_prompt and then joining them together with document_separator. It then adds that new string to the inputs with the variable name set by document_variable_name. Those inputs are then passed to the llm_chain. 这个document_variable_name简单来说就是在document_prompt中的占位符用于在Chain中的使用。 因此我们上文prompt_template变量中的“已知内容: {context}”用的就是context这个变量。因此在prompt_template中换成其他的占位符都不能正常使用这个Chain。 prompt_template 在上面的拓展中其实已经对prompt_template做了部分的讲解那么这个字符串还剩下“问题:{question}”这个地方没有说通 还是回归源码: return cls(combine_documents_chaincombine_documents_chain,callbackscallbacks,**kwargs,)我们可以在from_llm函数中看到其返回值是到了_call那么剩下的我们来看这个函数 ...... uestion inputs[self.input_key] accepts_run_manager (run_manager in inspect.signature(self._get_docs).parameters ) if accepts_run_manager:docs self._get_docs(question, run_manager_run_manager) else:docs self._get_docs(question) # type: ignore[call-arg] answer self.combine_documents_chain.run(input_documentsdocs, questionquestion, callbacks_run_manager.get_child() ) ...... 这里是在run这个函数中传入了一个字典值这个字典值有三个参数。 注意 这三个参数就是kwargs也就是_validate_inputs的参数input;此时已经是在Chain这个基本类了 def run(self,*args: Any,callbacks: Callbacks None,tags: Optional[List[str]] None,metadata: Optional[Dict[str, Any]] None,**kwargs: Any,) - Any:Convenience method for executing chain.The main difference between this method and Chain.__call__ is that thismethod expects inputs to be passed directly in as positional arguments orkeyword arguments, whereas Chain.__call__ expects a single input dictionarywith all the inputs接下来调用__call__: def __call__(self,inputs: Union[Dict[str, Any], Any],return_only_outputs: bool False,callbacks: Callbacks None,*,tags: Optional[List[str]] None,metadata: Optional[Dict[str, Any]] None,run_name: Optional[str] None,include_run_info: bool False,) - Dict[str, Any]:Execute the chain.Args:inputs: Dictionary of inputs, or single input if chain expectsonly one param. Should contain all inputs specified inChain.input_keys except for inputs that will be set by the chainsmemory.return_only_outputs: Whether to return only outputs in theresponse. If True, only new keys generated by this chain will bereturned. If False, both input keys and new keys generated by thischain will be returned. Defaults to False.callbacks: Callbacks to use for this chain run. These will be called inaddition to callbacks passed to the chain during construction, but onlythese runtime callbacks will propagate to calls to other objects.tags: List of string tags to pass to all callbacks. These will be passed inaddition to tags passed to the chain during construction, but onlythese runtime tags will propagate to calls to other objects.metadata: Optional metadata associated with the chain. Defaults to Noneinclude_run_info: Whether to include run info in the response. Defaultsto False.Returns:A dict of named outputs. Should contain all outputs specified inChain.output_keys.inputs self.prep_inputs(inputs)......这里的prep_inputs会调用_validate_inputs函数 def _validate_inputs(self,inputs: Dict[str, Any]) - None:Check that all inputs are present.missing_keys set(self.input_keys).difference(inputs)if missing_keys:raise ValueError(fMissing some input keys: {missing_keys})这里的input_keys通过调试看到的就是有多个输入分别是input_documents和question 这里的input_documents是来自于BaseCombineDocumentsChain class BaseCombineDocumentsChain(Chain, ABC):Base interface for chains combining documents.Subclasses of this chain deal with combining documents in a variety ofways. This base class exists to add some uniformity in the interface these typesof chains should expose. Namely, they expect an input key related to the documentsto use (default input_documents), and then also expose a method to calculatethe length of a prompt from documents (useful for outside callers to use todetermine whether its safe to pass a list of documents into this chain or whetherthat will longer than the context length).input_key: str input_documents #: :meta private:output_key: str output_text #: :meta private: 那为什么有两个呢“question”来自于哪里 StuffDocumentsChain继承BaseCombineDocumentsChain其input_key是这样定义的 propertydef input_keys(self) - List[str]:extra_keys [k for k in self.llm_chain.input_keys if k ! self.document_variable_name]return super().input_keys extra_keys原来是重写了input_keys函数其是对llm_chain的input_keys进行遍历。 那么llm_chain的input_keys是用其prompt的input_variables。这里的input_variables是PromptTemplate中的[“context”, “question”] propertydef input_keys(self) - List[str]:Will be whatever keys the prompt expects.:meta private:return self.prompt.input_variables至此我们StuffDocumentsChain的input_keys有两个变量了。
http://wiki.neutronadmin.com/news/350287/

相关文章:

  • 网站建设 招标书足球网站怎么做
  • 学校网站网页设计wordpress 链接新窗口
  • 如何用博客网站做cpa惠州网站建设哪里找
  • 网站建设 企业 资质 等级南宁seo服务优化
  • 专门做颜料的网站淄博网站开发公司
  • 网站突然没有收录淮南专业网站建设
  • 快递查询网站建设网络域名怎么设置
  • 网站主办者什么意思网页平面美工培训
  • dede双语网站58同城个人房屋出租信息发布
  • 温州优化网站方法网络技术服务合同模板
  • 局网站建设工作征求意见桥西企业做网站
  • 南昌市 做网站的公司网站制作的电话
  • 云南微网站建设的公司有哪些wordpress快递模板下载
  • 网站架构拓扑图企业网店推广运营策略
  • 广州网站维护公司微信怎么关闭小程序
  • 外贸网站建站要多少钱咋样看网站域名是哪个服务商的
  • html网页留言板代码乌兰察布seo
  • 个人网站开发与实现开题报告网络公司企业网站模板
  • 专业网站建设团队seo专业优化方法
  • sql做网站后台如何用wordpress插件下载
  • 网站建设_微信开发网站上怎么做动图
  • 平顶山网站建设价格联系昆明网站建设
  • 金华建设技工学校网站五屏网站建设多少钱
  • 如何做自己的博客网站济南全屋定制品牌
  • 网站开发 职位描述网站图片设置
  • 网站做标题有用吗山西企业建站方案
  • 怎样做网站分流赚钱扁平式风格网站
  • google 网站收录新北网站建设
  • 装修网站大全承德网站制作
  • 潍坊网站公司网络科技拍艺术照