分阶段建设网站/成都网站seo性价比高

分阶段建设网站,成都网站seo性价比高,一分钟企业宣传片怎么拍,更好的网站制作运行根目录下几个ipynb文件- Learn-Agent.ipynb- 学习《Custom agent 自定义代理》部分- v1-Create-Custom-Agent.ipynb- v2-Create-Custom-Agent.ipynb- 基于v1,新增一些职位描述(JD)信息- v3-Create-Custom-Agent.ipynb- 基于v2&#xff0c…

运行根目录下几个ipynb文件- Learn-Agent.ipynb- 学习《Custom agent 自定义代理》部分- v1-Create-Custom-Agent.ipynb- v2-Create-Custom-Agent.ipynb- 基于v1,新增一些职位描述(JD)信息- v3-Create-Custom-Agent.ipynb- 基于v2,新增一些简历(CV)信息- Learn-Function calling.ipynb- 理解Function calling理念- 补充-路由链.ipynb- 与本课、与Agent无关,是前面课程遗留的知识点

一 Learn-Agent

1.1 Define tools 定义工具

  • LangChain Decorators ✨ | 🦜️🔗 LangChain
from dotenv import load_dotenv, find_dotenvload_dotenv(find_dotenv())from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitterloader = WebBaseLoader("https://docs.smith.langchain.com/overview")
docs = loader.load()
documents = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200
).split_documents(docs)
vector = FAISS.from_documents(documents, OpenAIEmbeddings())
retriever = vector.as_retriever()retriever.get_relevant_documents("how to upload a dataset")[0]

from langchain.tools.retriever import create_retriever_toolretriever_tool = create_retriever_tool(retriever,"langsmith_search","Search for information about LangSmith. For any questions about LangSmith, you must use this tool!",
)tools = [retriever_tool]

1.2 Create the agent 创建代理

from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)from langchain import hub# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")
prompt.messagesfrom langchain.agents import create_openai_functions_agentagent = create_openai_functions_agent(llm, tools, prompt)from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

1.3 Run the agent 运行代理

agent_executor.invoke({"input": "hi!"})agent_executor.invoke({"input": "how can langsmith help with testing?"})

1.4 Adding in memory 添加内存

# Here we pass in an empty list of messages for chat_history because it is the first message in the chat
agent_executor.invoke({"input": "hi! my name is bob", "chat_history": []})

from langchain_core.messages import AIMessage, HumanMessageagent_executor.invoke({"chat_history": [HumanMessage(content="hi! my name is bob"),AIMessage(content="Hello Bob! How can I assist you today?"),],"input": "what's my name?",}
)

1.5 keep track of these messages automatically 自动跟踪这些消息

from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistorymessage_history = ChatMessageHistory()agent_with_chat_history = RunnableWithMessageHistory(agent_executor,# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistorylambda session_id: message_history,input_messages_key="input",history_messages_key="chat_history",
)agent_with_chat_history.invoke({"input": "hi! I'm bob"},# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistoryconfig={"configurable": {"session_id": "<foo>"}},
)

agent_with_chat_history.invoke({"input": "what's my name?"},# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistoryconfig={"configurable": {"session_id": "<foo>"}},
)

二 Concepts 概念

  • Schema 图式
  • Agent 代理
  • AgentExecutor 代理执行器
  • Tools 工具
  • Toolkits 工具包

2.1 OpenAI tools

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-tools-agent")prompt.messages

2.2 JSON Chat Agent

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/react-chat-json")prompt.messages

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/structured-chat-agent")prompt.messagesprint(prompt.messages[0].prompt.template)

2.3 Structured chat

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/structured-chat-agent")print(prompt.messages[0].prompt.template)

2.4 ReAct

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/react")
promptprint(prompt.template)

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/self-ask-with-search")
promptprint(prompt.template)

三 Custom agent 自定义代理

3.1 Load the LLM 加载LLM

from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

3.2 Define Tools 定义工具

from langchain.agents import tool@tool
def get_word_length(word: str) -> int:"""Returns the length of a word."""return len(word)get_word_length.invoke("abc")tools = [get_word_length]tools

3.3 Create Prompt 创建提示

由于 OpenAI 函数调用针对工具使用进行了微调,因此我们几乎不需要任何关于如何推理或如何输出格式的说明。

我们将只有两个输入变量: input 和 agent_scratchpad

input 应为包含用户目标的字符串。

agent_scratchpad 应该是包含先前代理工具调用和相应工具输出的消息序列。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderprompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but don't know word's lens",),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)prompt.messages[0].prompt.template
# "You are very powerful assistant, but don't know current events"

3.4 Bind tools to LLM 将工具绑定到LLM

要将我们的工具传递给代理,我们只需将它们格式化为 OpenAI 工具格式,然后传递给我们的模型即可。(通过绑定函数,我们可以确保每次调用模型时都能将它们传入)。

