当前位置: 首页 > news >正文

J-LangChain - 智能链构建

介绍

j-langchain是一个Java版的LangChain开发框架,旨在简化和加速各类大模型应用在Java平台的落地开发。它提供了一组实用的工具和类,使得开发人员能够更轻松地构建类似于LangChain的Java应用程序。

依赖

Maven

<dependency><groupId>io.github.flower-trees</groupId><artifactId>j-langchain</artifactId><version>1.0.1-preview</version>
</dependency>

Gradle

implementation 'io.github.flower-trees:j-langchain:1.0.1-preview'

💡 Notes:

  • 系统基于salt-function-flow流程编排框架开发,具体语法可 参考。

智能链构建

顺序调用

LangChain实现

from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParsermodel = OllamaLLM(model="qwen2.5:0.5b")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")chain = prompt | model | StrOutputParser()result = chain.invoke({"topic": "bears"})
print(result)

J-LangChain实现

@Component
public class ChainBuildDemo {@AutowiredChainActor chainActor;public void SimpleDemo() {BaseRunnable<StringPromptValue, ?> prompt = PromptTemplate.fromTemplate("tell me a joke about ${topic}");ChatOpenAI chatOpenAI = ChatOpenAI.builder().model("gpt-4").build();FlowInstance chain = chainActor.builder().next(prompt).next(oll).next(new StrOutputParser()).build();ChatGeneration result = chainActor.invoke(chain, Map.of("topic", "bears"));System.out.println(result);}
}

分支路由

J-LangChain实现

public void SwitchDemo() {BaseRunnable<StringPromptValue, ?> prompt = PromptTemplate.fromTemplate("tell me a joke about ${topic}");ChatOllama chatOllama = ChatOllama.builder().model("llama3:8b").build();ChatOpenAI chatOpenAI = ChatOpenAI.builder().model("gpt-4").build();FlowInstance chain = chainActor.builder().next(prompt).next(Info.c("vendor == 'ollama'", chatOllama),Info.c("vendor == 'chatgpt'", chatOpenAI),Info.c(input -> "sorry, I don't know how to do that")).next(new StrOutputParser()).build();Generation result = chainActor.invoke(chain, Map.of("topic", "bears", "vendor", "ollama"));System.out.println(result);
}

组合嵌套

LangChain实现

analysis_prompt = ChatPromptTemplate.from_template("is this a funny joke? {joke}")
composed_chain = {"joke": chain} | analysis_prompt | model | StrOutputParser()result = composed_chain.invoke({"topic": "bears"})
print(result)

J-LangChain实现

public void ComposeDemo() {ChatOllama llm = ChatOllama.builder().model("llama3:8b").build();StrOutputParser parser = new StrOutputParser();BaseRunnable<StringPromptValue, ?> prompt = PromptTemplate.fromTemplate("tell me a joke about ${topic}");FlowInstance chain = chainActor.builder().next(prompt).next(llm).next(parser).build();BaseRunnable<StringPromptValue, ?> analysisPrompt = PromptTemplate.fromTemplate("is this a funny joke? ${joke}");FlowInstance analysisChain = chainActor.builder().next(chain).next(input -> Map.of("joke", ((Generation)input).getText())).next(analysisPrompt).next(llm).next(parser).build();ChatGeneration result = chainActor.invoke(analysisChain, Map.of("topic", "bears"));System.out.println(result);}

并行执行

LangChain实现

from langchain_core.runnables import RunnableParalleljoke_chain = ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
poem_chain = ChatPromptTemplate.from_template("write a 2-line poem about {topic}") | modelparallel_chain = RunnableParallel(joke=joke_chain, poem=poem_chain)result = parallel_chain.invoke({"topic": "bear"})
print(result)

J-LangChain实现

