56 |
57 | ---
58 | src: ../../pages/common/series.md
59 | ---
60 |
61 | ---
62 | src: ../../pages/common/toc.md
63 | ---
64 |
65 | ---
66 | layout: iframe-right
67 | url: https://blog.langchain.dev/the-prompt-landscape/
68 | ---
69 |
70 | # Hub 热门提示词 🔥
71 |
72 | Popular Prompts in LangChain Hub
73 |
74 | 社区中各种不同用例的提示词在不断涌现
75 | A variety of prompts for different uses-cases have emerged.
76 |
77 | - [Prompt Engineering Guide](https://www.promptingguide.ai/) - [@dair_ai](https://twitter.com/dair_ai)
78 | - [Prompt Engineering](https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/) - [Lilian Weng](https://lilianweng.github.io/)
79 |
80 |
81 |
82 | LangChain Hub 推出一个多月以来也积累了丰富的提示词,大致可以被总结为十类用例
83 | Below we provide an overview of the major themes in prompting that we’ve seen since the launch of LangChain Hub and highlight interesting examples.
84 |
85 | ---
86 | layout: image
87 | image: https://blog.langchain.dev/content/images/size/w1000/2023/10/image-19.png
88 | ---
89 |
90 | ---
91 | layout: image
92 | image: https://blog.langchain.dev/content/images/size/w1000/2023/10/image-21.png
93 | ---
94 |
95 | ---
96 |
97 | # ✍️ 场景写作(Writing)
98 |
99 | Keywords: Writing Editor / Style, Content Generation
100 |
101 | 随着提示工程的普及,制作多样化内容的提示也不断增多(例如,邮件、博客文章、推文、教育学习材料)
102 | There's been a proliferation of prompts for producing diverse content (e.g. emails, blog posts, tweet threads, learning materials).
103 |
104 | - [SaaS User On-Boarding Email](https://smith.langchain.com/hub/gitmaxd/onboard-email): 生成引人注目的 SaaS 平台注册欢迎邮件
105 | - [Blog Generator](https://smith.langchain.com/hub/hardkothari/blog-generator):根据提供的上下文创建结构良好的博客文章
106 | - [Tweet from Text](https://smith.langchain.com/hub/hardkothari/tweet-from-text):在字数限制内、面向特定受众,制作简洁有效的推文
107 | - [Podcaster Tweet Thread](https://smith.langchain.com/hub/julia/podcaster-tweet-thread):给定播客的文字脚本,编写一条吸引眼球的推文
108 | - [Test Question Making](https://smith.langchain.com/hub/gregkamradt/test-question-making):为特定问题的测试(考试)创建一组精心设计的答案
109 |
110 | 另外,随着大语言模型的不断成熟,还有一些“绑定特定语言模型“的通用写作提示也在不断涌现
111 | Prompts to improve writing have widespread appeal given the impressive displays of creativity from specific LLMs.
112 |
113 | - Matt Shumer 编写的基于 GPT-4 模型的 [写作助手](https://smith.langchain.com/hub/rlm/matt-shumer-writing) 和 [风性化写作助手](https://smith.langchain.com/hub/rlm/matt-shumer-writing-style)
114 |
115 | @mattshumer_’s popular GPT-4 prompts provide ways to improve writing clarity or customize the style of LLM-generated text.
116 |
117 | ---
118 | layout: iframe
119 | url: https://smith.langchain.com/hub/gitmaxd/onboard-email
120 | ---
121 |
122 | ---
123 | layout: iframe
124 | url: https://smith.langchain.com/hub/rlm/matt-shumer-writing
125 | ---
126 |
127 | ---
128 | layout: iframe
129 | url: https://smith.langchain.com/hub/rlm/matt-shumer-writing-style
130 | ---
131 |
132 | ---
133 |
134 | # ⏳ 信息总结(Summarization)
135 |
136 | Keywords: Chain-of-density (CoD), Document Summerization
137 |
138 | [内容总结](https://blog.langchain.dev/llms-to-improve-documentation/) 是 LLM 的一个强大用例:例如 [Anthropic Claude 2](https://www.anthropic.com/index/claude-2),可以吸收超过 70 页的内容进行直接总结
139 | Summarization of content is a powerful LLM use-case. Longer context LLMs, e.g. Claude2, can absorb > 70 pages for direct summarization.
140 |
141 | [Chain of Density](https://browse.arxiv.org/pdf/2309.04269.pdf) 之类的提示技术提供了一种补充方法,从而产生密集且人性化的更好的摘要
142 | Prompting techniques like chain of density offer a complimentary approach, resulting in dense yet human-preferable summaries.
143 |
144 | - [Chain of Density](https://smith.langchain.com/hub/lawwu/chain_of_density):对给定文章(多次循环)生成越来越简洁、实体密集的摘要
145 | - [Anthropic Paper QA](https://smith.langchain.com/hub/hwchase17/anthropic-paper-qa):基于 Claude 2 的论文内容总结和审阅
146 | - [YouTube Transcript to Article](https://smith.langchain.com/hub/muhsinbashir/youtube-transcript-to-article):获取给定的 YouTube 视频文字并将其转换为结构良好且引人入胜的文章
147 |
148 | 此外,摘要可以应用于多种内容类型,例如聊天对话或特定于领域的数据([财务表摘要](https://smith.langchain.com/hub/hwchase17/financial-table-insights))
149 | In addition, summarization can be applied to diverse content types like chat conversations or domain specific data
150 |
151 | ---
152 | layout: iframe
153 | url: https://smith.langchain.com/hub/lawwu/chain_of_density
154 | ---
155 |
156 | ---
157 | layout: iframe
158 | url: https://smith.langchain.com/hub/hwchase17/anthropic-paper-qa
159 | ---
160 |
161 | ---
162 | layout: iframe
163 | url: https://smith.langchain.com/hub/muhsinbashir/youtube-transcript-to-article
164 | ---
165 |
166 | ---
167 | layout: iframe
168 | url: https://smith.langchain.com/hub/hwchase17/financial-table-insights
169 | ---
170 |
171 | ---
172 | layout: two-cols
173 | ---
174 |
175 | # 📋 信息提取(Extraction)
176 |
177 | Keywords: Knowledge Graph Triples, Function Calling
178 |
179 | LLM 可以是提取特定格式文本的强大工具,目前比较有代表性的是 OpenAI 的 [Function Calling](https://openai.com/blog/function-calling-and-other-api-updates) 功能
180 | LLMs can be powerful tools for extracting text in particular formats, often aided by OpenAI's function calling.
181 |
182 | 有些类库提供基于 Function Calling 的信息抽取功能,例如 [Instructor](https://jxnl.github.io/instructor/)
183 | Some frameworks developed to support it, such as Instructor.
184 |
185 | Hub 中也有针对特定提取任务设计的提示词,例如进行知识图谱三元组提取
186 | We've also seen prompts designed for specific extraction tasks, such as knowledge graph triple extraction.
187 |
188 | - [Instagraph](https://instagraph.ai/), [Text-to-Graph Playground](https://twitter.com/RLanceMartin/status/1691880034058064365)
189 |
190 | ::right::
191 |
192 |
193 |
194 | ---
195 | layout: iframe
196 | url: https://smith.langchain.com/hub/langchain/knowledge-triple-extractor
197 | ---
198 |
199 | ---
200 |
201 | # 👩💻 代码分析和生成(Code Analysis and Generation)
202 |
203 | Keywords: Code Review / Analysis,Code Generation
204 |
205 | 代码分析是最流行的 LLM 用例之一,Hub 中也有不少提示词是在这方面起作用的:
206 | Code analysis is one of the most popular LLM use-cases, we've seen a number of prompts related to this theme:
207 |
208 | - [Open Interpreter System](https://smith.langchain.com/hub/chuxij/open-interpreter-system):驱动 [Open Interpreter](https://www.pluralsight.com/resources/blog/data/chatgpt-code-interpreter-plugin-guide) 通过执行代码完成用户提出的各种目标
209 | - [Virtual Github PR Reviews](https://smith.langchain.com/hub/homanp/github-code-reviews):对 GitHub 代码仓库中的 Pull Request 进行代码审查
210 |
211 | ---
212 | layout: iframe
213 | url: https://smith.langchain.com/hub/chuxij/open-interpreter-system
214 | ---
215 |
216 | ---
217 | layout: iframe
218 | url: https://smith.langchain.com/hub/homanp/github-code-reviews
219 | ---
220 |
221 | ---
222 |
223 | # 🤖️ 提示优化(Prompt Optimization)
224 |
225 | Keywords: Image Creation, Instruction Improvement
226 |
227 | [Deepmind 的论文](https://arxiv.org/pdf/2309.03409.pdf) 指出:LLM 可以优化提示。
228 | The Deepmind work showing that LLMs can optimize prompts.
229 |
230 | 我们沿着这些思路看到了许多有趣的提示词;一个很好的例子是 [Midjourney](https://www.midjourney.com/) 的提示优化,如下所示:
231 | We’ve seen a number of interesting prompts along these lines; one good example is for Midjourney, as shown below:
232 |
233 |
234 |
235 |
236 |
Freddie Mercury electrifying the San Francisco Pride Parade stage, shining in a gleaming golden outfit, iconic microphone stand in hand, evoking the hyper-realistic style of Caravaggio, vivid and dynamic --ar 16:9 --q 2)
237 | Freddie Mercury performing at the 2023 San Francisco Pride Parade hyper realistic
238 |
239 |
240 |
241 | ---
242 | layout: iframe
243 | url: https://smith.langchain.com/hub/aemonk/midjourney_prompt_generator
244 | ---
245 |
246 | ---
247 | layout: iframe
248 | url: https://smith.langchain.com/hub/hardkothari/prompt-maker
249 | ---
250 |
251 | ---
252 | layout: iframe-right
253 | url: https://smith.langchain.com/hub/rlm/rag-prompt
254 | title: 📓 检索增强生成(RAG)
255 | ---
256 |
257 | # 📓 检索生成(RAG)
258 |
259 | Keywords: Adding Context
260 |
261 | 检索增强生成是现在非常流行的 LLM 应用场景
262 | RAG is a popular LLM application.
263 |
264 | 
265 |
266 | 它将 LLM 的推理能力与外部数据源的内容结合起来,这对于 [企业数据](https://www.glean.com/blog/how-to-build-an-ai-assistant-for-the-enterprise) 来说尤其强大
267 | RAG has particular promise because it marries the reasoning capability of LLMs with the content of external data sources, which is particularly powerful for enterprise data.
268 |
269 | ---
270 | layout: iframe
271 | url: https://smith.langchain.com/hub/rlm/rag-prompt-llama
272 | ---
273 |
274 | ---
275 | layout: iframe
276 | url: https://smith.langchain.com/hub/rlm/rag-prompt-mistral
277 | ---
278 |
279 | ---
280 | layout: iframe-right
281 | url: https://smith.langchain.com/hub/rlm/text-to-sql
282 | ---
283 |
284 | # 🗄️ SQL
285 |
286 | Keywords: Text-to-SQL Query
287 |
288 | 由于企业数据通常从 SQL 数据库中获取,因此使用 LLM 作为 SQL 查询的自然语言交互入口是一个合理的应用场景
289 | Because enterprise data is often captures in SQL databases, there is great interest in using LLMs as a natural language interface for SQL.
290 |
291 | 目前已经有[一些论文](https://arxiv.org/pdf/2204.00498.pdf)指出:给定数据表的一些特定信息,LLM 可以生成 SQL,包括每个 `CREATE TABLE` 描述、`SELECT` 语句的三个示例行
292 | A number of papers have reported that LLMs can generate SQL given some specific information about the table, including a CREATE TABLE description for each table followed by three example rows in a SELECT statement.
293 |
294 |
295 | LangChain 也提供了 [查询 SQL 数据库](https://python.langchain.com/docs/use_cases/qa_structured/sql) 的工具
296 | LangChain has numerous tools for querying SQL databases.
297 |
298 |
299 | ---
300 |
301 | # 📝 评价打分(LLM Graders)
302 |
303 | Keywords: LLM Evaluators, Bias Checking
304 |
305 | 把 LLM 用作评分器是一个很有趣的想法,核心思想是利用 LLM 评判一个响应结果和基准答案的匹配度
306 | The central idea of using LLMs as graders is to utilize the discrimination of an LLM to grade a response relative to a ground truth answer.
307 |
308 | - [Model Evaluator](https://smith.langchain.com/hub/simonp/model-evaluator):根据自定义标准对模型或现有的 LangSmith 运行/数据集进行评分
309 | - [Assumption Checker](https://smith.langchain.com/hub/smithing-gold/assumption-checker):识别查询中的关键假设,然后形成可检查的事实并评估这些假设的问题
310 |
311 | 事实上,包括 [OpenAI Cookbook](https://github.com/openai/openai-cookbook/blob/main/examples/evaluation/How_to_eval_abstractive_summarization.ipynb),以及 [LangChain](tps://twitter.com/hwchase17/status/1692220493657485674)、[LlamaIndex](https://twitter.com/jerryjliu0/status/1703074710077260092) 都展示过这种使用 LLM 来打分的技巧
312 | In fact, this idea that has been broadly showcased in OpenAI cookbooks and open source projects.
313 |
314 | LangSmith 的评价系统也做了很多类似的 [测试和评估](https://docs.smith.langchain.com/evaluation) 功能探索
315 | Much of the work on LangSmith has focused on evaluation support.
316 |
317 | ---
318 | layout: iframe
319 | url: https://smith.langchain.com/hub/simonp/model-evaluator
320 | ---
321 |
322 | ---
323 | layout: iframe
324 | url: https://smith.langchain.com/hub/smithing-gold/assumption-checker
325 | ---
326 |
327 | ---
328 | layout: two-cols
329 | title: 📚 合成数据生成(Synthetic Data Generation)
330 | ---
331 |
332 | # 📚 合成数据生成(Synthetic Data Gen)
333 |
334 | Keywords: Fine-tuning Data, Evaluation Tests
335 |
336 | 微调 LLM 是引导 LLM 行为的主要方法之一,但是收集用于微调的训练数据是一个挑战
337 | Fine-tuning LLMs is one of the primary ways to steer LLM behavior, while gathering training data for fine-tuning is a challenge.
338 |
339 | 一个思路:使用 LLM 生成微调训练所需要的合成数据集
340 | Many work has focused on using LLMs to generate synthetic datasets.
341 |
342 | - [Synthetic Training Data](https://smith.langchain.com/hub/gitmaxd/synthetic-training-data):OpenAI 训练数据生成
343 | - [Question Answer Pair](https://smith.langchain.com/hub/homanp/question-answer-pair):基于上下文的问答集合生成
344 |
345 | ::right::
346 |
347 |
348 |
349 | ---
350 | layout: iframe
351 | url: https://smith.langchain.com/hub/gitmaxd/synthetic-training-data
352 | ---
353 |
354 | ---
355 | layout: iframe
356 | url: https://smith.langchain.com/hub/homanp/question-answer-pair
357 | ---
358 |
359 | ---
360 | layout: image-right
361 | image: https://pbs.twimg.com/media/F5_OeQdXoAAkAxo?format=jpg&name=medium
362 | ---
363 |
364 | # 🧠 推论(Reasoning)
365 |
366 | Keywords: Chain-of-Thought, Agents (ReAct)
367 |
368 | [论文](https://arxiv.org/pdf/2309.03409.pdf)研究表明:[思考链](https://arxiv.org/abs/2201.11903)有助于提升 LLM 的准确率
369 | This has found broad appeal because it improves many reasoning tasks by a large margin and is easy to implement.
370 |
371 | - `Let's think step by step`
372 | - `Take a deep breath and work on this problem step-by-step`
373 | - [Tree of Thought](https://arxiv.org/abs/2305.10601):思考链 ➡️ 思考树
374 |
375 | [思考链](https://twitter.com/cwolferesearch/status/1657122778984660993)提示还可以附加到许多任务中,并且对于 [Agent](https://lilianweng.github.io/posts/2023-06-23-agent/) 来说变得尤为重要。例如,[ReAct Agent](https://www.promptingguide.ai/techniques/react) 以交错的方式将工具使用与推理结合起来
376 | Reasoning prompts as shown above can be appended as simple instructions to many tasks and have become particularly important for agents.
377 |
378 | ---
379 | layout: image
380 | image: https://pbs.twimg.com/media/Fv9G3cFWwAA6yTV?format=jpg&name=4096x4096
381 | ---
382 |
383 | ---
384 | layout: iframe
385 | url: https://smith.langchain.com/hub/shoggoth13/react-chat-agent
386 | ---
387 |
388 | ---
389 | layout: iframe
390 | url: https://smith.langchain.com/hub/jacob/langchain-tsdoc-research-agent
391 | ---
392 |
393 | ---
394 | src: ../../pages/common/refs.md
395 | ---
396 |
397 | ---
398 | src: ../../pages/common/end.md
399 | ---
400 |
--------------------------------------------------------------------------------
/201-langchain-modules/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/201-langchain-modules/src/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "slidev",
5 | "build": "slidev build --base /201-langchain-modules/ --out ../../dist/201-langchain-modules",
6 | "export": "slidev export --dark --timeout 0 --output ../../pdfs/201-langchain-modules.pdf"
7 | },
8 | "devDependencies": {
9 | "@slidev/cli": "^0.42.4",
10 | "@slidev/theme-seriph": "^0.21.3"
11 | },
12 | "slidev": {
13 | "addons": [
14 | "../../addons/webup"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/201-langchain-modules/src/slides.md:
--------------------------------------------------------------------------------
1 | ---
2 | # See all frontmatter configurations: https://sli.dev/custom/#frontmatter-configures
3 | # theme id or package name, see also: https://sli.dev/themes/use.html
4 | theme: 'seriph'
5 | # titleTemplate for the webpage, `%s` will be replaced by the page's title
6 | titleTemplate: '%s|WebUP'
7 | # some information about the slides, markdown enabled
8 | info: |
9 | AGI 学习笔记,仅供个人学习使用
10 | # favicon, can be a local file path or URL
11 | favicon: https://files.codelife.cc/user-website-icon/20220523/5hyKeZxOknU2owAPvnSWD1388.png?x-oss-process=image/resize,limit_0,m_fill,w_25,h_25/quality,q_92/format,webp
12 | # enabled pdf downloading in SPA build, can also be a custom url
13 | download: 'https://github.com/webup/agi-talks/raw/master/pdfs/201-langchain-modules.pdf'
14 | # syntax highlighter, can be 'prism' or 'shiki'
15 | highlighter: 'shiki'
16 | # controls whether texts in slides are selectable
17 | selectable: false
18 | # enable slide recording, can be boolean, 'dev' or 'build'
19 | record: 'build'
20 | # define transition between slides
21 | transition: fade
22 | # default frontmatter applies to all slides
23 | defaults:
24 |
25 | # slide configurations
26 | hideInToc: true
27 | layout: cover
28 | class: text-center
29 | background: https://source.unsplash.com/collection/94734566/1920x1080
30 | ---
31 |
32 | # LangChain 模块解析(上)
33 |
34 | LangChain Modules Hands-on
35 |
36 |
56 |
57 | ---
58 | src: ../../pages/common/series.md
59 | ---
60 |
61 | ---
62 | src: ../../pages/common/toc.md
63 | ---
64 |
65 | ---
66 |
67 | # Agent vs. Chain
68 |
69 | 如果说 Agent 是 Chain 的进化形态,那哪些方面是对等的?哪些地方又存在质变?
70 |
71 | ➡️ Agent 继承了 Chain 的所有能力
72 |
73 | - Chain 的能力构成了 Agent 的 “推理链” 能力基础
74 | - Agent 的执行器(Executor)就是基于 LLM Chain 实现的
75 | - Agent 自身具备和 Chain 类似的 “调用 / 执行” 接口的能力
76 |
77 |
78 |
79 | ⬆️⬆️ Agent 在 Chain 的能力基础上进化出了两个核心能力
80 |
81 | - 一条思考链(Chain of Thought):Agent 可以规划和调度推理链,会思考分步骤的、每一步的行动
82 | - 一个工具箱(Toolbox):Agent 自带工具体系,可以接入并调用外部工具(工具可以按既定接口规范定制)
83 | - Agent 只关注每个工具的输入输出(格式及内容),工具内部可以自行进行本地和 Web 接口调用
84 |
85 | ---
86 |
87 | # Agent 的思考链模式:ReAct
88 |
89 | [ReAct](https://react-lm.github.io/): Synergizing Reasoning and Acting in Language Models
90 |
91 | 
92 |
93 | ReAct 使用大语言模型同时生成推理链和行动,两者交替出现,相互支持:
94 | - 推理链帮助 Agent 制定、跟踪和更新行动计划
95 | - 行动让 Agent 与环境上下文交互,获取更多信息支持推理
96 |
97 | ♻️流程概览:给出任务 ➡️ 推理下一步行动 ➡️ 行动并更新环境 ➡️ 观察并推理下一步行动 ➡️ 循环直至任务完成
98 |
99 | ---
100 | level: 2
101 | ---
102 |
103 | # 🌰 使用 ReAct 模式的 Agent
104 |
105 | ```ts {7-16|18-21|all} {maxHeight:'90%'}
106 | import { initializeAgentExecutorWithOptions } from "langchain/agents";
107 | import { OpenAI } from "langchain/llms/openai";
108 | import { SerpAPI } from "langchain/tools";
109 | import { Calculator } from "langchain/tools/calculator";
110 |
111 | const model = new OpenAI({ temperature: 0 });
112 | const tools = [
113 | /* Web 搜索工具 */
114 | new SerpAPI(process.env.SERPAPI_API_KEY, {
115 | location: "Austin,Texas,United States",
116 | hl: "en",
117 | gl: "us",
118 | }),
119 | /* 本地计算器工具 */
120 | new Calculator(),
121 | ];
122 |
123 | const executor = await initializeAgentExecutorWithOptions(tools, model, {
124 | agentType: "zero-shot-react-description",
125 | verbose: true,
126 | });
127 |
128 | const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`;
129 | const result = await executor.call({ input });
130 | ```
131 |
132 | ---
133 | layout: iframe
134 | url: https://smith.langchain.com/public/99f09caa-d6e4-4424-a8cd-7daa02ee5e13/r
135 | ---
136 |
137 | ---
138 | level: 2
139 | ---
140 |
141 | # ReAct 模式的核心提示词
142 |
143 | ```ts
144 | export const PREFIX = `Answer the following questions as best you can. You have access to the following tools:`;
145 |
146 | export const FORMAT_INSTRUCTIONS = `Use the following format in your response:
147 |
148 | Question: the input question you must answer
149 | Thought: you should always think about what to do
150 | Action: the action to take, should be one of [{tool_names}]
151 | Action Input: the input to the action
152 | Observation: the result of the action
153 | ... (this Thought/Action/Action Input/Observation can repeat N times)
154 | Thought: I now know the final answer
155 | Final Answer: the final answer to the original input question`;
156 |
157 | export const SUFFIX = `Begin!
158 |
159 | Question: {input}
160 | Thought:{agent_scratchpad}`;
161 | ```
162 |
163 | ```ts
164 | const executor = await initializeAgentExecutorWithOptions(tools, chat, {
165 | agentType: "",
166 | agentArgs: { prefix, suffix }, // 可自定义前置和后置提示词
167 | });
168 | ```
169 |
170 | ---
171 |
172 | # Agent 的思考链模式:Plan and Execute
173 |
174 | [Plan-and-Solve Prompting](https://arxiv.org/pdf/2305.04091.pdf): Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models
175 |
176 | 顾名思义,Agent 通过首先计划要做什么,然后执行子任务来实现目标
177 |
178 | - 这个想法很大程度上是受到 [BabyAGI](https://github.com/yoheinakajima/babyagi) 和后来的《Plan-and-Solve Prompting》论文的启发
179 | - 计划几乎总是由 LLM 完成;执行通常由单独的(带有工具的)Agent 完成
180 |
181 |
182 |
183 | 该 Agent 有两个主要的关键步骤:
184 |
185 | 1. 首先,Agent 使用 LLM 创建一个计划,以明确的步骤回答查询
186 | 2. 一旦制定了计划,它就会使用传统的 Agent(比如 ReAct)来解决每个步骤
187 |
188 |
189 |
190 | > 其想法是,计划步骤通过将较大的任务分解为更简单的子任务,使 LLM 更加“步入正轨”。
191 | >
192 | > 但是,与传统 Agent 相比,此方法需要更多单独的 LLM 查询,并且延迟更高。
193 |
194 | ---
195 | level: 2
196 | ---
197 |
198 | # 🌰 使用 Plan and Execute 模式的 Agent
199 |
200 | 该模式的 Agent 目前仅支持 Chat 模型
201 |
202 | ```ts {13-16|all}
203 | import { Calculator } from "langchain/tools/calculator";
204 | import { SerpAPI } from "langchain/tools";
205 | import { ChatOpenAI } from "langchain/chat_models/openai";
206 | import { PlanAndExecuteAgentExecutor } from "langchain/experimental/plan_and_execute";
207 |
208 | const tools = [new Calculator(), new SerpAPI()];
209 | const model = new ChatOpenAI({
210 | temperature: 0,
211 | modelName: "gpt-3.5-turbo",
212 | verbose: true,
213 | });
214 |
215 | const executor = PlanAndExecuteAgentExecutor.fromLLMAndTools({
216 | llm: model,
217 | tools,
218 | });
219 |
220 | const result = await executor.call({
221 | input: `Who is the current president of the United States? What is their current age raised to the second power?`,
222 | });
223 | ```
224 |
225 | ---
226 | layout: iframe
227 | url: https://smith.langchain.com/public/33110a27-032f-4d6d-a121-4063931d189b/r
228 | ---
229 |
230 | ---
231 | level: 2
232 | ---
233 |
234 | # Plan and Execute 模式的核心提示词
235 |
236 | ```ts
237 | export const PLANNER_SYSTEM_PROMPT_MESSAGE_TEMPLATE = [
238 | `Let's first understand the problem and devise a plan to solve the problem.`,
239 | `Please output the plan starting with the header "Plan:"`,
240 | `and then followed by a numbered list of steps.`,
241 | `Please make the plan the minimum number of steps required`,
242 | `to answer the query or complete the task accurately and precisely.`,
243 | `Your steps should be general, and should not require a specific method to solve a step. If the task is a question,`,
244 | `the final step in the plan must be the following: "Given the above steps taken,`,
245 | `please respond to the original query."`,
246 | `At the end of your plan, say ""`,
247 | ].join(" ");
248 |
249 | export const DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE = `Previous steps: {previous_steps}
250 |
251 | Current objective: {current_step}
252 |
253 | {agent_scratchpad}
254 |
255 | You may extract and combine relevant data from your previous steps when responding to me.`;
256 | ```
257 |
258 | ---
259 |
260 | # ReAct 模式的工具能力强化:JSON Schema
261 |
262 | 工具的输入输出限定为单个字符串 ➡️ 可以使用工具提供的 JSON Schema 接口定义来扩展输入输出
263 |
264 | ```ts {10-20|23-25|all} {maxHeight:'85%'}
265 | import { z } from "zod";
266 | import { ChatOpenAI } from "langchain/chat_models/openai";
267 | import { initializeAgentExecutorWithOptions } from "langchain/agents";
268 | import { Calculator } from "langchain/tools/calculator";
269 | import { DynamicStructuredTool } from "langchain/tools";
270 |
271 | const model = new ChatOpenAI({ temperature: 0 });
272 | const tools = [
273 | new Calculator(), // Older existing single input tools will still work
274 | new DynamicStructuredTool({
275 | name: "random-number-generator",
276 | description: "generates a random number between two input numbers",
277 | schema: z.object({
278 | low: z.number().describe("The lower bound of the generated number"),
279 | high: z.number().describe("The upper bound of the generated number"),
280 | }),
281 | func: async ({ low, high }) =>
282 | (Math.random() * (high - low) + low).toString(), // Outputs still must be strings
283 | returnDirect: false, // This is an option that allows the tool to return the output directly
284 | }),
285 | ];
286 |
287 | const executor = await initializeAgentExecutorWithOptions(tools, model, {
288 | agentType: "structured-chat-zero-shot-react-description",
289 | });
290 |
291 | const input = `What is a random number between 5 and 10 raised to the second power?`;
292 | const result = await executor.call({ input });
293 | ```
294 |
295 | ---
296 | layout: iframe
297 | url: https://smith.langchain.com/public/1b23a713-58e3-42f8-93db-60fa99cb1207/r
298 | ---
299 |
300 | ---
301 |
302 | # ReAct 模式的工具能力强化:OpenAI Functions
303 |
304 | OpenAI 模型(如 `gpt-3.5-turbo-0613`)已经过微调,可以检测何时应调用函数并响应应传递给函数的输入
305 |
306 | - OpenAI Functions 的目标是比通用文本完成或聊天 API 更可靠地返回有效且有用的函数调用
307 | - 在 API 调用中,您可以描述函数并让模型智能地选择输出包含调用这些函数的参数的 JSON 对象
308 |
309 | ```ts
310 | import { initializeAgentExecutorWithOptions } from "langchain/agents";
311 | import { ChatOpenAI } from "langchain/chat_models/openai";
312 | import { SerpAPI } from "langchain/tools";
313 | import { Calculator } from "langchain/tools/calculator";
314 |
315 | const tools = [new Calculator(), new SerpAPI()];
316 | const chat = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });
317 |
318 | const executor = await initializeAgentExecutorWithOptions(tools, chat, {
319 | agentType: "openai-functions",
320 | verbose: true,
321 | });
322 |
323 | const result = await executor.run("What is the weather in New York?");
324 | ```
325 |
326 | ---
327 | layout: iframe
328 | url: https://smith.langchain.com/public/f81e509f-9a51-4f0b-9554-4b351cd8ebdb/r
329 | ---
330 |
331 | ---
332 |
333 | # ReAct 模式下的 XML Agent
334 |
335 | 某些语言模型(例如 [Anthropic](https://www.anthropic.com/) 的 Claude)特别擅长推理/编写 XML
336 |
337 | ```ts
338 | import { ChatAnthropic } from "langchain/chat_models/anthropic";
339 | import { initializeAgentExecutorWithOptions } from "langchain/agents";
340 | import { SerpAPI } from "langchain/tools";
341 |
342 | const model = new ChatAnthropic({ modelName: "claude-2", temperature: 0.1 });
343 | const tools = [new SerpAPI()];
344 |
345 | const executor = await initializeAgentExecutorWithOptions(tools, model, {
346 | agentType: "xml",
347 | verbose: true,
348 | });
349 | console.log("Loaded agent.");
350 |
351 | const input = `What is the weather in Honolulu?`;
352 | const result = await executor.call({ input });
353 | ```
354 |
355 | ---
356 | layout: iframe
357 | url: https://smith.langchain.com/public/d0acd50a-f99d-4af0-ae66-9009de319fb5/r
358 | ---
359 |
360 | ---
361 |
362 | # Agent 的工具箱
363 |
364 | 工具是 Agent 可以用来与世界交互的功能
365 |
366 | Agent 只关心工具的输入输出,内部实现对 Agent 透明
367 |
368 | - 这些工具可以是通用实用程序(例如搜索)、其它 Chain 调用,甚至其它 Agent 调用
369 |
370 |
371 |
372 | Agent 定义了工具的标准接口,以实现无缝集成
373 |
374 | - 具体来说,工具的接口具有单个文本输入和单个文本输出
375 | - 它包括名称和描述,用于向模型传达该工具的用途以及何时使用它
376 |
377 | ```ts
378 | abstract class Tool {
379 | abstract name: string;
380 | abstract description: string;
381 |
382 | abstract _call(arg: string): Promise;
383 | }
384 | ```
385 |
386 | ---
387 | level: 2
388 | ---
389 |
390 | # 🌰 Calculator 工具的实现
391 |
392 | ```ts {all|9-12|1,17|all}
393 | import { Parser } from "expr-eval";
394 | import { Tool } from "./base.js";
395 |
396 | /**
397 | * The Calculator class is a tool used to evaluate mathematical
398 | * expressions. It extends the base Tool class.
399 | */
400 | export class Calculator extends Tool {
401 | name = "calculator";
402 |
403 | description = `Useful for getting the result of a math expression.
404 | The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.`;
405 |
406 | /** @ignore */
407 | async _call(input: string) {
408 | try {
409 | return Parser.evaluate(input).toString();
410 | } catch (error) {
411 | return "I don't know how to do that.";
412 | }
413 | }
414 | }
415 | ```
416 |
417 | ---
418 | level: 2
419 | ---
420 |
421 | # Tool 的结构化输入定义
422 |
423 | Tool 可以通过 JSON Schema 来强化输入的定义,在 JS/TS SDK 中会使用 Zod 转换 TypeScript 类型声明
424 |
425 | 如下所示,SerpAPI 工具中对参数接口进行了详细的定义:
426 |
427 | ```ts {all} {maxHeight:'80%'}
428 | // Copied over from `serpapi` package
429 | interface BaseParameters {
430 | /**
431 | * Parameter defines the device to use to get the results. It can be set to
432 | * `desktop` (default) to use a regular browser, `tablet` to use a tablet browser
433 | * (currently using iPads), or `mobile` to use a mobile browser (currently
434 | * using iPhones).
435 | */
436 | device?: "desktop" | "tablet" | "mobile";
437 | /**
438 | * Parameter will force SerpApi to fetch the Google results even if a cached
439 | * version is already present. A cache is served only if the query and all
440 | * parameters are exactly the same. Cache expires after 1h. Cached searches
441 | * are free, and are not counted towards your searches per month. It can be set
442 | * to `false` (default) to allow results from the cache, or `true` to disallow
443 | * results from the cache. `no_cache` and `async` parameters should not be used together.
444 | */
445 | no_cache?: boolean;
446 | /**
447 | * Specify the client-side timeout of the request. In milliseconds.
448 | */
449 | timeout?: number;
450 | }
451 |
452 | export interface SerpAPIParameters extends BaseParameters {
453 | /**
454 | * Search Query
455 | * Parameter defines the query you want to search. You can use anything that you
456 | * would use in a regular Google search. e.g. `inurl:`, `site:`, `intitle:`. We
457 | * also support advanced search query parameters such as as_dt and as_eq. See the
458 | * [full list](https://serpapi.com/advanced-google-query-parameters) of supported
459 | * advanced search query parameters.
460 | */
461 | q: string;
462 | /**
463 | * Location
464 | * Parameter defines from where you want the search to originate. If several
465 | * locations match the location requested, we'll pick the most popular one. Head to
466 | * [/locations.json API](https://serpapi.com/locations-api) if you need more
467 | * precise control. location and uule parameters can't be used together. Avoid
468 | * utilizing location when setting the location outside the U.S. when using Google
469 | * Shopping and/or Google Product API.
470 | */
471 | location?: string;
472 | /**
473 | * Encoded Location
474 | * Parameter is the Google encoded location you want to use for the search. uule
475 | * and location parameters can't be used together.
476 | */
477 | uule?: string;
478 | /**
479 | * Google Place ID
480 | * Parameter defines the id (`CID`) of the Google My Business listing you want to
481 | * scrape. Also known as Google Place ID.
482 | */
483 | ludocid?: string;
484 | /**
485 | * Additional Google Place ID
486 | * Parameter that you might have to use to force the knowledge graph map view to
487 | * show up. You can find the lsig ID by using our [Local Pack
488 | * API](https://serpapi.com/local-pack) or [Places Results
489 | * API](https://serpapi.com/places-results).
490 | * lsig ID is also available via a redirect Google uses within [Google My
491 | * Business](https://www.google.com/business/).
492 | */
493 | lsig?: string;
494 | /**
495 | * Google Knowledge Graph ID
496 | * Parameter defines the id (`KGMID`) of the Google Knowledge Graph listing you
497 | * want to scrape. Also known as Google Knowledge Graph ID. Searches with kgmid
498 | * parameter will return results for the originally encrypted search parameters.
499 | * For some searches, kgmid may override all other parameters except start, and num
500 | * parameters.
501 | */
502 | kgmid?: string;
503 | /**
504 | * Google Cached Search Parameters ID
505 | * Parameter defines the cached search parameters of the Google Search you want to
506 | * scrape. Searches with si parameter will return results for the originally
507 | * encrypted search parameters. For some searches, si may override all other
508 | * parameters except start, and num parameters. si can be used to scrape Google
509 | * Knowledge Graph Tabs.
510 | */
511 | si?: string;
512 | /**
513 | * Domain
514 | * Parameter defines the Google domain to use. It defaults to `google.com`. Head to
515 | * the [Google domains page](https://serpapi.com/google-domains) for a full list of
516 | * supported Google domains.
517 | */
518 | google_domain?: string;
519 | /**
520 | * Country
521 | * Parameter defines the country to use for the Google search. It's a two-letter
522 | * country code. (e.g., `us` for the United States, `uk` for United Kingdom, or
523 | * `fr` for France). Head to the [Google countries
524 | * page](https://serpapi.com/google-countries) for a full list of supported Google
525 | * countries.
526 | */
527 | gl?: string;
528 | /**
529 | * Language
530 | * Parameter defines the language to use for the Google search. It's a two-letter
531 | * language code. (e.g., `en` for English, `es` for Spanish, or `fr` for French).
532 | * Head to the [Google languages page](https://serpapi.com/google-languages) for a
533 | * full list of supported Google languages.
534 | */
535 | hl?: string;
536 | /**
537 | * Set Multiple Languages
538 | * Parameter defines one or multiple languages to limit the search to. It uses
539 | * `lang_{two-letter language code}` to specify languages and `|` as a delimiter.
540 | * (e.g., `lang_fr|lang_de` will only search French and German pages). Head to the
541 | * [Google lr languages page](https://serpapi.com/google-lr-languages) for a full
542 | * list of supported languages.
543 | */
544 | lr?: string;
545 | /**
546 | * as_dt
547 | * Parameter controls whether to include or exclude results from the site named in
548 | * the as_sitesearch parameter.
549 | */
550 | as_dt?: string;
551 | /**
552 | * as_epq
553 | * Parameter identifies a phrase that all documents in the search results must
554 | * contain. You can also use the [phrase
555 | * search](https://developers.google.com/custom-search/docs/xml_results#PhraseSearchqt)
556 | * query term to search for a phrase.
557 | */
558 | as_epq?: string;
559 | /**
560 | * as_eq
561 | * Parameter identifies a word or phrase that should not appear in any documents in
562 | * the search results. You can also use the [exclude
563 | * query](https://developers.google.com/custom-search/docs/xml_results#Excludeqt)
564 | * term to ensure that a particular word or phrase will not appear in the documents
565 | * in a set of search results.
566 | */
567 | as_eq?: string;
568 | /**
569 | * as_lq
570 | * Parameter specifies that all search results should contain a link to a
571 | * particular URL. You can also use the
572 | * [link:](https://developers.google.com/custom-search/docs/xml_results#BackLinksqt)
573 | * query term for this type of query.
574 | */
575 | as_lq?: string;
576 | /**
577 | * as_nlo
578 | * Parameter specifies the starting value for a search range. Use as_nlo and as_nhi
579 | * to append an inclusive search range.
580 | */
581 | as_nlo?: string;
582 | /**
583 | * as_nhi
584 | * Parameter specifies the ending value for a search range. Use as_nlo and as_nhi
585 | * to append an inclusive search range.
586 | */
587 | as_nhi?: string;
588 | /**
589 | * as_oq
590 | * Parameter provides additional search terms to check for in a document, where
591 | * each document in the search results must contain at least one of the additional
592 | * search terms. You can also use the [Boolean
593 | * OR](https://developers.google.com/custom-search/docs/xml_results#BooleanOrqt)
594 | * query term for this type of query.
595 | */
596 | as_oq?: string;
597 | /**
598 | * as_q
599 | * Parameter provides search terms to check for in a document. This parameter is
600 | * also commonly used to allow users to specify additional terms to search for
601 | * within a set of search results.
602 | */
603 | as_q?: string;
604 | /**
605 | * as_qdr
606 | * Parameter requests search results from a specified time period (quick date
607 | * range). The following values are supported:
608 | * `d[number]`: requests results from the specified number of past days. Example
609 | * for the past 10 days: `as_qdr=d10`
610 | * `w[number]`: requests results from the specified number of past weeks.
611 | * `m[number]`: requests results from the specified number of past months.
612 | * `y[number]`: requests results from the specified number of past years. Example
613 | * for the past year: `as_qdr=y`
614 | */
615 | as_qdr?: string;
616 | /**
617 | * as_rq
618 | * Parameter specifies that all search results should be pages that are related to
619 | * the specified URL. The parameter value should be a URL. You can also use the
620 | * [related:](https://developers.google.com/custom-search/docs/xml_results#RelatedLinksqt)
621 | * query term for this type of query.
622 | */
623 | as_rq?: string;
624 | /**
625 | * as_sitesearch
626 | * Parameter allows you to specify that all search results should be pages from a
627 | * given site. By setting the as_dt parameter, you can also use it to exclude pages
628 | * from a given site from your search resutls.
629 | */
630 | as_sitesearch?: string;
631 | /**
632 | * Advanced Search Parameters
633 | * (to be searched) parameter defines advanced search parameters that aren't
634 | * possible in the regular query field. (e.g., advanced search for patents, dates,
635 | * news, videos, images, apps, or text contents).
636 | */
637 | tbs?: string;
638 | /**
639 | * Adult Content Filtering
640 | * Parameter defines the level of filtering for adult content. It can be set to
641 | * `active`, or `off` (default).
642 | */
643 | safe?: string;
644 | /**
645 | * Exclude Auto-corrected Results
646 | * Parameter defines the exclusion of results from an auto-corrected query that is
647 | * spelled wrong. It can be set to `1` to exclude these results, or `0` to include
648 | * them (default).
649 | */
650 | nfpr?: string;
651 | /**
652 | * Results Filtering
653 | * Parameter defines if the filters for 'Similar Results' and 'Omitted Results' are
654 | * on or off. It can be set to `1` (default) to enable these filters, or `0` to
655 | * disable these filters.
656 | */
657 | filter?: string;
658 | /**
659 | * Search Type
660 | * (to be matched) parameter defines the type of search you want to do.
661 | * It can be set to:
662 | * `(no tbm parameter)`: regular Google Search,
663 | * `isch`: [Google Images API](https://serpapi.com/images-results),
664 | * `lcl` - [Google Local API](https://serpapi.com/local-results)
665 | * `vid`: [Google Videos API](https://serpapi.com/videos-results),
666 | * `nws`: [Google News API](https://serpapi.com/news-results),
667 | * `shop`: [Google Shopping API](https://serpapi.com/shopping-results),
668 | * or any other Google service.
669 | */
670 | tbm?: string;
671 | /**
672 | * Result Offset
673 | * Parameter defines the result offset. It skips the given number of results. It's
674 | * used for pagination. (e.g., `0` (default) is the first page of results, `10` is
675 | * the 2nd page of results, `20` is the 3rd page of results, etc.).
676 | * Google Local Results only accepts multiples of `20`(e.g. `20` for the second
677 | * page results, `40` for the third page results, etc.) as the start value.
678 | */
679 | start?: number;
680 | /**
681 | * Number of Results
682 | * Parameter defines the maximum number of results to return. (e.g., `10` (default)
683 | * returns 10 results, `40` returns 40 results, and `100` returns 100 results).
684 | */
685 | num?: string;
686 | /**
687 | * Page Number (images)
688 | * Parameter defines the page number for [Google
689 | * Images](https://serpapi.com/images-results). There are 100 images per page. This
690 | * parameter is equivalent to start (offset) = ijn * 100. This parameter works only
691 | * for [Google Images](https://serpapi.com/images-results) (set tbm to `isch`).
692 | */
693 | ijn?: string;
694 | }
695 | ```
696 |
697 | ---
698 |
699 | # Agent 工具箱中的工具集
700 |
701 | 工具集(Toolkit)是旨在一起用于特定任务并具有方便的加载方法的工具的集合
702 |
703 | ```ts
704 | const toolkit = new JsonToolkit(new JsonSpec(data));
705 | const model = new OpenAI({ temperature: 0 });
706 | const executor = createJsonAgent(model, toolkit);
707 | ```
708 |
709 | 值得注意的是,为了更好地串联工具,工具集一般会重新定义 ReAct Agent 的部分提示词
710 |
711 | ```ts {all} {maxHeight:'55%'}
712 | export const JSON_PREFIX = `You are an agent designed to interact with JSON.
713 | Your goal is to return a final answer by interacting with the JSON.
714 | You have access to the following tools which help you learn more about the JSON you are interacting with.
715 | Only use the below tools. Only use the information returned by the below tools to construct your final answer.
716 | Do not make up any information that is not contained in the JSON.
717 | Your input to the tools should be in the form of in json pointer syntax (e.g. /key1/0/key2).
718 | You must escape a slash in a key with a ~1, and escape a tilde with a ~0.
719 | For example, to access the key /foo, you would use /~1foo
720 | You should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling 'json_list_keys'.
721 | If you have not seen a key in one of those responses, you cannot use it.
722 | You should only add one key at a time to the path. You cannot add multiple keys at once.
723 | If you encounter a null or undefined value, go back to the previous key, look at the available keys, and try again.
724 |
725 | If the question does not seem to be related to the JSON, just return "I don't know" as the answer.
726 | Always begin your interaction with the 'json_list_keys' with an empty string as the input to see what keys exist in the JSON.
727 |
728 | Note that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly".
729 | In this case, you should ALWAYS follow up by using the 'json_list_keys' tool to see what keys exist at that path.
730 | Do not simply refer the user to the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.`;
731 |
732 | export const JSON_SUFFIX = `Begin!"
733 |
734 | Question: {input}
735 | Thought: I should look at the keys that exist to see what I can query. I should use the 'json_list_keys' tool with an empty string as the input.
736 | {agent_scratchpad}`;
737 | ```
738 |
739 | ---
740 | layout: iframe
741 | url: https://smith.langchain.com/public/e173ea9a-eb25-45bb-93c9-edf4d3bab6b0/r
742 | ---
743 |
744 | ---
745 | level: 2
746 | ---
747 |
748 | # 🌰 Web API 调用:OpenAPI Agent
749 |
750 | 如下所示,我们会通过 OpenAPI Agent 来调用 OpenAI 的文本补全接口(参见 [完整接口文件](https://github.com/langchain-ai/langchainjs/blob/main/examples/openai_openapi.yaml))
751 |
752 | ```ts
753 | const headers = {
754 | "Content-Type": "application/json",
755 | Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
756 | };
757 | const model = new OpenAI({ temperature: 0 });
758 | const toolkit = new OpenApiToolkit(new JsonSpec(data), model, headers);
759 | const executor = createOpenApiAgent(model, toolkit);
760 | ```
761 | ```ts {all} {maxHeight:'50%'}
762 | export const OPENAPI_PREFIX = `You are an agent designed to answer questions by making web requests to an API given the OpenAPI spec.
763 |
764 | If the question does not seem related to the API, return I don't know. Do not make up an answer.
765 | Only use information provided by the tools to construct your response.
766 |
767 | To find information in the OpenAPI spec, use the 'json_explorer' tool. The input to this tool is a question about the API.
768 |
769 | Take the following steps:
770 | First, find the base URL needed to make the request.
771 |
772 | Second, find the relevant paths needed to answer the question. Take note that, sometimes, you might need to make more than one request to more than one path to answer the question.
773 |
774 | Third, find the required parameters needed to make the request. For GET requests, these are usually URL parameters and for POST requests, these are request body parameters.
775 |
776 | Fourth, make the requests needed to answer the question. Ensure that you are sending the correct parameters to the request by checking which parameters are required. For parameters with a fixed set of values, please use the spec to look at which values are allowed.
777 |
778 | Use the exact parameter names as listed in the spec, do not make up any names or abbreviate the names of parameters.
779 | If you get a not found error, ensure that you are using a path that actually exists in the spec.`;
780 |
781 | export const OPENAPI_SUFFIX = `Begin!"
782 |
783 | Question: {input}
784 | Thought: I should explore the spec to find the base url for the API.
785 | {agent_scratchpad}`;
786 | export const JSON_EXPLORER_DESCRIPTION = `
787 | Can be used to answer questions about the openapi spec for the API. Always use this tool before trying to make a request.
788 | Example inputs to this tool:
789 | 'What are the required query parameters for a GET request to the /bar endpoint?'
790 | 'What are the required parameters in the request body for a POST request to the /foo endpoint?'
791 | Always give this tool a specific question.`;
792 | ```
793 |
794 | ---
795 | layout: iframe
796 | url: https://smith.langchain.com/public/23fde4a9-e601-4d3b-93b7-152ed2dd6e9e/r
797 | ---
798 |
799 | ---
800 | layout: iframe
801 | url: https://smith.langchain.com/public/7466ecfb-6bc7-47de-b1e4-b7d386578c0e/r
802 | ---
803 |
804 | ---
805 | layout: iframe
806 | url: https://smith.langchain.com/public/719fb342-b90b-4ca2-b721-2fa4cf2497b5/r
807 | ---
808 |
809 | ---
810 | layout: iframe
811 | url: https://smith.langchain.com/public/c165d036-f363-4041-a652-8ade7b0893e4/r
812 | ---
813 |
814 | ---
815 | level: 2
816 | ---
817 |
818 | # 🌰 向量存储也可以作用工具(集)
819 |
820 | ```ts {16-} {maxHeight:'90%'}
821 | import { OpenAI } from "langchain/llms/openai";
822 | import { HNSWLib } from "langchain/vectorstores/hnswlib";
823 | import { OpenAIEmbeddings } from "langchain/embeddings/openai";
824 | import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
825 | import { VectorStoreToolkit, createVectorStoreAgent, VectorStoreInfo } from "langchain/agents";
826 |
827 | const model = new OpenAI({ temperature: 0 });
828 | /* Load in the file we want to do question answering over */
829 | const text = fs.readFileSync("state_of_the_union.txt", "utf8");
830 | /* Split the text into chunks using character, not token, size */
831 | const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000 });
832 | const docs = await textSplitter.createDocuments([text]);
833 | /* Create the vectorstore */
834 | const vectorStore = await HNSWLib.fromDocuments(docs, new OpenAIEmbeddings());
835 |
836 | /* Create the agent */
837 | const vectorStoreInfo: VectorStoreInfo = {
838 | name: "state_of_union_address",
839 | description: "the most recent state of the Union address",
840 | vectorStore,
841 | };
842 |
843 | const toolkit = new VectorStoreToolkit(vectorStoreInfo, model);
844 | const agent = createVectorStoreAgent(model, toolkit);
845 |
846 | const input = "What did biden say about Ketanji Brown Jackson is the state of the union address?";
847 | const result = await agent.call({ input });
848 | ```
849 |
850 | ---
851 | layout: iframe
852 | url: https://smith.langchain.com/public/6b91b7c9-4eaa-48ae-a883-0b6a7794d707/r
853 | ---
854 |
855 | ---
856 |
857 | # 必不可缺的 Callback 回调系统
858 |
859 | Callback 回调系统让我们可以连接到 LLM 应用的各个阶段,这对于日志记录、监控、流传输等非常有用
860 |
861 | `callbacks` 参数在整个 API(Model、Chain、Agent、Tool 等)的大多数对象上的两个不同位置可用
862 |
863 | - 可以在构造器位置上接入 Callback(但不能跨对象使用),以 JS/TS 中的 Model 为例:
864 |
865 | ```ts
866 | import { ConsoleCallbackHandler } from "langchain/callbacks";
867 |
868 | const llm = new OpenAI({
869 | // These tags will be attached to all calls made with this LLM.
870 | tags: ["example", "callbacks", "constructor"],
871 | // This handler will be used for all calls made with this LLM.
872 | callbacks: [new ConsoleCallbackHandler()],
873 | });
874 | ```
875 |
876 | - 也可以在模块对象的 `apply()` / `run()` / `call()` 实例方法中发起请求时绑定,但仅对该请求有效:
877 |
878 | ```ts
879 | const llm = new OpenAI({ temperature: 0 });
880 | const response = await llm.call("1 + 1 =", {
881 | // These tags will be attached only to this call to the LLM.
882 | tags: ["example", "callbacks", "request"],
883 | // This handler will be used only for this call.
884 | callbacks: [new ConsoleCallbackHandler()],
885 | });
886 | ```
887 |
888 | ---
889 | level: 2
890 | ---
891 |
892 | # 回顾:链路调试的“文韬武略”
893 |
894 | 我们既可以接入强力的 LangSmith,也可以使用 Console 输出调试信息
895 |
896 | 如何获得足够多且跨模块对象 Console 调试信息 ➡️ 开启 `verbose` 选项:
897 |
898 | ```sh
899 | export LANGCHAIN_VERBOSE=true
900 | ```
901 | ```ts
902 | const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: "xml", verbose: true });
903 | ```
904 |
905 | 或者直接通过环境变量接入 LangSmith:
906 |
907 | ```sh
908 | export LANGCHAIN_TRACING_V2=true
909 | export LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
910 | export LANGCHAIN_API_KEY= # still in closed beta
911 | export LANGCHAIN_PROJECT= # if not specified, defaults to "default"
912 | ```
913 |
914 | ⚠️ 以下方式只能用于对象构造器和对象请求,不能形成完整链路:
915 |
916 | ```ts {4-}
917 | import { Client } from "langsmith";
918 | import { LangChainTracer } from "langchain/callbacks";
919 |
920 | const client = new Client({ apiUrl: "https://api.smith.langchain.com", apiKey: "YOUR_API_KEY" });
921 | const tracer = new LangChainTracer({ projectName: "YOUR_PROJECT_NAME", client });
922 | ```
923 |
924 | ---
925 | level: 2
926 | ---
927 |
928 | # 如何自定义 Callback 处理器
929 |
930 | LangChain 支持通过实现基本回调处理程序接口来创建您自己的处理程序
931 |
932 | 自定义 Callback Handler 可以做一些比输出调试信息到控制台更复杂的事情,例如将事件发送到日志记录服务。作为示例,这里是一个记录到控制台的处理程序的 JS/TS 版本简单实现:
933 |
934 | ```ts {4-} {maxHeight:'70%'}
935 | import { BaseCallbackHandler } from "langchain/callbacks";
936 | import { Serialized } from "langchain/load/serializable";
937 | import { AgentAction, AgentFinish, ChainValues } from "langchain/schema";
938 |
939 | export class MyCallbackHandler extends BaseCallbackHandler {
940 | name = "MyCallbackHandler";
941 |
942 | async handleChainStart(chain: Serialized) {
943 | console.log(`Entering new ${chain.id} chain...`);
944 | }
945 |
946 | async handleChainEnd(_output: ChainValues) {
947 | console.log("Finished chain.");
948 | }
949 |
950 | async handleAgentAction(action: AgentAction) {
951 | console.log(action.log);
952 | }
953 |
954 | async handleToolEnd(output: string) {
955 | console.log(output);
956 | }
957 |
958 | async handleText(text: string) {
959 | console.log(text);
960 | }
961 |
962 | async handleAgentEnd(action: AgentFinish) {
963 | console.log(action.log);
964 | }
965 | }
966 | ```
967 |
968 | ---
969 | src: ../../pages/common/refs.md
970 | ---
971 |
972 | ---
973 | src: ../../pages/common/end.md
974 | ---
--------------------------------------------------------------------------------
/240106-langchain-status/src/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "slidev",
5 | "build": "slidev build --base /240106-langchain-status/ --out ../../dist/240106-langchain-status",
6 | "export": "slidev export --dark --timeout 0 --output ../../pdfs/240106-langchain-status.pdf"
7 | },
8 | "devDependencies": {
9 | "@slidev/cli": "^0.46.1",
10 | "@slidev/theme-seriph": "^0.21.3"
11 | },
12 | "slidev": {
13 | "addons": [
14 | "../../addons/webup"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/240106-langchain-status/src/slides.md:
--------------------------------------------------------------------------------
1 | ---
2 | # See all frontmatter configurations: https://sli.dev/custom/#frontmatter-configures
3 | # theme id or package name, see also: https://sli.dev/themes/use.html
4 | theme: 'seriph'
5 | # titleTemplate for the webpage, `%s` will be replaced by the page's title
6 | titleTemplate: '%s|WebUP'
7 | # some information about the slides, markdown enabled
8 | info: |
9 | AGI 学习笔记,仅供个人学习使用
10 | # favicon, can be a local file path or URL
11 | favicon: https://files.codelife.cc/user-website-icon/20220523/5hyKeZxOknU2owAPvnSWD1388.png?x-oss-process=image/resize,limit_0,m_fill,w_25,h_25/quality,q_92/format,webp
12 | # enabled pdf downloading in SPA build, can also be a custom url
13 | download: 'https://github.com/webup/agi-talks/raw/master/pdfs/240106-langchain-status.pdf'
14 | # syntax highlighter, can be 'prism' or 'shiki'
15 | highlighter: 'shikiji'
16 | # controls whether texts in slides are selectable
17 | selectable: false
18 | # enable slide recording, can be boolean, 'dev' or 'build'
19 | record: 'build'
20 | # define transition between slides
21 | transition: fade
22 | # default frontmatter applies to all slides
23 | defaults:
24 |
25 | # slide configurations
26 | hideInToc: true
27 | layout: cover
28 | class: text-center
29 | background: https://source.unsplash.com/collection/94734566/1920x1080
30 | ---
31 |
32 | # LangChain 生态综述
33 |
34 | LangChain Ecosystem Walkthrough
35 |
36 |