llm_with_tools = llm.bind_tools(tools)llm_with_tools.kwargs['tools']

3.5 Create the Agent 创建代理

from langchain.agents.format_scratchpad.openai_tools import (format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParseragent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)

3.6 Run the agent 运行代理

from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)agent_executor.invoke({"input": "How many letters in the word eudca"})

llm.invoke("How many letters in the word educa")
# AIMessage(content='5')

3.7 Adding memory 添加内存

from langchain.prompts import MessagesPlaceholderMEMORY_KEY = "chat_history"
prompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but bad at calculating lengths of words.",),MessagesPlaceholder(variable_name=MEMORY_KEY),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)from langchain_core.messages import AIMessage, HumanMessagechat_history = []agent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),"chat_history": lambda x: x["chat_history"],}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)input1 = "how many letters in the word educa?"
result = agent_executor.invoke({"input": input1, "chat_history": chat_history})
chat_history.extend([HumanMessage(content=input1),AIMessage(content=result["output"]),]
)
agent_executor.invoke({"input": "is that a real word?", "chat_history": chat_history})

四 Tools 工具

from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapperapi_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100)
tool = WikipediaQueryRun(api_wrapper=api_wrapper)tool.name   # 'wikipedia'

4.1 Defining Custom Tools 定义自定义工具

# Import things that are needed generically
from langchain.pydantic_v1 import BaseModel, Field
from langchain.tools import BaseTool, StructuredTool, tool@tool
def search(query: str) -> str:"""Look up things online."""return "LangChain"print(search.name)
print(search.description)
print(search.args)"""search
search(query: str) -> str - Look up things online.
{'query': {'title': 'Query', 'type': 'string'}}"""@tool
def multiply(a: int, b: int) -> int:"""Multiply two numbers."""return a * bprint(multiply.name)
print(multiply.description)
print(multiply.args)"""multiply
multiply(a: int, b: int) -> int - Multiply two numbers.
{'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}"""from langchain_openai import ChatOpenAI# 参数temperature设置为0.0,从而减少生成答案的随机性。
llm = ChatOpenAI(temperature=0)from langchain.agents import load_tools# llm-math 工具结合语言模型和计算器用以进行数学计算
# wikipedia工具通过API连接到wikipedia进行搜索查询。
tools = load_tools(["llm-math","wikipedia"], llm=llm #第一步初始化的模型
)from langchain.agents import initialize_agent
from langchain.agents import AgentType# 初始化代理
agent= initialize_agent(tools, #第二步加载的工具llm, #第一步初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型handle_parsing_errors=True, #处理解析错误verbose = True #输出中间步骤
)agent("计算300的25%") 

question = "Tom M. Mitchell是一位美国计算机科学家,\
也是卡内基梅隆大学(CMU)的创始人大学教授。\
他写了哪本书呢?"agent(question) 

from langchain import hub
base_prompt = hub.pull("langchain-ai/openai-functions-template")
base_promptbase_prompt.messagesfrom langchain_experimental.tools import PythonREPLTooltools = [PythonREPLTool()]instructions = """You are an agent designed to write and execute python code to answer questions.
You have access to a python REPL, which you can use to execute python code.
If you get an error, debug your code and try again.
Only use the output of your code to answer the question. 
You might know the answer without running any code, but you should still run the code to get the answer.
If it does not seem like you can write code to answer the question, just return "I don't know" as the answer.
"""instructions = """您是一个设计用于编写和执行python代码以回答问题的代理。
您可以访问python REPL,可以使用它来执行python代码。
如果出现错误,请调试代码,然后重试。
只使用代码的输出来回答问题。
您可能在不运行任何代码的情况下就知道了答案,但您仍然应该运行代码来获得答案。
如果你似乎无法编写代码来回答这个问题,只需返回“我不知道”作为答案。
"""prompt = base_prompt.partial(instructions=instructions)
prompt

from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_functions_agentagent = create_openai_functions_agent(ChatOpenAI(temperature=0), tools, prompt)
agent

from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executorcustomer_list = ["小明","小黄","小红","小蓝","小橘","小绿",]agent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})

# !pip install pypinyinagent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})

import langchain
langchain.debug=True
agent_executor.invoke({"input": f"将使用pinyin拼音库这些客户名字转换为拼音,并打印输出列表: {customer_list}。"})
langchain.debug=False

import langchain
langchain.debug=True
agent_executor.invoke({"input": "第 10 个斐波那契数是多少?"})
langchain.debug=False
from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)from langchain.agents import tool@tool
def get_word_length(word: str) -> int:"""Returns the length of a word."""return len(word)get_word_length.invoke("abc")  # 3tools = [get_word_length]from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderprompt = ChatPromptTemplate.from_messages([("system","You are very powerful assistant, but don't know current events",),("user", "{input}"),MessagesPlaceholder(variable_name="agent_scratchpad"),]
)llm_with_tools = llm.bind_tools(tools)