public void ParallelDemo() {ChatOllama llm = ChatOllama.builder().model("llama3:8b").build();BaseRunnable<StringPromptValue, ?> joke = PromptTemplate.fromTemplate("tell me a joke about ${topic}");BaseRunnable<StringPromptValue, ?> poem = PromptTemplate.fromTemplate("write a 2-line poem about ${topic}");FlowInstance jokeChain = chainActor.builder().next(joke).next(llm).build();FlowInstance poemChain = chainActor.builder().next(poem).next(llm).build();FlowInstance chain = chainActor.builder().concurrent((IResult<Map<String, String>>) (iContextBus, isTimeout) -> {AIMessage jokeResult = iContextBus.getResult(jokeChain.getFlowId());AIMessage poemResult = iContextBus.getResult(poemChain.getFlowId());return Map.of("joke", jokeResult.getContent(), "poem", poemResult.getContent());}, jokeChain, poemChain).build();Map<String, String> result = chainActor.invoke(chain, Map.of("topic", "bears"));System.out.println(JsonUtil.toJson(result));}

动态路由

LangChain实现
通过 RunnableLambda 实现动态路由:

from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableLambdachain = (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:""")| OllamaLLM(model="qwen2.5:0.5b")| StrOutputParser()
)langchain_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:"""
) | OllamaLLM(model="qwen2.5:0.5b")
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:"""
) | OllamaLLM(model="qwen2.5:0.5b")
general_chain = PromptTemplate.from_template("""Respond to the following question:Question: {question}
Answer:"""
) | OllamaLLM(model="qwen2.5:0.5b")def route(info):if "anthropic" in info["topic"].lower():return anthropic_chainelif "langchain" in info["topic"].lower():return langchain_chainelse:return general_chainfull_chain = {"topic": chain, "question": lambda x: x["question"]} | RunnableLambda(route)result = full_chain.invoke({"question": "how do I use LangChain?"})
print(result)def route(info):if "anthropic" in info["topic"].lower():return anthropic_chainelif "langchain" in info["topic"].lower():return langchain_chainelse:return general_chainfrom langchain_core.runnables import RunnableLambdafull_chain = {"topic": chain, "question": lambda x: x["question"]} | RunnableLambda(route)result = full_chain.invoke({"question": "how do I use LangChain?"})
print(result)

J-LangChain实现

public void RouteDemo() {ChatOllama llm = ChatOllama.builder().model("llama3:8b").build();BaseRunnable<StringPromptValue, Object> prompt = PromptTemplate.fromTemplate("""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:""");FlowInstance chain = chainActor.builder().next(prompt).next(llm).next(new StrOutputParser()).build();FlowInstance langchainChain = chainActor.builder().next(PromptTemplate.fromTemplate("""You are an expert in langchain. \Always answer questions starting with "As Harrison Chase told me". \Respond to the following question:Question: ${question}Answer:""")).next(ChatOllama.builder().model("llama3:8b").build()).build();FlowInstance anthropicChain = chainActor.builder().next(PromptTemplate.fromTemplate("""You are an expert in anthropic. \Always answer questions starting with "As Dario Amodei told me". \Respond to the following question:Question: ${question}Answer:""")).next(ChatOllama.builder().model("llama3:8b").build()).build();FlowInstance generalChain = chainActor.builder().next(PromptTemplate.fromTemplate("""Respond to the following question:Question: ${question}Answer:""")).next(ChatOllama.builder().model("llama3:8b").build()).build();FlowInstance fullChain = chainActor.builder().next(chain).next(input -> Map.of("topic", input, "question", ((Map<?, ?>)ContextBus.get().getFlowParam()).get("question"))).next(Info.c("topic == 'anthropic'", anthropicChain),Info.c("topic == 'langchain'", langchainChain),Info.c(generalChain)).build();AIMessage result = chainActor.invoke(fullChain, Map.of("question", "how do I use Anthropic?"));System.out.println(result.getContent());}

动态构建

LangChain实现

from langchain_core.runnables import chain, RunnablePassthroughllm = OllamaLLM(model="qwen2.5:0.5b")contextualize_instructions = """Convert the latest user question into a standalone question given the chat history. Don't answer the question, return the question and nothing else (no descriptive text)."""
contextualize_prompt = ChatPromptTemplate.from_messages([("system", contextualize_instructions),("placeholder", "{chat_history}"),("human", "{question}"),]
)
contextualize_question = contextualize_prompt | llm | StrOutputParser()@chain
def contextualize_if_needed(input_: dict):if input_.get("chat_history"):return contextualize_questionelse:return RunnablePassthrough() | itemgetter("question")@chain
def fake_retriever(input_: dict):return "egypt's population in 2024 is about 111 million"qa_instructions = ("""Answer the user question given the following context:\n\n{context}."""
)
qa_prompt = ChatPromptTemplate.from_messages([("system", qa_instructions), ("human", "{question}")]
)full_chain = (RunnablePassthrough.assign(question=contextualize_if_needed).assign(context=fake_retriever)| qa_prompt| llm| StrOutputParser()
)result = full_chain.invoke({"question": "what about egypt","chat_history": [("human", "what's the population of indonesia"),("ai", "about 276 million"),],
})
print(result)

