实现自己的AI视频监控系统-第四章-基于langchain的AI大模型与智能体应用1
文章目录
- 前言
- 一、基于LangChain的AI视频分析系统大模型赋能
- 1. 传统视频分析系统的局限性
- 2. LangChain:大模型应用的框架
- 什么是LangChain?
- LangChain的核心价值
- 为什么选择LangChain进行视频分析赋能?
- 3. 大模型赋能的价值与优势
- 4. 我们将实现什么
- 二、langchain的基本应用及简介
- 1.模型的调用
- 2.模型理解语义并调用工具
- 3.智能体的构建与调用
- 4.智能体的工具调用
- 5.智能体加入历史记忆
- 总结
- 下期预告
前言
在前面内容的实践下,我们实现了一个基础的AI视频监控系统,包括视频流的管理、视频的AI分析以及分析画面的推送与展示,在大模型技术快速发展的阶段,新的技术以其超强的能力给传统的视频分析系统注入了新的活力,本章节我们将基于langchain框架(一个大模型智能体应用框架),实现对AI视频分析系统的大模型赋能。
一、基于LangChain的AI视频分析系统大模型赋能
1. 传统视频分析系统的局限性
在我们之前实现的AI视频监控系统中,虽然已经能够完成基本的物体检测、行为识别和实时报警功能,但仍然存在一些局限性:
-
语义理解能力有限:传统计算机视觉模型难以理解复杂场景中的上下文关系
-
泛化能力不足:针对训练数据之外的场景或对象,识别准确率显著下降
-
多模态分析缺失:无法结合文本、语音等多模态信息进行综合分析
-
交互能力薄弱:系统只能提供预设类型的输出,缺乏自然语言交互能力
2. LangChain:大模型应用的框架
在深入探讨如何赋能之前,我们首先需要了解本次升级的核心技术——LangChain。
什么是LangChain?
LangChain是一个用于开发由大语言模型驱动的应用程序的框架。它不仅仅是一个简单的API包装器,而是一个全面的工具集,旨在将大型语言模型(如GPT-4、LLaMA等)与外部数据源和计算资源连接起来,创建真正强大且实用的AI应用。
LangChain的核心价值
-
组件化架构:提供了一套可组合的工具和组件,使开发者能够以模块化的方式构建复杂的大模型应用。
-
上下文感知:能够将大模型与上下文信息(如我们的视频分析结果)连接起来,大大增强了模型的实用性。
-
推理能力:通过Agent等机制,使大模型能够决定采取何种行动、使用何种工具,逐步完成复杂任务。
为什么选择LangChain进行视频分析赋能?
-
多模态融合能力:LangChain提供了将视觉模型输出(如YOLO检测结果)与语言模型结合的标准方式,使我们能够构建真正的多模态分析系统。
-
灵活的工作流设计:通过Chain和Agent机制,我们可以设计复杂但灵活的视频分析工作流,适应各种不同的监控场景。
-
上下文管理:LangChain的Memory组件特别适合视频监控场景,能够维持长期的上下文记忆,识别行为模式和异常趋势。
-
工具集成简单:可以轻松将现有的视频分析工具(如OpenCV、FFmpeg)封装为LangChain工具,供大模型调用。
3. 大模型赋能的价值与优势
通过集成大型语言模型(LLM)和LangChain框架,我们可以为视频分析系统带来以下提升:
-
高级语义理解:LLM能够理解视频内容的深层语义,进行推理和解释
-
零样本学习能力:无需额外训练即可处理未见过的场景和对象
-
多模态融合:结合视觉、文本和语音信息,提供更全面的分析
-
自然交互:支持以自然语言查询和获取系统分析结果
-
决策支持:基于多源信息提供决策建议和预测分析
4. 我们将实现什么
在本章节,我们将基于大模型和langchain技术实现以下基本功能:
- 设计用户交互终端:在先前的使用中,我们采用接口方式提供AI视频分析系统的能力,接下来,我们将设计一个即开即用的配套交互端。
- 语意及对话理解:我们的交互系统可以执行基本的功能,还可以依据用户的输入信息实现基本的对话功能。
- 功能及系统的调度:交互系统将基于大模型技术可以实现功能的调用以及运行情况的汇总。
二、langchain的基本应用及简介
在开始之前,需要简单介绍一下基本情况:
- 假定我们已经使用ollama工具部署了一个大模型服务,且大模型服务在中心计算端,我们通过api的方式访问ollama进行大模型功能的调用。
- 推荐使用jupyter notebook进行学习和测试
1.模型的调用
import langchain_ollama
print(langchain_ollama.__version__)
from langchain_ollama import ChatOllama
llm = ChatOllama(base_url="ollama所在的ip及端口", # 添加了协议和端口model="ollama所包含的模型名称",validate_model_on_init=True,temperature=0.0,num_predict=1024,
)
user_input = "I need some expert guidance for building an AI agent. Could you request assistance for me?"
res = llm.invoke(user_input)
print("--------------------------------------------")
print(res.content)0.3.7
--------------------------------------------
Of course! To provide the best guidance for building your AI agent, I'll need to know more about what kind of project you're working on and what specific areas you need help with. Here are a few questions that can help us get started:1. What is the primary purpose or application of your AI agent? (e.g., customer service chatbot, personal assistant, game player)
2. Are there any particular technologies or programming languages you plan to use?
3. Do you have experience in machine learning and AI development, or are you looking for guidance from scratch?
4. What kind of data will the AI agent be working with? (e.g., text, images, audio)
5. Are there specific features or capabilities that you want your AI agent to have?Once I know a bit more about what you're aiming for, I can help connect you with experts who specialize in those areas and provide tailored advice on how to proceed.
res["messages"][-1].pretty_print()
2.模型理解语义并调用工具
import langchain_ollama
from typing_extensions import Annotated, TypedDict
from langchain_ollama import ChatOllamaclass add(TypedDict):"""Add two integers."""# Annotations must have the type and can optionally include a default value and description (in that order).a: Annotated[int, ..., "First integer"]b: Annotated[int, ..., "Second integer"]class multiply(TypedDict):"""Multiply two integers."""a: Annotated[int, ..., "First integer"]b: Annotated[int, ..., "Second integer"]tools = [add, multiply]llm = ChatOllama(base_url="ollama所在的ip及端口", # 添加了协议和端口model="ollama所包含的模型名称",validate_model_on_init=True,temperature=0.0,num_predict=1024,
).bind_tools(tools)user_input = "1+1是多少?4*2是多少?"
res = llm.invoke(user_input)
print("--------------------------------------------")
for value in res.tool_calls:print(value["name"],value["args"])--------------------------------------------
add {'a': 1, 'b': 1}
multiply {'a': 4, 'b': 2}
3.智能体的构建与调用
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agentllm = ChatOllama(base_url="ollama所在的ip及端口", # 添加了协议和端口model="ollama所包含的模型名称",validate_model_on_init=True,temperature=0.0,num_predict=1024,
)
agent = create_react_agent(model=llm,# other parameterstools=[]
)res = agent.invoke({"messages":[{"role": "user", "content": "I need some expert guidance for building an AI agent. Could you request assistance for me?"}]})
res["messages"][-1].pretty_print()
================================== Ai Message ==================================Of course! To provide the best guidance for building your AI agent, I'll need to know more about what kind of project you're working on and what specific areas you need help with. Here are a few questions that can help us get started:1. What is the primary purpose or application of your AI agent? (e.g., customer service chatbot, personal assistant, game player)
2. Are there any particular technologies or programming languages you plan to use?
3. Do you have experience in machine learning and AI development, or are you looking for guidance from scratch?
4. What kind of data will the AI agent be working with? (e.g., text, images, audio)
5. Are there specific features or capabilities that you want your AI agent to have?Once I know a bit more about what you're aiming for, I can help connect you with experts who specialize in those areas and provide tailored advice on how to proceed.
4.智能体的工具调用
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool@tool(return_direct=True)
def add(a: int, b: int) -> int:"""Add two numbers"""return a + bllm = ChatOllama(base_url="ollama所在的ip及端口", # 添加了协议和端口model="ollama所包含的模型名称",validate_model_on_init=True,temperature=0.0,num_predict=1024,
)agent.invoke({"messages": [{"role": "user", "content": "what's 3 + 5?"}]}
)
agent = create_react_agent(model=llm,# other parameterstools=[add]
)res = agent.invoke({"messages":[{"role": "user", "content": "1+1?"}]})
res["messages"][-1].pretty_print()================================= Tool Message =================================
Name: add2
5.智能体加入历史记忆
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool
# 短期内存
from langgraph.checkpoint.memory import InMemorySavercheckpointer = InMemorySaver()@tool(return_direct=True)
def add(a: int, b: int) -> int:"""Add two numbers"""return a + bllm = ChatOllama(base_url="ollama所在的ip及端口", # 添加了协议和端口model="ollama所包含的模型名称",validate_model_on_init=True,temperature=0.0,num_predict=1024,
)agent = create_react_agent(model=llm,# other parameterstools=[add],checkpointer=checkpointer
)
# 设置静态上下文
config = {"configurable": {"thread_id": "1" }
}
res = agent.invoke({"messages":[{"role": "user", "content": "我是xxx,你好"}]},config=config)
res["messages"][-1].pretty_print()
================================== Ai Message ==================================你好,xxx!有什么我可以帮助你的吗?# 第二次执行
res = agent.invoke({"messages":[{"role": "user", "content": "你好,请问我是谁?"}]},config=config)
res["messages"][-1].pretty_print()
================================== Ai Message ==================================你提到自己是“xxx”。如果你指的是别的身份或者有其他问题需要解答,请提供更多信息。
总结
至此,我们已经了解了langchain框架的基本使用,接下来,我们将基于已有系统的功能和需求,设计一款AI视频监控系统独有的大模型交互系统,实现交互体验的提升、AI智能的跨越。
下期预告
- 交互系统基本需求分析
- 基于大模型和langchain的系统智能化建设