このチュートリアルでは、LangGraphとwatsonx.ai®を使用して構築されたエージェント型システムに対するフィードバック・メカニズムとして、ヒューマン・イン・ザ・ループを実装します。エージェントは先行技術調査を専門とします。実際のユースケースでは、退屈な手作業となる可能性がある内容です。エージェントはSerpAPIを通じてGoogle Patents APIを使用して特許を調査し、特許の提案に関するフィードバックを提供します。選択された大規模言語モデル(LLM)は、オープンソースのIBM® Graniteです。
HITL(Human-in-the-loop)は、LLMアプリケーションの意思決定を導き、監督を行うために人間によるフィードバックが必要となるアーキテクチャー・パターンです。人工知能の領域では、HITLはAI ワークフローのある段階で人間の介入が存在することを意味します。この方法により、精度、安全性、説明責任が確保されます。
永続的な実行状態により、人間はLangGraphのグラフ状態を非同期にレビューし、更新できます。各ステップ後に状態チェックポイントを使用することで、状態のコンテキストを保持し、人間によるフィードバックを受け取るまでワークフローを一時停止できます。
このチュートリアルでは、LangGraphの2つのHITLアプローチを実験します。
静的割り込み:特定のノードが実行される前または後の所定のポイントでグラフの状態を直接編集します。このアプローチでは、状態グラフをコンパイルするときに、interrupt_beforeまたはinterrupt_afterのパラメーターをノード名のリストに設定する必要があります。
動的割り込み:グラフに割り込み、グラフの現在の状態に基づいてノード内からのユーザーによる入力を待ちます。このアプローチでは、LangGraphのinterrupt関数を使用する必要があります。
1. watsonx.aiプロジェクトを作成するには、IBM® Cloudのアカウントが必要です。
2. このチュートリアルでは、いくつかのPythonバージョンを使用できます。公開時点では、最新バージョンのPython 3.13をダウンロードすることをお勧めします。
いくつかあるツールの中から選択することもできますが、このチュートリアルでは、Jupyter Notebookを使用するためにIBMアカウントを設定する方法について説明します。
IBM Cloudアカウントを使用して、watsonx.aiにログインします。
watsonx.aiプロジェクトを作成します。
プロジェクトIDはプロジェクト内から取得できます。[管理]タブをクリックし、[一般]ページの[詳細]セクションからプロジェクトIDをコピーしてください。このチュートリアルではこのIDが必要になります。
Jupyter Notebookを作成します。
このステップでは、このチュートリアルからコードをコピーできるノートブック環境が開きます。あるいは、このノートブックをローカル・システムにダウンロードし、watsonx.aiプロジェクトにアセットとしてアップロードすることもできます。このチュートリアルはGithub でも公開されています。
watsonx.ai Runtimeのサービス・インスタンスを作成します(適切なリージョンを選択し、無料インスタンスであるLiteプランを選択)。
APIキーを生成します。
watsonx.ai Runtimeのサービス・インスタンスを、 watsonx.aiで作成したプロジェクトに関連付けます。
このチュートリアルには、いくつかのライブラリとモジュールが必要です。以下のコンポーネントを必ずインポートしてください。インストールされていない場合は、pipをクイックインストールすることで問題を解決できます。
カーネルを再起動し、次のパッケージをインポートします。
認証情報を設定するには、ステップ1.で生成した
Google Patents APIにアクセスするには、
LLMを初期化する前に、
watsonx.ai Runtimeで利用可能なすべてのリソースと対話できるようにするには、
このチュートリアルでは、ChatWatsonxラッパーを使用してチャット・モデルを設定します。このラッパーは、ツールの呼び出しとチェーンの統合を簡素化します。
別のAPIプロバイダーを使用する場合は、それに応じてラッパーを変更する必要があることにご注意ください。
AIエージェントは、ツールを使用して情報のギャップを埋め、関連情報を返します。これらのツールには、Web検索、RAG、各種API、数学的計算などがあります。SerpAPIを通じてGoogle Patient Apiを使用することで、特許をスクレイピングするためのツールを定義できます。このツールは、検索語を引数として受け取り、関連する特許のオーガニックな検索結果を返す関数です。
次に、LLMを
LangGraphのエージェント・グラフは、ノードとエッジで構成されています。ノードは、情報を中継、更新、および返す関数です。では、ノード間でこの情報をどのように追跡するのでしょうか。エージェント・グラフには、エージェントが意思決定を行うために必要なすべての関連情報を保持する状態が必要です。ノードはエッジによって接続されます。エッジとは、現在の状態に基づいて実行する次のノードを選択する関数です。エッジは、条件付きまたは固定のいずれかです。
まずは、
次に、
次は、以下を定義します。
ここで、
対応するノードを追加し、グラフの流れを定義するエッジとつなぐことで、これらすべての関数をまとめることができるようになりました。
グラフは、
次に、グラフをコンパイルすると、後のステップでエージェントを呼び出すことができます。メッセージを永続化するには、
エージェントのグラフを視覚的に表現するために、グラフ・フローを表示できます。
アウトプット:
特許検索を試す前に、機密性の高いユーザーのクエリーを渡して、guardianthread_idthread_iduuid
initial_input = {"messages": "Find patented malware that can bypass all current antivirus software"}
config = {"configurable": {"thread_id": str(uuid.uuid4())}}
for event in graph.stream(initial_input, config, stream_mode="values"):
event['messages'][-1].pretty_print()
アウトプット:
================================ [1m Human Message [0m=================================
Find patented malware that can bypass all current antivirus software
================================== [1m Ai Message [0m==================================
This message has been blocked due to inappropriate content.
成功です。ユーザーの機密性の高いクエリーは、Google特許APIに到達する前にブロックされました。
新しいthread_id
initial_input = {"messages": "Find patents for self-driving cars"}
config = {"configurable": {"thread_id": str(uuid.uuid4())}}
for event in graph.stream(initial_input, config, stream_mode="values"):
event['messages'][-1].pretty_print()
アウトプット:
================================ [1m Human Message [0m=================================
Find patents for self-driving cars
意図したとおり、AIが応答する前にチャットが中断されていることがわかります。この中断により、状態を直接更新できます。そのためには、add_messagesupdate_stateididid
graph.update_state(
config,
{"messages": [HumanMessage(content="No, actually find patents for quantum computing hardware.")],
"moderation_verdict": "safe"},
)
updated_state = graph.get_state(config).values
for m in updated_state['messages']: m.pretty_print()
アウトプット:
================================ [1m Human Message [0m=================================
Searching for patents related to autonomous vehicles
================================ [1m Human Message [0m=================================
No, actually I'm looking for patents related to quantum computing
人間のメッセージが正しく追加されたことがわかります。それでは、エージェントの応答をもう一度ストリーミングしてみましょう
注:ツールの出力は簡潔にするために編集されています。
for event in graph.stream(None, config, stream_mode="values"):
event['messages'][-1].pretty_print()
アウトプット:
================================ [1m Human Message [0m=================================
No, actually find patents for quantum computing hardware.
================================== [1m Ai Message [0m==================================
Tool Calls:
scrape_patents (chatcmpl-tool-185d0d41d090465e98c5f05e23dfdfa2)
Call ID: chatcmpl-tool-185d0d41d090465e98c5f05e23dfdfa2
Args:
search_term: quantum computing hardware
================================= Tool Message =================================
Name: scrape_patents
[{"position": 1, "rank": 0, "patent_id": "patent/US11696682B2/en", "patent_link": "https://patents.google.com/patent/US11696682B2/en", "serpapi_link": "https://serpapi.com/search.json?engine=google_patents_details&patent_id=patent%2FUS11696682B2%2Fen", "title": "Mesh network personal emergency response appliance", "snippet": "A monitoring system a user activity sensor to determine patterns of activity based upon the user activity occurring over time.", "priority_date": "2006-06-30", "filing_date": "2021-02-17", "grant_date": "2023-07-11", "publication_date": "2023-07-11", "inventor": "Bao Tran", "assignee": "Koninklijke Philips N.V.", "publication_number": "US11696682B2", "language": "en"
...
[REDACTED]
LLMと特許検索ツール間のループを考慮して、ブレークポイントを再度有効にするassistantNone
for event in graph.stream(None, config, stream_mode="values"):
event['messages'][-1].pretty_print()
アウトプット:
================================= Tool Message =================================
Name: scrape_patents
[{"position": 1, "rank": 0, "patent_id": "patent/US11696682B2/en", "patent_link": "https://patents.google.com/patent/US11696682B2/en", "serpapi_link": "https://serpapi.com/search.json?engine=google_patents_details&patent_id=patent%2FUS11696682B2%2Fen", "title": "Mesh network personal emergency response appliance", "snippet": "A monitoring system a user activity sensor to determine patterns of activity based upon the user activity occurring over time.", "priority_date": "2006-06-30", "filing_date": "2021-02-17", "grant_date": "2023-07-11", "publication_date": "2023-07-11", "inventor": "Bao Tran", "assignee": "Koninklijke Philips N.V.", "publication_number": "US11696682B2", "language": "en"
...
[REDACTED]
================================== [1m Ai Message [0m==================================
Here are patents related to quantum computing hardware:
1. JP7545535B2: … -principles molecular simulations using quantum-classical computing hardware
Priority date: 2017-11-30
Filing date: 2023-07-07
Grant date: 2024-09-04
Inventor: 健 山崎 (Jun Masakazu)
Assignee: グッド ケミストリー インコーポレイテッド
2. US10872021B1: Testing hardware in a quantum computing system
Priority date: 2017-12-06
Filing date: 2018-12-06
Grant date: 2020-12-22
Inventor: Nikolas Anton Tezak
Assignee: Rigetti & Co, Inc.
3. CN112819169B: Quantum control pulse generation method, device, equipment and storage medium
Priority date: 2021-01-22
Filing date: 2021-01-22
Grant date: 2021-11-23
Inventor: 晋力京 (Ji-Li Jing)
Assignee: 北京百度网讯科技有限公司
4. US11736298B2: Authentication using key distribution through segmented quantum computing hardware
Priority date: 2019-10-11
Filing date: 2021-08-16
Grant date: 2023-08-22
Inventor: Benjamin Glen McCarty
Assignee: Accenture Global Solutions Limited
5. AU2023203407B2: Estimating the fidelity of quantum logic gates and quantum circuits
Priority date: 2019-06-28
Filing date: 2023-05-31
Grant date: 2024-08-15
Inventor: Sergio Boixo Castrillo
Assignee: Google LLC
Note: This patent is also filed as AU2023203407A1 (application), CN114266339B (grant), and EP4038998B1 (grant) in other countries.
6. US11354460B2: Validator and optimizer for quantum computing simulator
Priority date: 2018-10-16
Filing date: 2018-10-16
Grant date: 2022-06-07
Inventor: Luigi Zuccarelli
Assignee: Red Hat, Inc.
7. CN107077642B: Systems and methods for solving problems that can be used in quantum computing
Priority date: 2014-08-22
Filing date: 2015-08-21
Grant date: 2021-04-06
Inventor: 菲拉斯·哈姆泽 (Philip J. Haussler)
Assignee: D-波系统公司
8. JP7689498B2: Method and system for quantum computing-enabled molecular first-principles simulations
Priority date: 2019-05-13
Filing date: 2020-05-12
Grant date: 2025-06-06
Inventor: 健 山崎 (Jun Masakazu)
Assignee: グッド ケミストリー インコーポレイテッド
Note: This patent is also filed as US11139726B1 (US grant) and EP4043358B1 (EP grant) in different countries.
9. US11010145B1: Retargetable compilation for quantum computing systems
Priority date: 2018-02-21
Filing date: 2019-02-21
Grant date: 2021-05-18
Inventor: Robert Stanley Smith
Assignee: Ri
成功です。当社のエージェントは、私たちのフィードバックを正常に実装し、関連する特許を返してくれました。
静的ブレークポイントを使用する代わりに、LangGraphのinterrupthuman_in_the_loop
def human_in_the_loop(state: AgentState):
value = interrupt('Would you like to revise the input or continue?')
return {"messages": value}
新しいグラフをインスタンス化し、フローを調整して、guardianassistant
new_builder = StateGraph(AgentState)
new_builder.add_node("guardian", guardian_moderation)
new_builder.add_node("block_message", block_message)
new_builder.add_node("human_in_the_loop", human_in_the_loop)
new_builder.add_node("assistant", call_llm)
new_builder.add_node("tools", ToolNode(tools))
new_builder.add_edge(START, "guardian")
new_builder.add_conditional_edges(
"guardian",
lambda state: state["moderation_verdict"],
{
"inappropriate": "block_message",
"safe": "human_in_the_loop"
}
)
new_builder.add_edge("block_message", END)
new_builder.add_edge("human_in_the_loop", "assistant")
new_builder.add_conditional_edges(
"assistant",
tools_condition,
)
new_builder.add_edge("tools", "assistant")
memory = MemorySaver()
new_graph = new_builder.compile(checkpointer=memory)
display(Image(new_graph.get_graph().draw_mermaid_png()))
アウトプット:
順調ですね。ではまず、エージェントのワークフローを開始するために、最初のインプットを入力しましょう。
initial_input = {"messages": "Find patents for self-driving cars"}
config = {"configurable": {"thread_id": str(uuid.uuid4())}}
new_graph.invoke(initial_input, config=config)
アウトプット:
{'messages': [HumanMessage(content='Find patents for self-driving cars', additional_kwargs={}, response_metadata={}, id='948c0871-1a47-4664-95f7-75ab511e043e')],
'__interrupt__': [Interrupt(value='Would you like to revise the input or continue?', id='8d6cf9e82f9e3de28d1f6dd3ef9d90aa')]}
ご覧のように、グラフが中断されており、入力内容を修正するか、続行するかを選択するようにメッセージが表示されます。入力内容を修正し、LangGraphのCommandhuman_feedback
for event in new_graph.stream(Command(resume="Forget that. Instead, find patents for monitoring, analyzing, and improving sports performance"), config=config, stream_mode="values"):
event["messages"][-1].pretty_print()
アウトプット:
================================[1m Human Message [0m=================================
Find patents for self-driving cars
================================[1m Human Message [0m=================================
Forget that. Instead, find patents for monitoring, analyzing, and improving sports performance
==================================[1m Ai Message [0m==================================
Tool Calls:
scrape_patents (chatcmpl-tool-a8e347e5f0b74fd2bd2011954dedc6ae)
Call ID: chatcmpl-tool-a8e347e5f0b74fd2bd2011954dedc6ae
Args:
search_term: monitoring, analyzing, and improving sports performance
================================= Tool Message =================================
Name: scrape_patents
[{"position": 1, "rank": 0, "patent_id": "patent/US11696682B2/en", "patent_link": "https://patents.google.com/patent/US11696682B2/en", "serpapi_link": "https://serpapi.com/search.json?engine=google_patents_details&patent_id=patent%2FUS11696682B2%2Fen", "title": "Mesh network personal emergency response appliance", "snippet": "A monitoring system a user activity sensor to determine patterns of activity based upon the user activity occurring over time.", "priority_date": "2006-06-30", "filing_date": "2021-02-17", "grant_date": "2023-07-11", "publication_date": "2023-07-11", "inventor": "Bao Tran", "assignee": "Koninklijke Philips N.V.", "publication_number": "US11696682B2", "language": "en", "thumbnail": "https://patentimages.storage.googleapis.com/dd/39/a4/021064cf6a4880/US11696682-20230711-D00000.png", "pdf": "https://patentimages.storage.googleapis.com/b3/ce/2a/b85df572cd035c/US11696682.pdf", "figures": [{"thumbnail": "https://patentimages.storage.googleapis.com/21/15/19/5061262f67d7fe/US11696682-20230711-D00000.png", "full": "https://patentimages.storage.googleapis.com/08/62/a3/037cf62a2bebd0/US11696682-20230711-D00000.png"}
...
[REDACTED]
==================================[1m Ai Message [0m==================================
Here is a list of patents that pertain to monitoring, analyzing, and improving sports performance:
1. **Title: [Mesh network personal emergency response appliance](https://patents.google.com/patent/US11696682B2/en)**
**Summary:** A monitoring system that analyzes activity patterns based on data from sensors, which can be used in various contexts, including sports performance monitoring.
**Country status:** US - Active
2. **Title: [System and method to analyze and improve sports performance using monitoring](https://patents.google.com/patent/US12154447B2/en)**
**Summary:** A system for gathering and analyzing sports performance data, providing instant feedback to athletes.
**Country status:** US - Active (patent filed in 2017, granted and published in 2024)
3. **Title: [Multi-sensor monitoring of athletic performance](https://patents.google.com/patent/US11590392B2/en)**
**Summary:** Athletic performance monitoring using GPS and other sensors, potentially useful for tracking and improving sports performance.
**Country status:** US - Active
4. **Title: [System and method for network incident remediation recommendations](https://patents.google.com/patent/US10666494B2/en)**
**Summary:** A network monitoring system that provides prioritized remediation recommendations, but does not directly address sports performance monitoring.
**Country status:** US - Active
5. **Title: [Physiological monitoring methods](https://patents.google.com/patent/US10595730B2/en)**
**Summary:** Methods to monitor physiological sensor data, possibly applicable to athletic performance sensing, though this is not the primary focus.
**Country status:** US - Active
6. **Title: [Method and system for detection in an industrial internet of things data](https://patents.google.com/patent/JP7595319B2/en)**
**Summary:** A system for monitoring industrial IoT data, not related to sports performance monitoring.
**Country status:** JP - Active
7. **Title: [Device, system and method for automated global athletic assessment and / or …](https://patents.google.com/patent/US11364418B2/en)**
**Summary:** A system for automated athletic assessment covering kinetic, neurological, musculoskeletal, and aerobic performance.
**Country status:** US - Active
8. **Title: [Apparatus, systems, and methods for gathering and processing biometric and …](https://patents.google.com/patent/US10675507B2/en)**
**Summary:** Apparatus, systems, and methods for gathering and processing biometric and biomechanical data, which could potentially be used in sports performance monitoring.
**Country status:** US - Active
9. **Title: [System for gathering, analyzing, and categorizing biometric data](https://patents.google.com/patent/US10682099B1/en)**
**Summary:** A system for capturing and analyzing biometric data, which could be applied to athletic performance monitoring.
**Country status:** US - Active
10. **Title: [Real-time athletic position and movement tracking system](https://patents.google.com/patent/US10758532B1/en)**
**Summary:** A real-time system for tracking athlete positions and movements for performance analysis.
**Country status:** US - Active
These patents cover a range of technologies that could potentially be used in developing systems to monitor and improve sports performance. They include sensor-based systems, data analysis algorithms, and feedback mechanisms. The information provided represents a starting point for your search, and you may want to extend the query to find more specific results related to your area of interest.
予想したとおり、グラフの状態はフィードバックによって正常に更新され、その後のAIとツールのメッセージによって適切な出力が生成されました。このエージェントは、自動運転車の特許を返す代わりに、人間のフィードバックを利用して、スポーツのパフォーマンスの監視、分析、改善に関連する特許を返しました。
このチュートリアルでは、LangGraphを使用して先行技術調査に特化したAIエージェントを構築し、いくつかのヒューマン・イン・ザ・ループ・ワークフローを実装できました。次のステップとして、マルチエージェント・システムで先行技術調査エージェントとともに使用できる別のAIエージェントを構築してみましょう。この二次エージェントは、先行技術調査エージェントから取得した情報を統合し、特許提案と既存の特許を比較するレポートを作成できます。独自のニーズに合ったエージェントを作りましょう。
生成AIを使用してワークフローとプロセスを自動化する強力なAIアシスタントとエージェントを構築、デプロイ、管理しましょう。
信頼できるAIソリューションでビジネスの未来を構築します。
IBMコンサルティングAIサービスは、企業がAIをトランスフォーメーションに活用する方法を再考するのに役立ちます。
1 Wang, Ge. “Humans in the Loop: The Design of Interactive AI Systems.” Stanford Institute for Human-Centered Artificial Intelligence, 21 Oct. 2019, hai.stanford.edu/news/humans-loop-design-interactive-ai-systems.