LangChain Routing 学习笔记

2024-04-29 23:28

本文主要是介绍LangChain Routing 学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

LangChain Routing 学习笔记

  • 0. 引言
  • 1. 使用提示词
  • 2. 使用 RunnableLambda

0. 引言

在使用大语言模型开发应用时,其中一个场景就是根据不同的输入,调用(或者说路由到)不同的逻辑。这就好比我们以前开发时经常使用的if ... else ... 一样。

实现路由有多种方法,下面介绍2种简单的方法。

1. 使用提示词

这种方法简单来说就是使用提示词,让大语言模型根据输入给出特定的输出。

示例代码,

from dotenv import load_dotenv, find_dotenv_ = load_dotenv(find_dotenv())
from langchain_openai import ChatOpenAI
# from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplatechain = (PromptTemplate.from_template("""Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.Do not respond with more than one word.<question>
{question}
</question>Classification:""")# | ChatAnthropic(model_name="claude-3-haiku-20240307")| ChatOpenAI(model="gpt-4", temperature=0)| StrOutputParser()
)chain.invoke({"question": "how do I call Anthropic?"})

输出结果,

Anthropic

2. 使用 RunnableLambda

示例代码,

from dotenv import load_dotenv, find_dotenv_ = load_dotenv(find_dotenv())
from langchain_openai import ChatOpenAI
# from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplatechain = (PromptTemplate.from_template("""Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.Do not respond with more than one word.<question>
{question}
</question>Classification:""")# | ChatAnthropic(model_name="claude-3-haiku-20240307")| ChatOpenAI(model="gpt-4", temperature=0)| StrOutputParser()
)
from langchain_core.prompts import PromptTemplate
# from langchain_anthropic import ChatAnthropiclangchain_chain = PromptTemplate.from_template("""You are an expert in langchain. \
Always answer questions starting with "As Harrison Chase told me". \
Respond to the following question:Question: {question}
Answer:"""
# ) | ChatAnthropic(model_name="claude-3-haiku-20240307")
) | ChatOpenAI(model="gpt-4", temperature=0)
anthropic_chain = PromptTemplate.from_template("""You are an expert in anthropic. \
Always answer questions starting with "As Dario Amodei told me". \
Respond to the following question:Question: {question}
Answer:"""
# ) | ChatAnthropic(model_name="claude-3-haiku-20240307")
) | ChatOpenAI(model="gpt-4", temperature=0)
general_chain = PromptTemplate.from_template("""Respond to the following question:Question: {question}
Answer:"""
# ) | ChatAnthropic(model_name="claude-3-haiku-20240307")
) | ChatOpenAI(model="gpt-4", temperature=0)
def route(info):if "anthropic" in info["topic"].lower():return anthropic_chainelif "langchain" in info["topic"].lower():return langchain_chainelse:return general_chain
from langchain_core.runnables import RunnableLambdafull_chain = {"topic": chain, "question": lambda x: x["question"]} | RunnableLambda(route
)
full_chain.invoke({"question": "how do I use Anthropic?"})

输出,

AIMessage(content="As Dario Amodei, the co-founder of Anthropic, explained, using Anthropic's language models typically involves accessing their APIs to generate text or analyze inputs. While exact steps depend on the specific application and whether you're working with a public or private API, generally, you would:\n\n1. **Sign up for access**: Visit Anthropic's website and sign up for an account if they offer public access or reach out to them for partnership if their services are not publicly available.\n\n2. **Obtain an API key**: Once your account is set up, you'll receive an API key that authorizes your application to interact with their models.\n\n3. **Understand the API documentation**: Familiarize yourself with Anthropic's API documentation which outlines how to structure requests, what parameters are available, and how to interpret responses.\n\n4. **Make API calls**: Using a programming language of your choice (like Python), write code that constructs API requests. This usually involves specifying the prompt you want the model to respond to, the maximum length of the response, and other optional settings.\n\n5. **Process the response**: The API will return a response which is typically in JSON format. Your code should parse this response to extract the generated text or any other data provided.\n\n6. **Integrate into your application**: Depending on your use case, integrate the generated text or insights into your software, whether it's for chatbots, content generation, language translation, or analysis.\n\n7. **Respect usage guidelines and ethical considerations**: Always adhere to Anthropic's terms of service, be mindful of the ethical implications of using AI, and ensure you're handling user data responsibly.\n\nRemember that the specifics might change as Anthropic evolves its services, so always refer to their latest documentation for the most accurate instructions.", response_metadata={'token_usage': {'completion_tokens': 364, 'prompt_tokens': 47, 'total_tokens': 411}, 'model_name': 'gpt-4', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-636a9a22-389b-478f-8938-51309df9a3d1-0')

示例代码,

full_chain.invoke({"question": "how do I use LangChain?"})

输出,

AIMessage(content="As Harrison Chase explained, using LangChain involves several steps:\n\n1. **Understand Your Use Case**: First, determine what problem you want to solve or what task you aim to accomplish with LangChain. It's a framework designed to create powerful language models and AI applications.\n\n2. **Choose Components**: LangChain is modular, so you'll select the appropriate components for your use case. This might include LLMs (Large Language Models), vector databases, prompt engineering tools, and more.\n\n3. **Set Up Environment**: You need a development environment that supports the technologies used by LangChain, typically Python with libraries like Langchain, Hugging Face Transformers, or other necessary dependencies.\n\n4. **Integrate APIs**: If you're using external models or services, set up API keys and integrate them into your project.\n\n5. **Design Workflows**: Define how data will flow through the system, from input to processing by language models to output. This might involve creating chains of different components.\n\n6. **Write Code**: Implement your design using LangChain's APIs and modules. Start with simple scripts or move on to more complex applications as you become comfortable.\n\n7. **Test and Iterate**: Use sample inputs to test your setup, analyze the outputs, and refine your implementation based on the results.\n\n8. **Deploy and Monitor**: Once satisfied with the performance, deploy your application to a server or cloud platform. Continuously monitor its performance and make adjustments as needed.\n\nRemember, LangChain is about combining different AI components effectively, so it's crucial to have a clear understanding of each part you're using and how they interact. Always refer to the official documentation for the most up-to-date guidance and examples.", response_metadata={'token_usage': {'completion_tokens': 344, 'prompt_tokens': 44, 'total_tokens': 388}, 'model_name': 'gpt-4', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-abe4f2fd-9d7c-4f08-8e48-d32ff173d6e3-0')

示例代码,

full_chain.invoke({"question": "whats 2 + 2"})

输出,

AIMessage(content='4', response_metadata={'token_usage': {'completion_tokens': 2, 'prompt_tokens': 23, 'total_tokens': 25}, 'model_name': 'gpt-4', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-3c6d5a95-cac9-4dc8-a600-63180f655196-0')

完结!

这篇关于LangChain Routing 学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/947425

相关文章

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06