4.2 关联工具

from langchain.agents.format_scratchpad.openai_tools import (format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParseragent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),}| prompt| llm_with_tools| OpenAIToolsAgentOutputParser()
)from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)list(agent_executor.stream({"input": "How many letters in the word eudca"}))

# 导入tool函数装饰器
from langchain.agents import tool
from datetime import date@tool
def time(text: str) -> str:"""返回今天的日期,用于任何需要知道今天日期的问题。\输入应该总是一个空字符串,\这个函数将总是返回今天的日期,任何日期计算应该在这个函数之外进行。"""return str(date.today())# 初始化代理
agent= initialize_agent(tools=[time], #将刚刚创建的时间工具加入代理llm=llm, #初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型handle_parsing_errors=True, #处理解析错误verbose = True #输出中间步骤
)# 使用代理询问今天的日期. 
# 注: 代理有时候可能会出错(该功能正在开发中)。如果出现错误,请尝试再次运行它。
agent("今天的日期是?") 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/899598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在MCU工程中优化CPU工作效率的几种方法

在嵌入式系统开发中&#xff0c;优化 CPU 工作效率对于提升系统性能、降低功耗、提高实时性至关重要。Keil 作为主流的嵌入式开发工具&#xff0c;提供了多种优化策略&#xff0c;包括 关键字使用、内存管理、字节对齐、算法优化 等。本文将从多个方面介绍如何在 Keil 工程中优…

Java开发者指南:深入理解HotStuff新型共识算法

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家、全栈领域优质创作者、高级开发工程师、高级信息系统项目管理师、系统架构师&#xff0c;数学与应用数学专业&#xff0c;10年以上多种混合语言开发经验&#xff0c;从事DICOM医学影像开发领域多年&#xff0c;熟悉DICOM协议及…

opencv图像处理之指纹验证

一、简介 在当今数字化时代&#xff0c;生物识别技术作为一种安全、便捷的身份验证方式&#xff0c;正广泛应用于各个领域。指纹识别作为生物识别技术中的佼佼者&#xff0c;因其独特性和稳定性&#xff0c;成为了众多应用场景的首选。今天&#xff0c;我们就来深入探讨如何利…

【STM32】知识点介绍一:硬件知识

文章目录 一、电源引脚简介二、电平信号三、电路分析 一、电源引脚简介 VCC、GND、VDD和VSS是电子电路中常见的术语&#xff0c;代表着不同的电源引脚或电压。 VCC&#xff08;Voltage at the Common Collector&#xff09;&#xff1a;VCC是指集电极&#xff08;Collector&am…

什么是 SEO(搜索引擎优化)?

您有网站吗&#xff0c;或者您正在考虑创建一个网站&#xff1f;您想吸引更多人加入您的业务吗&#xff1f;如果答案是肯定的&#xff0c;那么毫无疑问&#xff1a;SEO 应该是您营销工作的一部分。这是建立品牌和吸引用户访问您的网站的好方法。但它实际上意味着什么呢&#xf…

鸿蒙HarmonyOS NEXT设备升级应用数据迁移流程

数据迁移是什么 什么是数据迁移&#xff0c;对用户来讲就是本地数据的迁移&#xff0c;终端设备从HarmonyOS 3.1 Release API 9及之前版本&#xff08;单框架&#xff09;迁移到HarmonyOS NEXT&#xff08;双框架&#xff09;后保证本地数据不丢失。例如&#xff0c;我在某APP…

【现代深度学习技术】现代卷积神经网络04:含并行连接的网络(GoogLeNet)

【作者主页】Francek Chen 【专栏介绍】 ⌈ ⌈ ⌈PyTorch深度学习 ⌋ ⌋ ⌋ 深度学习 (DL, Deep Learning) 特指基于深层神经网络模型和方法的机器学习。它是在统计机器学习、人工神经网络等算法模型基础上&#xff0c;结合当代大数据和大算力的发展而发展出来的。深度学习最重…

【ESP32】ESP32与MQTT通信:实现传感器数据监测与设备控制

ESP32与MQTT通信 1 项目概览2 硬件组成3 MQTT协议解析MQTT协议简介MQTT核心概念本项目中的MQTT应用 4 MQTT Broker选择EMQX Broker其他常用MQTT Broker 5 代码解析初始化与配置MQTT消息处理发布传感器数据 6 MQTT话题TOPIC设计7 EMQX的优势在IoT项目中的体现8 MQTT通信流程9 应…

每天一篇目标检测文献(六)——Part One