J-LangChain实现

public void DynamicDemo() {ChatOllama llm = ChatOllama.builder().model("llama3:8b").build();String contextualizeInstructions = """Convert the latest user question into a standalone question given the chat history. Don't answer the question, return the question and nothing else (no descriptive text).""";BaseRunnable<ChatPromptValue, Object> contextualizePrompt = ChatPromptTemplate.fromMessages(List.of(Pair.of("system", contextualizeInstructions),Pair.of("placeholder", "${chatHistory}"),Pair.of("human", "${question}")));FlowInstance contextualizeQuestion = chainActor.builder().next(contextualizePrompt).next(llm).next(new StrOutputParser()).build();FlowInstance contextualizeIfNeeded = chainActor.builder().next(Info.c("chatHistory != null", contextualizeQuestion),Info.c(input -> Map.of("question", ((Map<String, String>)input).get("question")))).build();String qaInstructions ="""Answer the user question given the following context:\n\n${context}.""";BaseRunnable<ChatPromptValue, Object>  qaPrompt = ChatPromptTemplate.fromMessages(List.of(Pair.of("system", qaInstructions),Pair.of("human", "${question}")));FlowInstance fullChain = chainActor.builder().all((iContextBus, isTimeout) -> Map.of("question", iContextBus.getResult(contextualizeIfNeeded.getFlowId()).toString(),"context", iContextBus.getResult("fakeRetriever")),Info.c(contextualizeIfNeeded),Info.c(input -> "egypt's population in 2024 is about 111 million").cAlias("fakeRetriever")).next(qaPrompt).next(input -> {System.out.println(JsonUtil.toJson(input)); return input;}).next(llm).next(new StrOutputParser()).build();ChatGeneration result = chainActor.invoke(fullChain,Map.of("question", "what about egypt","chatHistory",List.of(Pair.of("human", "what's the population of indonesia"),Pair.of("ai", "about 276 million"))));System.out.println(result);}

相关文章:

J-LangChain - 智能链构建

介绍 j-langchain是一个Java版的LangChain开发框架&#xff0c;旨在简化和加速各类大模型应用在Java平台的落地开发。它提供了一组实用的工具和类&#xff0c;使得开发人员能够更轻松地构建类似于LangChain的Java应用程序。 依赖 Maven <dependency><groupId>i…...

开源低代码平台-Microi吾码 打印引擎使用

引言 在开发中&#xff0c;会遇到很多记录的表单数据需要下载打印下来使用到线下各种应用场景中。在传统的方法中可能是需要先导出数据&#xff0c;然后将数据填入word表格中在打印下来。 但Microi吾码提供了一项新功能&#xff0c;便是打印引擎。打印引擎即可在线设计…...

【MySQL】索引 面试题

