LangGraph-2-Demo

'''
狀態:一個共享數據結構,表示應用程序的當前快照。它可以是任何 Python 類型,但通常是 TypedDict 或 Pydantic BaseModel。
節點:Python 函數,用于編碼代理的邏輯。它們以當前 狀態 作為輸入,執行一些計算或副作用,并返回更新后的 狀態。
邊:Python 函數,根據當前 狀態 確定要執行的下一個 節點。它們可以是條件分支或固定轉換。
節點 和 邊 僅僅是 Python 函數 - 它們可以包含 LLM 或普通的 Python 代碼。
節點完成工作,邊指示下一步要做什么.
'''

# 創建檢索Tool

from langchain_community.document_loaders import WebBaseLoader
# WebBaseLoader獲取博客內容用于RAG
urls = ["https://blog.csdn.net/xnuscd/article/details/143474722"
]docs = [WebBaseLoader(url).load() for url in urls]## 文檔切塊
from langchain_text_splitters import RecursiveCharacterTextSplitter
docs_list = [item for sublist in docs for item in sublist]text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=100, chunk_overlap=50
)
doc_splits = text_splitter.split_documents(docs_list)#創建檢索
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddingsvectorstore = InMemoryVectorStore.from_documents( # 內存向量存儲documents=doc_splits, embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever() #檢索器
from langchain.tools.retriever import create_retriever_toolretriever_tool = create_retriever_tool( # 檢索Toolretriever,"retrieve_blog_posts","Search and return information about Lilian Weng blog posts.",
)

## 綁定Tool,構建模型和生成器

from langgraph.graph import MessagesState
from langchain.chat_models import init_chat_model
#
response_model = init_chat_model("openai:gpt-4.1", temperature=0)def generate_query_or_respond(state: MessagesState):response = ( # 傳入 狀態state的messagesresponse_model.bind_tools([retriever_tool]).invoke(state["messages"]))return {"messages": [response]}# input = {
#     "messages": [
#         {
#             "role": "user",
#             "content": "What does Lilian Weng say about types of reward hacking?",
#         }
#     ]
# }
# generate_query_or_respond(input)["messages"][-1].pretty_print()
#
# ================================== Ai Message ==================================
# Tool Calls:
# retrieve_blog_posts (call_tYQxgfIlnQUDMdtAhdbXNwIM)
# Call ID: call_tYQxgfIlnQUDMdtAhdbXNwIM
# Args:
#     query: types of reward hacking

## 添加一個條件邊 — grade_documents —
??????

來判斷檢索到的文檔是否與問題相關

from pydantic import BaseModel, Field
from typing import LiteralGrade_Prompt= ("You are a grader assessing relevance of a retrieved document to a user question. \n ""Here is the retrieved document: \n\n {context} \n\n""Here is the user question: {question} \n""If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n""Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question."
)class GradeDocuments(BaseModel):""" 相關性評分 yes / no"""binary_score: str = Field(description="Relevance score: 'yes' if relevant, or 'no' if not relevant")grader_model = init_chat_model("openai:gpt-4.1", temperature=0)def grade_documents(state: MessagesState,
) -> Literal["generate_answer", "rewrite_question"]:question = state["messages"][0].contentcontext = state["messages"][-1].contentprompt = Grade_Prompt.format(question=question, context=context)response = (grader_model # Pydantic 結構化輸出.with_structured_output(GradeDocuments).invoke([{"role": "user", "content": prompt}]))score = response.binary_scoreif score == "yes": ## 根據GradeDocuments結果,輸出決策return "generate_answer"else:return "rewrite_question"

## 構建?rewrite_question 節點;generate_answer 節點

即 grade_documents 為No 時 進行rewrite_question ;為Yes 繼續generate_answer 
REWRITE_PROMPT = ("Look at the input and try to reason about the underlying semantic intent / meaning.\n""Here is the initial question:""\n ------- \n""{question}""\n ------- \n""Formulate an improved question:"
)# 構建 rewrite_question 節點,
# 如果沒找到相關的文檔 即 GradeDocuments 為No
# ,則重新理解用戶問題
def rewrite_question(state: MessagesState):"""Rewrite the original user question."""messages = state["messages"]question = messages[0].contentprompt = REWRITE_PROMPT.format(question=question)response = response_model.invoke([{"role": "user", "content": prompt}])return {"messages": [{"role": "user", "content": response.content}]}GENERATE_PROMPT = ("You are an assistant for question-answering tasks. ""Use the following pieces of retrieved context to answer the question. ""If you don't know the answer, just say that you don't know. ""Use three sentences maximum and keep the answer concise.\n""Question: {question} \n""Context: {context}"
)
# 構建 generate_answer 節點;通過GradeDocuments=Yes,根據問題、檢索進行生成
def generate_answer(state: MessagesState):"""Generate an answer."""question = state["messages"][0].contentcontext = state["messages"][-1].contentprompt = GENERATE_PROMPT.format(question=question, context=context)response = response_model.invoke([{"role": "user", "content": prompt}])return {"messages": [response]}

## 組裝 Graph


from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode
from langgraph.prebuilt import tools_condition# MessagesState:這是一個自定義的狀態結構(通常是TypedDict或pydantic.BaseModel)
workflow = StateGraph(MessagesState) #創建工作流,基于MessagesState的狀態圖實例# 添加 Node
workflow.add_node(generate_query_or_respond)
# 添加一個名為"retrieve"的節點,類型為ToolNode(工具節點),綁定了retriever_tool
workflow.add_node("retrieve", ToolNode([retriever_tool]))
workflow.add_node(rewrite_question)
workflow.add_node(generate_answer)
# 添加 edge
workflow.add_edge(START, "generate_query_or_respond")# 決定是否要檢索
workflow.add_conditional_edges("generate_query_or_respond",tools_condition, # 條件函數:用該函數判斷下一步{# 條件映射:函數返回值 → 目標節點"tools": "retrieve", # 若條件函數返回"tools",則下一步執行"retrieve"節點END: END,# 若條件函數返回END,則直接結束工作流},
)# 調用"retrieve"節點后 的edge
workflow.add_conditional_edges("retrieve", # 起點節點:從檢索節點出發grade_documents,# 條件函數:評估檢索到的文檔是否有效
)
workflow.add_edge("generate_answer", END) # 結束edge
workflow.add_edge("rewrite_question", "generate_query_or_respond")# 編譯
graph = workflow.compile()
from IPython.display import Image, displaydisplay(Image(graph.get_graph().draw_mermaid_png()))

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/96915.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/96915.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/96915.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

基于硅基流動API構建智能聊天應用的完整指南

基于硅基流動API構建智能聊天應用的完整指南 一、引言:AI編程工具重塑開發范式 人工智能編程工具正在徹底改變軟件開發的方式,使開發者能夠快速構建以前需要大量專業知識的復雜應用。本文將深入探討如何使用硅基流動(SiliconFlow)的API,結合…

深入解析MyBatis中#{}和${}的區別與應用場景

在MyBatis框架的使用過程中,SQL映射文件的編寫是核心工作之一。而#{}和${}這兩種參數占位符語法,雖然看起來相似,卻有著本質的區別。正確理解和使用它們,不僅關系到應用程序的安全性,還會影響系統性能。本文將全面剖析…

ELKB日志分析平臺 部署

ElasticSearch ELKB 日志分析 介紹 docker-compose一鍵部署ELK(elasticsearchlogstashkibana) 以下是使用 Docker Compose 部署 Elasticsearch、Logstash、Kibana 和 Beats(以 Filebeat 為例) 的完整方案,涵蓋配置文件、關鍵參數說明及部署步…

File IO 字節流 | Java 學習日志 | 第 12 天

File 1.概述 File表示路徑,可以表示文件和文件夾,可以存在也可以不存在 相對路徑(相對當前項目),絕對路徑。 構造方法File(file/string),File(file/string,string)。 public static void main(String[] ar…

基于SpringBoot的服裝公司進銷存管理系統設計與開發(代碼+數據庫+LW)

摘要 隨著服裝行業競爭的加劇,傳統手工或簡單電子表格管理進銷存的方式已難以滿足現代企業的需求,效率低下且易出錯。基于SpringBoot框架的服裝公司進銷存管理系統應運而生,旨在通過信息化手段提升運營效率和服務質量。系統特別設計了銷售員…

openFeign用的什么協議,dubbo用的什么協議

簡單直接的答案是:?OpenFeign?:默認使用 ?HTTP? 協議(通常是 HTTP/1.1,也支持 HTTP/2),通信格式為 ?RESTful JSON。?Dubbo?:默認使用 ?Dubbo 協議?(一種自定義的、基于 TCP…

Android SystemServer 系列專題【篇四:SystemServerInitThreadPool線程池管理】

本篇重點介紹一下SystemServerInitThreadPool,顧名思義此類針對SystemServer進程的提供了一套ThreadPool線程池的統一標準方案,下面從源碼和日志的角度來剖析一個這個類。1、SystemServerInitThreadPool單例設計SystemServerInitThreadPool的源碼路徑在f…

2014-2024高教社杯全國大學生數學建模競賽賽題匯總預覽分析

一、分析賽題核心意義收集近 11 年的賽題并非簡單的 “題目存檔”,而是為了從歷史規律、能力匹配、實戰準備三個維度為參賽者或研究者提供價值。1.1把握競賽命題趨勢,降低選題盲目性賽題命題往往緊扣當年社會熱點、科技前沿與行業痛點(如 202…

一個頭像圖片滾動輪播組件(React實現)

遇到一個效果,組件庫里沒有現成能用的組件,于是手搓了一個,傳入圖片url列表,和其他配置項即可直接使用。 輪播效果實現思路 假設共有10張圖片輪流滾動,輪播圖展示3張圖片。給正在輪播的圖片綁定visible類,輪…

從入門到理解:支持向量機的核心原理與實戰思路

一、SVM 的核心目標:找 “最好” 的超平面。1.1 什么是 “超平面”?超平面是一個幾何概念,簡單來說:在 2 維空間(平面)中,超平面是一條直線(1 維);在 3 維空間…

Python 辦公自動化實戰:Excel 批量處理 + 自動發郵件

Python 辦公自動化實戰:Excel 批量處理 自動發郵件關鍵詞: Python辦公自動化 ? Pandas ? OpenPyXL ? Email ? 定時任務 摘要: 每月底還在手動處理幾十份Excel報表并郵件發送?快來學習如何用Python全自動完成!本文…

高教杯數學建模2021-C 生產企業原材料的訂購與運輸

某建筑和裝飾板材的生產企業所用原材料主要是木質纖維和其他植物素纖維材料, 總體可分為 A,B,C 三種類型。該企業每年按 48 周安排生產,需要提前制定 24 周的原 材料訂購和轉運計劃,即根據產能要求確定需要訂購的原材料供應商&…

【Python系列】Flask 和 FastAPI對比

博客目錄1. 類型和設計目標2. 性能3. 異步支持4. 數據驗證和文檔5. 學習曲線和生態6. 使用場景示例對比Flask(同步)FastAPI(異步)總結Flask 和 FastAPI 都是 Python 中流行的 Web 框架,但它們的設計目標、特性和適用場…

把 AI 塞進「空調遙控器」——基于 MEMS 溫濕陣列的 1 分鐘極速房間熱場掃描

標簽:MEMS 陣列、熱場掃描、極速空調、TinyML、RISC-V、零樣本、離線推理、節能 ---- 背景:為什么空調遙控器要「畫圖」? 傳統空調只有一個溫濕度探頭,經常“東邊冷、西邊熱”。 ? 大客廳 30 ㎡,溫差 5 ℃&#xff1…

【機器學習】8 Logistic regression

本章目錄 8 Logistic regression 245 8.1 Introduction 245 8.2 Model specification 245 8.3 Model fitting 245 8.3.1 MLE 246 8.3.2 Steepest descent 247 8.3.3 Newton’s method 249 8.3.4 Iteratively reweighted least squares (IRLS) 250 8.3.5 Quasi-Newton (variabl…

C++中如何使用互斥(1)------std::lock_guard

操作系統:ubuntu22.04 IDE:Visual Studio Code 編程語言:C11 算法描述 std::lock_guard 是 C11 引入的一個 RAII(Resource Acquisition Is Initialization)風格的鎖管理類,用于自動管理互斥鎖(mutex&#x…

AI算力提升7.5倍!英偉達發布新一代機器人超級計算機Jetson Thor,驅動物理AI革命

今天,NVIDIA 宣布其專為物理 AI 和機器人打造的新一代機器人計算機 Jetson Thor 正式發售。其中,Jetson AGX Thor 開發者套件售價為 3499 美元(約合人民幣 2.5 萬元)。NVIDIA 創始人兼首席執行官黃仁勛表示:“Jetson T…

【數學建模】如何總結數學建模中的層次分析法最好

模型簡介模型名稱:層次分析法核心問題類型:評價類核心思想和適用場景 核心思想:將大決策問題拆解成小比較問題,通過數學計算綜合最終結論:本質是人的主觀判斷轉換為客觀數據的工具[[適用場景]] 個人決策企業 / 項目決策…

`mmap` 系統調用詳解

mmap 是 Unix/Linux 系統中一個強大且多用途的系統調用,用于將文件或設備映射到進程的地址空間,實現內存映射I/O。 1. 函數的概念與用途 mmap(內存映射)函數允許程序將文件或其他對象直接映射到其地址空間,這樣文件內容…

深度剖析Spring AI源碼(二):Model抽象層 - “馴服”天下AI的“緊箍咒”

深度剖析Spring AI源碼(二):Model抽象層 - “馴服”天下AI的“緊箍咒”上一章我們鳥瞰了Spring AI的宏偉藍圖,今天,我們要深入這座大廈的基石——Model抽象層。如果說Spring AI是連接Java與AI世界的橋梁,那…