今天看的是《Object Detection with Deep Learning: A Review》 目录 一、摘要 1.1 原文 1.2 翻译 二、介绍 2.1 信息区域选择 2.2 特征提取 2.3 分类 三、深度学习的简要回顾 3.1 历史、诞生、衰落和繁荣 3.2 CNN架构和优势 一、摘要 1.1 原文 Due to object dete…

Arthas线上问题诊断器

Arthas是Alibaba开源的java诊断工具 解决问题 这个类从哪个jar 包加载的&#xff1f;为什么会报各种相关的Exception&#xff1f; 遇到问题无法在线上debug&#xff0c;不能直通过加载日志再重新发布 有什么办法可以监控到JVM的实时运行状态&#xff1f; …

[Lc5_dfs+floodfill] 简介 | 图像渲染 | 岛屿数量

目录 0.floodfill算法简介 1.图像渲染 题解 2.岛屿数量 题解 之前我们在 bfs 中有介绍过[Lc15_bfsfloodfill] 图像渲染 | 岛屿数量 | 岛屿的最大面积 | 被围绕的区域&#xff0c;现在我们来看看 dfs 又是如何解决的呢 0.floodfill算法简介 floodfill算法又叫洪水灌溉或者…

JVM类加载器详解

文章目录 1.类与类加载器2.类加载器加载规则3.JVM 中内置的三个重要类加载器为什么 获取到 ClassLoader 为null就是 BootstrapClassLoader 加载的呢&#xff1f; 4.自定义类加载器什么时候需要自定义类加载器代码示例 5.双亲委派模式类与类加载器双亲委派模型双亲委派模型的执行…

【SPP】RFCOMM 层在SPP中互操作性要求深度解析

蓝牙串口协议&#xff08;SPP&#xff09;通过 RFCOMM 协议实现 RS232 串口仿真&#xff0c;其互操作性是设备互联的关键。本文基于蓝牙核心规范&#xff0c;深度解析 RFCOMM 层的能力矩阵、信号处理、流控机制及实战开发&#xff0c;结合状态机、流程图和代码示例&#xff0c;…

Gossip协议:分布式系统中的“八卦”传播艺术

目录 一、 什么是Gossip协议&#xff1f;二、 Gossip协议的应用 &#x1f4a1;三、 Gossip协议消息传播模式详解 &#x1f4da;四、 Gossip协议的优缺点五、 总结&#xff1a; &#x1f31f;我的其他文章也讲解的比较有趣&#x1f601;&#xff0c;如果喜欢博主的讲解方式&…

【C++初阶】----模板初阶

1.泛型函数 泛型编程&#xff1a;编写与类型无关的通用代码&#xff0c;是代码复用的一种手段。模板是泛型编程的基础。 2.函数模板 2.1函数模板的概念 函数模板代表了一个函数家族&#xff0c;该函数模板与类型无关&#xff0c;在使用时被参数化&#xff0c;根据实参类型…

git-- github的使用--账户和本地连接

以下指令在git 执行bash 流程&#xff1a;先看有没有密钥&#xff1b; 没有的话&#xff0c;在电脑生成密钥对&#xff0c;公钥复制到github&#xff1b; 要想使用https&#xff0c;配置令牌&#xff0c;注意令牌有期限问题&#xff0c;连接不了有可能是期限问题 一个电脑对…

Angular由一个bug说起之十五:自定义基于Overlay的Tooltip

背景 工具提示&#xff08;tooltip&#xff09;是一个常见的 UI 组件&#xff0c;用于在用户与页面元素交互时提供额外的信息。由于angular/material/tooltip的matTooltip只能显示纯文本&#xff0c;所以我们可以通过自定义Directive来实现一个灵活且功能丰富的tooltip Overlay…

搭建QNX Software Center的Docker环境

背景 本人使用 Ubuntu Server 22.04 服务器&#xff0c;所以没有图形界面&#xff0c;而 QNX Software Center 需要图形界面。为了保证服务器环境的整理&#xff0c;计划使用Docker部署QNX Software Center 一瓶安装图形界面。本方既是实现方案的记录。 资源 Dockerfile&…

C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)

前言 C#/.NET/.NET Core技术前沿周刊&#xff0c;你的每周技术指南针&#xff01;记录、追踪C#/.NET/.NET Core领域、生态的每周最新、最实用、最有价值的技术文章、社区动态、优质项目和学习资源等。让你时刻站在技术前沿&#xff0c;助力技术成长与视野拓宽。 欢迎投稿、推荐…

【STM32】WDG看门狗(学习笔记)

学习来源----->江协科技STM32 WDG简介 WDG&#xff08;Watchdog&#xff09;看门狗看门狗可以监控程序的运行状态&#xff0c;当程序因为设计漏洞、硬件故障、电磁干扰等原因&#xff0c;出现卡死或跑飞现象时&#xff0c;看门狗能及时复位程序&#xff0c;避免程序陷入长…