文章目录 适合创建索引的情况创建索引的注意事项MySQL中不适合创建索引的情况索引失效的常见情况 索引定义与作用 索引是帮助MySQL高效获取数据的有序数据结构&#xff0c;通过维护特定查找算法的数据结构&#xff08;如B树&#xff09;&#xff0c;以某种方式引用数据&#xf…...

【高阶数据结构】AVL树

AVL树 1.AVL的概念2.AVL树的实现1.AVL树的结构2.AVL树的插入1.更新平衡因子2.旋转1.右单旋2.左单旋3.左右双旋4.右左双旋 3.AVL树的查找4.AVL树的平衡检测5.AVL树的性能分析6.AVL树的删除 3.总代码1.AVLTree.h2.Test.cpp 1.AVL的概念 AVL树是最先发明的自平衡⼆叉查找树&#…...

【Spring】基于XML的Spring容器配置——<bean>标签与属性解析

Spring框架是一个非常流行的应用程序框架&#xff0c;它通过控制反转&#xff08;IoC&#xff09;和依赖注入&#xff08;DI&#xff09;来简化企业级应用的开发。Spring容器是其核心部分&#xff0c;负责管理对象的创建、配置和生命周期。在Spring中&#xff0c;XML配置是一种…...

docker mysql5.7安装

