pocketflow庫實現guardrail

目錄

    • 代碼
    • 代碼解釋
      • 1. 系統架構
      • 2. 核心組件詳解
        • 2.1 LLM調用函數
        • 2.2 UserInputNode(用戶輸入節點)
        • 2.3 GuardrailNode(安全防護節點)
        • 2.4 LLMNode(LLM處理節點)
      • 3. 流程控制機制
    • 示例運行

代碼

from pocketflow import Node, Flowfrom openai import OpenAIdef call_llm(messages):client = OpenAI(api_key = "your api key",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")response = client.chat.completions.create(model="qwen-turbo",messages=messages,temperature=0.7)return response.choices[0].message.contentclass UserInputNode(Node):def prep(self, shared):# Initialize messages if this is the first runif "messages" not in shared:shared["messages"] = []print("Welcome to the Travel Advisor Chat! Type 'exit' to end the conversation.")return Nonedef exec(self, _):# Get user inputuser_input = input("\nYou: ")return user_inputdef post(self, shared, prep_res, exec_res):user_input = exec_res# Check if user wants to exitif user_input and user_input.lower() == 'exit':print("\nGoodbye! Safe travels!")return None  # End the conversation# Store user input in sharedshared["user_input"] = user_input# Move to guardrail validationreturn "validate"class GuardrailNode(Node):def prep(self, shared):# Get the user input from shared datauser_input = shared.get("user_input", "")return user_inputdef exec(self, user_input):# Basic validation checksif not user_input or user_input.strip() == "":return False, "Your query is empty. Please provide a travel-related question."if len(user_input.strip()) < 3:return False, "Your query is too short. Please provide more details about your travel question."# LLM-based validation for travel topicsprompt = f"""
Evaluate if the following user query is related to travel advice, destinations, planning, or other travel topics.
The chat should ONLY answer travel-related questions and reject any off-topic, harmful, or inappropriate queries.
User query: {user_input}
Return your evaluation in YAML format:
```yaml
valid: true/false
reason: [Explain why the query is valid or invalid]
```"""# Call LLM with the validation promptmessages = [{"role": "user", "content": prompt}]response = call_llm(messages)# Extract YAML contentyaml_content = response.split("```yaml")[1].split("```")[0].strip() if "```yaml" in response else responseimport yamlresult = yaml.safe_load(yaml_content)assert result is not None, "Error: Invalid YAML format"assert "valid" in result and "reason" in result, "Error: Invalid YAML format"is_valid = result.get("valid", False)reason = result.get("reason", "Missing reason in YAML response")return is_valid, reasondef post(self, shared, prep_res, exec_res):is_valid, message = exec_resif not is_valid:# Display error message to userprint(f"\nTravel Advisor: {message}")# Skip LLM call and go back to user inputreturn "retry"# Valid input, add to message historyshared["messages"].append({"role": "user", "content": shared["user_input"]})# Proceed to LLM processingreturn "process"class LLMNode(Node):def prep(self, shared):# Add system message if not presentif not any(msg.get("role") == "system" for msg in shared["messages"]):shared["messages"].insert(0, {"role": "system", "content": "You are a helpful travel advisor that provides information about destinations, travel planning, accommodations, transportation, activities, and other travel-related topics. Only respond to travel-related queries and keep responses informative and friendly. Your response are concise in 100 words."})# Return all messages for the LLMreturn shared["messages"]def exec(self, messages):# Call LLM with the entire conversation historyresponse = call_llm(messages)return responsedef post(self, shared, prep_res, exec_res):# Print the assistant's responseprint(f"\nTravel Advisor: {exec_res}")# Add assistant message to historyshared["messages"].append({"role": "assistant", "content": exec_res})# Loop back to continue the conversationreturn "continue"# Create the flow with nodes and connections
user_input_node = UserInputNode()
guardrail_node = GuardrailNode()
llm_node = LLMNode()# Create flow connections
user_input_node - "validate" >> guardrail_node
guardrail_node - "retry" >> user_input_node  # Loop back if input is invalid
guardrail_node - "process" >> llm_node
llm_node - "continue" >> user_input_node     # Continue conversationflow = Flow(start=user_input_node)shared = {}
flow.run(shared)

代碼解釋

這個示例展示了如何使用PocketFlow框架實現一個帶有guardrail(安全防護)機制的旅行顧問聊天機器人。整個系統由三個核心節點組成,通過條件流控制實現智能對話管理。

1. 系統架構

用戶輸入 → 安全驗證 → LLM處理 → 用戶輸入↑         ↓←─────────┘(驗證失敗時重試)

2. 核心組件詳解

2.1 LLM調用函數
def call_llm(messages):client = OpenAI(api_key = "your api key",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")
  • 使用阿里云DashScope的兼容OpenAI API接口
  • 配置qwen-turbo模型,temperature=0.7保證回答的創造性
2.2 UserInputNode(用戶輸入節點)
class UserInputNode(Node):def prep(self, shared):if "messages" not in shared:shared["messages"] = []

功能

  • prep:初始化對話歷史,首次運行時顯示歡迎信息
  • exec:獲取用戶輸入
  • post:檢查退出條件,將輸入存儲到共享狀態,返回"validate"進入驗證流程
2.3 GuardrailNode(安全防護節點)

這是系統的核心安全組件,實現多層驗證:

基礎驗證

if not user_input or user_input.strip() == "":return False, "Your query is empty..."
if len(user_input.strip()) < 3:return False, "Your query is too short..."

LLM智能驗證

prompt = f"""
Evaluate if the following user query is related to travel advice...
Return your evaluation in YAML format:
```yaml
valid: true/false
reason: [Explain why the query is valid or invalid]
```"""

驗證流程

  1. 基礎格式檢查(空輸入、長度)
  2. 使用LLM判斷是否為旅行相關話題
  3. 解析YAML格式的驗證結果
  4. 根據驗證結果決定流向:
    • 失敗:返回"retry"重新輸入
    • 成功:返回"process"進入LLM處理
2.4 LLMNode(LLM處理節點)
def prep(self, shared):if not any(msg.get("role") == "system" for msg in shared["messages"]):shared["messages"].insert(0, {"role": "system", "content": "You are a helpful travel advisor..."})

功能

  • prep:確保系統提示詞存在,定義AI助手角色
  • exec:調用LLM生成回答
  • post:顯示回答,更新對話歷史,返回"continue"繼續對話

3. 流程控制機制

user_input_node - "validate" >> guardrail_node
guardrail_node - "retry" >> user_input_node
guardrail_node - "process" >> llm_node
llm_node - "continue" >> user_input_node

流程說明

  1. 正常流程:用戶輸入 → 驗證通過 → LLM處理 → 繼續對話
  2. 安全攔截:用戶輸入 → 驗證失敗 → 重新輸入
  3. 退出機制:用戶輸入"exit" → 程序結束

示例運行

在這里插入圖片描述

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

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

相關文章

Fetch API 使用詳解:Bearer Token 與 localStorage 實踐

Fetch API&#xff1a;現代瀏覽器內置的用于發送 HTTP 請求的 API&#xff0c;Bearer Token&#xff1a;一種基于令牌的身份驗證方案&#xff0c;常用于 JWT 認證&#xff0c;localStorage&#xff1a;瀏覽器提供的持久化存儲方案&#xff0c;用于在客戶端存儲數據。 token是我…

Netty自定義協議解析

目錄 自定義協議設計 實現消息解碼器 實現消息編碼器 自定義消息對象 配置ChannelPipeline Netty提供了強大的編解碼器抽象基類,這些基類能夠幫助開發者快速實現自定義協議的解析。 自定義協議設計 在實現自定義協議解析之前,需要明確協議的具體格式。例如,一個簡單的…

馭碼 CodeRider 2.0 產品體驗:智能研發的革新之旅

馭碼 CodeRider 2.0 產品體驗&#xff1a;智能研發的革新之旅 在當今快速發展的軟件開發領域&#xff0c;研發效率與質量始終是開發者和企業關注的核心。面對開發協作流程繁瑣、代碼生成補全不準、代碼審核低效、知識協同困難以及部署成本與靈活性難以平衡等問題&#xff0c;…

NLP學習路線圖(二十六):自注意力機制

一、為何需要你?序列建模的困境 在你出現之前,循環神經網絡(RNN)及其變種LSTM、GRU是處理序列數據(如文本、語音、時間序列)的主流工具。它們按順序逐個處理輸入元素,將歷史信息壓縮在一個隱藏狀態向量中傳遞。 瓶頸顯現: 長程依賴遺忘: 隨著序列增長,早期信息在傳遞…

【渲染】Unity-分析URP的延遲渲染-DeferredShading

我是一名資深游戲開發&#xff0c;小時候喜歡看十萬個為什么 介紹 本文旨在搞清楚延遲渲染在unity下如何實現的&#xff0c;為自己寫延遲渲染打一個基礎&#xff0c;打開從知到行的大門延遲渲染 輸出物體表面信息(rt1, rt2, rt3, …) 著色(rt1, rt2, rt3, …)研究完感覺核心…

華為OD機考- 簡單的自動曝光/平均像素

import java.util.Arrays; import java.util.Scanner;public class DemoTest4 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的區別while (in.hasNextLine()) { // 注意 while 處理多個 caseint[] arr Array…

java 樂觀鎖的實現和注意細節

文章目錄 1. 前言樂觀鎖 vs. 悲觀鎖&#xff1a;基本概念對比使用場景及優勢簡述 2. 基于版本號的樂觀鎖實現代碼示例注意事項 3. 基于CAS機制的樂觀鎖實現核心思想代碼示例關鍵點說明 4. 框架中的樂觀鎖實踐MyBatis中基于版本號的樂觀鎖實現示例代碼 JPA&#xff08;Hibernate…

河北對口計算機高考C#筆記(2026高考適用)---持續更新~~~~

C#筆記 C#發展史 1998年,C#發布第一個版本。2002年,visual studio開發環境推出C#的特點 1.語法簡潔,不允許直接操作內存,去掉了指針操作 2.徹底面向對象設計。 3.與Web緊密結合。 4.強大的安全機制,語法錯誤提示,引入垃圾回收器機制。 5.兼容性。 6.完善的錯誤,異常處理…

C# dll版本沖突解決方案

隨著項目功能逐漸增加&#xff0c;引入三方庫數量也會增多。不可避免遇到庫的間接引用dll版本沖突&#xff0c;如System.Memory.dll、System.Buffer.dll等。編譯會報警&#xff0c;運行可能偶發異常。 可使用ILMerge工具合并動態庫&#xff0c;將一個庫的多個dll合并為一個dll。…

深度解析:etcd 在 Milvus 向量數據庫中的關鍵作用

目錄 &#x1f680; 深度解析&#xff1a;etcd 在 Milvus 向量數據庫中的關鍵作用 &#x1f4a1; 什么是 etcd&#xff1f; &#x1f9e0; Milvus 架構簡介 &#x1f4e6; etcd 在 Milvus 中的核心作用 &#x1f527; 實際工作流程示意 ?? 如果 etcd 出現問題會怎樣&am…

隨機訪問介質訪問控制:網絡中的“自由競爭”藝術

想象一場自由辯論賽——任何人隨時可以發言&#xff0c;但可能多人同時開口導致混亂。這正是計算機網絡中隨機訪問協議的核心挑戰&#xff1a;如何讓多個設備在共享信道中高效競爭&#xff1f;本文將深入解析五大隨機訪問技術及其智慧。 一、核心思想&#xff1a;自由競爭 沖突…

設計模式作業

package sdau;public class man {public static void main(String[] args) {show(new Cat()); // 以 Cat 對象調用 show 方法show(new Dog()); // 以 Dog 對象調用 show 方法Animal a new Cat(); // 向上轉型 a.eat(); // 調用的是 Cat 的 eatCat c (Cat)a…

Kaspa Wasm SDK

文章目錄 1. 簡要2. github地址 1. 簡要 kaspa wallet SDK&#xff0c;在官方WASM基礎上封裝了應用層的方法&#xff0c;簡便了WASM的初始化及調用。 核心功能包括如下&#xff1a; 賬戶地址生成及管理Kaspa Api 和 Kasplex Api的封裝kaspa結點RPC 封裝P2SH的各個場景script封…

ROS mapserver制作靜態地圖

ROS mapserver制作靜態地圖 靜態地圖構建 1、獲取一個PNG地圖&#xff0c;二值化 2、基于PNG地圖&#xff0c;生成PGM地圖&#xff0c;可以通過一些網站在線生成&#xff0c;例如Convertio 文件配置 1、將文件放置于/package/map路徑下。 2、編寫yaml文件&#xff0c;如下…

tree 樹組件大數據卡頓問題優化

問題背景 項目中有用到樹組件用來做文件目錄&#xff0c;但是由于這個樹組件的節點越來越多&#xff0c;導致頁面在滾動這個樹組件的時候瀏覽器就很容易卡死。這種問題基本上都是因為dom節點太多&#xff0c;導致的瀏覽器卡頓&#xff0c;這里很明顯就需要用到虛擬列表的技術&…

瀏覽器工作原理05 [#] 渲染流程(上):HTML、CSS和JavaScript是如何變成頁面的

引用 瀏覽器工作原理與實踐 一、提出問題 在上一篇文章中我們介紹了導航相關的流程&#xff0c;那導航被提交后又會怎么樣呢&#xff1f;就進入了渲染階段。這個階段很重要&#xff0c;了解其相關流程能讓你“看透”頁面是如何工作的&#xff0c;有了這些知識&#xff0c;你可…

DrissionPage爬蟲包實戰分享

一、爬蟲 1.1 爬蟲解釋 爬蟲簡單的說就是模擬人的瀏覽器行為&#xff0c;簡單的爬蟲是request請求網頁信息&#xff0c;然后對html數據進行解析得到自己需要的數據信息保存在本地。 1.2 爬蟲的思路 # 1.發送請求 # 2.獲取數據 # 3.解析數據 # 4.保存數據 1.3 爬蟲工具 Dris…

android 布局小知識點 隨記

1. 布局屬性的命名前綴規律 與父容器相關的前綴 layout_alignParent&#xff1a;相對于父容器的對齊方式。 例如&#xff1a;layout_alignParentTop"true"&#xff08;相對于父容器頂部對齊&#xff09;。layout_margin&#xff1a;與父容器或其他控件的邊距。 例如…

GeoDrive:基于三維幾何信息有精確動作控制的駕駛世界模型

25年5月來自北大、理想汽車和 UC Berkeley 的論文“GeoDrive: 3D Geometry-Informed Driving World Model with Precise Action Control”。 世界模型的最新進展徹底改變動態環境模擬&#xff0c;使系統能夠預見未來狀態并評估潛在行動。在自動駕駛中&#xff0c;這些功能可幫…

Java高頻面試之并發編程-25

hello啊&#xff0c;各位觀眾姥爺們&#xff01;&#xff01;&#xff01;本baby今天又來報道了&#xff01;哈哈哈哈哈嗝&#x1f436; 面試官&#xff1a;CAS都有哪些問題&#xff1f;如何解決&#xff1f; CAS 的問題及解決方案 CAS&#xff08;Compare and Swap&#xff0…