一.更改 /etc/docker/daemon.json sudo mkdir -p /etc/dockersudo tee /etc/docker/daemon.json <<-EOF {"registry-mirrors": ["https://do.nark.eu.org","https://dc.j8.work","https://docker.m.daocloud.io","https:/…...

HDR视频技术之十一:HEVCH.265 的 HDR 编码方案

前文我们对 HEVC 的 HDR 编码优化技术做了介绍&#xff0c;侧重编码性能的提升。 本章主要阐述 HEVC 中 HDR/WCG 相关的整体编码方案&#xff0c; 包括不同应用场景下的 HEVC 扩展编码技术。 1 背景 HDR 信号一般意味着使用更多比特&#xff0c;一般的 HDR 信号倾向于使用 10…...

最新的强大的文生视频模型Pyramid Flow 论文阅读及复现

《PYRAMIDAL FLOW MATCHING FOR EFFICIENT VIDEO GENERATIVE MODELING》 论文地址&#xff1a;2410.05954https://arxiv.org/pdf/2410.05954 项目地址&#xff1a; jy0205/Pyramid-Flow&#xff1a; 用于高效视频生成建模的金字塔流匹配代码https://github.com/jy0205/Pyram…...

Effective C++ 条款 11:在 `operator=` 中处理“自我赋值”

文章目录 条款 11&#xff1a;在 operator 中处理“自我赋值”核心问题示例&#xff1a;使用地址比较示例&#xff1a;copy-and-swap 技术设计建议总结 条款 11&#xff1a;在 operator 中处理“自我赋值” 核心问题 自我赋值风险 如果赋值操作符没有处理自我赋值&#xff08;…...

19、鸿蒙学习——配置HDC命令 环境变量

一、下载Command Line Tools 可参考上篇《鸿蒙学习——配置OHPM、hvigor环境变量》 二、配置hdc环境变量 hdc命令行工具用于HarmonyOS应用/元服务调试所需的工具&#xff0c;该工具存放在命令行工具自带的sdk下的toolchains目录中。为方便使用hdc命令行工具&#xff0c;请将…...

初始 ShellJS:一个 Node.js 命令行工具集合

一. 前言 Node.js 丰富的生态能赋予我们更强的能力&#xff0c;对于前端工程师来说&#xff0c;使用 Node.js 来编写复杂的 npm script 具有明显的 2 个优势&#xff1a;首先&#xff0c;编写简单的工具脚本对前端工程师来说额外的学习成本很低甚至可以忽略不计&#xff0c;其…...

网络工程师常用软件之PING测试工具

老王说网络&#xff1a;网络资源共享汇总 https://docs.qq.com/sheet/DWXZiSGxiaVhxYU1F ☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝ 今天介绍一款好用的PING测试工具&#xff0c;ATKKPING。 ATKKPING的主要功能包括测试…...

深入探索仓颉编程语言:函数与结构类型的终极指南

引言 仓颉编程语言是一种现代化、语法精炼的编程语言&#xff0c;其设计目标是提供高度的灵活性与高性能的执行效率。函数与结构类型是仓颉语言的两大基础模块&#xff0c;也是开发者需要掌握的核心。本文将详细讲解仓颉语言中函数和结构类型的特性&#xff0c;辅以代码实例和…...

Java 对象的内存分配机制详解

在 Java 中&#xff0c;对象的内存分配是一个复杂但非常重要的过程。理解对象在堆中的分配方式&#xff0c;尤其是新生代和老年代的区别&#xff0c;对于优化 Java 应用程序的性能至关重要。本文将详细探讨 Java 对象在堆中的分配机制&#xff0c;包括新生代、老年代、Survivor…...

v8引擎垃圾回收

V8引擎垃圾回收机制 v8引擎负责JavaScript的执行。V8引擎具有内置的垃圾回收机制&#xff0c;用于自动管理内存分配和释放 堆与栈 栈空间 栈空间是小而连续的内存空间&#xff0c;主要用于存储局部变量和函数调用的相关信息&#xff0c;同时栈结构是“先进后出”的策略 栈…...

H5st5.0.0协议分析

签名核心&#xff1a;设备注册 5 8 9段签名校验 其中第八段主要收集了一些指纹信息 需要 对应一致 注册核心加密&#xff1a; fp localTk fp - 16位字符串 localTk - 92位字符串 tls指纹检测 py、js纯算皆可调用 注意&#xff1a;仅供学习交流&#xff0c;与作者无关&am…...

明达助力构建智能变电站新体系

背景概述 随着智能电网技术的飞速进步与电力需求的持续增长&#xff0c;变电站作为电力传输网络的核心节点&#xff0c;其运维效率及安全性能对电网的整体稳定运行起着决定性作用。传统的人工巡检和维护手段已难以匹配现代电网对高效性、实时性及智能化管理的迫切需求。因此&a…...

Flink优化----FlinkSQL 调优

目录 FlinkSQL 调优 1 设置空闲状态保留时间 2 开启 MiniBatch 3 开启 LocalGlobal 3.1 原理概述 3.2 提交案例&#xff1a;统计每天每个 mid 出现次数 3.3 提交案例&#xff1a;开启 miniBatch 和 LocalGlobal 4 开启 Split Distinct 4.1 原理概述 4.2 提交案例&…...

机器学习(二)-简单线性回归

文章目录 1. 简单线性回归理论2. python通过简单线性回归预测房价2.1 预测数据2.2导入标准库2.3 导入数据2.4 划分数据集2.5 导入线性回归模块2.6 对测试集进行预测2.7 计算均方误差 J2.8 计算参数 w0、w12.9 可视化训练集拟合结果2.10 可视化测试集拟合结果2.11 保存模型2.12 …...

01.01、判定字符是否唯一

01.01、[简单] 判定字符是否唯一 1、题目描述 实现一个算法&#xff0c;确定一个字符串 s 的所有字符是否全都不同。 在这一题中&#xff0c;我们的任务是判断一个字符串 s 中的所有字符是否全都不同。我们将讨论两种不同的方法来解决这个问题&#xff0c;并详细解释每种方法…...

解决VirtualBox/VMware虚拟机在win10下运行ensp时AR启动卡死问题

未经授权&#xff0c;禁止转载&#xff01;1.环境准备与确认首先 &#xff0c;确认你的虚拟机是否是windows10&#xff0c;例如我的虚拟机操作系统如下&#xff1a;2.然后&#xff0c;确认你的环境是否正确&#xff0c;重点查看VirtualBox是否是"VirtualBox-5.2.44-139111…...

NI USB-6210 DAQ采集卡开箱照

1、包装非常简单&#xff0c;有点对不起它6000~7000元的价格&#xff1a;2、 内部也没有什么特别的&#xff1a;3、一张用户须知&#xff0c;一本使用说明&#xff1a;4、一张光盘&#xff0c;感觉有点Low&#xff0c;现在电脑很少有光驱了&#xff1a;5、这条USB线据说要200大…...

如何提升桌面互动体验?BongoCat的个性化配置方案

如何提升桌面互动体验&#xff1f;BongoCat的个性化配置方案 【免费下载链接】BongoCat &#x1f431; 跨平台互动桌宠 BongoCat&#xff0c;为桌面增添乐趣&#xff01; 项目地址: https://gitcode.com/gh_mirrors/bong/BongoCat 在数字化工作与娱乐日益融合的今天&…...

像素时装锻造坊应用场景:NFT项目像素角色皮肤的批量生成方案

像素时装锻造坊应用场景&#xff1a;NFT项目像素角色皮肤的批量生成方案 1. 项目背景与核心价值 像素时装锻造坊&#xff08;Pixel Fashion Atelier&#xff09;是一款专为NFT项目设计的像素角色皮肤批量生成工具。它基于Stable Diffusion与Anything-v5技术栈&#xff0c;将传…...

拯救者工具箱终极指南:3大场景释放笔记本隐藏性能

拯救者工具箱终极指南&#xff1a;3大场景释放笔记本隐藏性能 【免费下载链接】LenovoLegionToolkit Lightweight Lenovo Vantage and Hotkeys replacement for Lenovo Legion laptops. 项目地址: https://gitcode.com/gh_mirrors/le/LenovoLegionToolkit Lenovo Legion…...

Titanium SDK快速入门:10分钟创建你的第一个跨平台App

Titanium SDK快速入门&#xff1a;10分钟创建你的第一个跨平台App 【免费下载链接】titanium-sdk &#x1f680; Native iOS and Android Apps with JavaScript 项目地址: https://gitcode.com/gh_mirrors/ti/titanium-sdk Titanium SDK是一个强大的开源框架&#xff0c…...

3步解锁网盘下载新体验:告别限速困扰的终极方案

3步解锁网盘下载新体验&#xff1a;告别限速困扰的终极方案 【免费下载链接】Online-disk-direct-link-download-assistant 一个基于 JavaScript 的网盘文件下载地址获取工具。基于【网盘直链下载助手】修改 &#xff0c;支持 百度网盘 / 阿里云盘 / 中国移动云盘 / 天翼云盘 /…...

5分钟快速上手:Switch注入完整指南与TegraRcmGUI使用教程

5分钟快速上手&#xff1a;Switch注入完整指南与TegraRcmGUI使用教程 【免费下载链接】TegraRcmGUI C GUI for TegraRcmSmash (Fuse Gele exploit for Nintendo Switch) 项目地址: https://gitcode.com/gh_mirrors/te/TegraRcmGUI 如果你正在寻找一款简单易用的Switch注…...

Cosmos-Reason1-7B实际作品:实验室化学反应装置稳定性与泄漏风险评估

Cosmos-Reason1-7B实际作品&#xff1a;实验室化学反应装置稳定性与泄漏风险评估 1. 项目概述 Cosmos-Reason1-7B是NVIDIA开发的多模态物理推理视觉语言模型&#xff0c;专注于物理场景理解和安全风险评估。该模型能够分析图像和视频内容&#xff0c;结合物理常识进行链式思维…...

YOLOv10实战:用官方镜像5分钟搭建智能监控原型系统

YOLOv10实战&#xff1a;用官方镜像5分钟搭建智能监控原型系统 想快速验证一个智能监控的想法&#xff0c;却卡在繁琐的环境配置和模型部署上&#xff1f;从安装CUDA、配置Python环境&#xff0c;到调试各种依赖库&#xff0c;可能半天时间就过去了&#xff0c;真正的业务逻辑…...