当前位置: 首页 > 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;并详细解释每种方法…...

7.4.分块查找

一.分块查找的算法思想&#xff1a; 1.实例&#xff1a; 以上述图片的顺序表为例&#xff0c; 该顺序表的数据元素从整体来看是乱序的&#xff0c;但如果把这些数据元素分成一块一块的小区间&#xff0c; 第一个区间[0,1]索引上的数据元素都是小于等于10的&#xff0c; 第二…...

CVPR 2025 MIMO: 支持视觉指代和像素grounding 的医学视觉语言模型

CVPR 2025 | MIMO&#xff1a;支持视觉指代和像素对齐的医学视觉语言模型 论文信息 标题&#xff1a;MIMO: A medical vision language model with visual referring multimodal input and pixel grounding multimodal output作者&#xff1a;Yanyuan Chen, Dexuan Xu, Yu Hu…...

FastAPI 教程:从入门到实践

FastAPI 是一个现代、快速&#xff08;高性能&#xff09;的 Web 框架&#xff0c;用于构建 API&#xff0c;支持 Python 3.6。它基于标准 Python 类型提示&#xff0c;易于学习且功能强大。以下是一个完整的 FastAPI 入门教程&#xff0c;涵盖从环境搭建到创建并运行一个简单的…...

【项目实战】通过多模态+LangGraph实现PPT生成助手

PPT自动生成系统 基于LangGraph的PPT自动生成系统&#xff0c;可以将Markdown文档自动转换为PPT演示文稿。 功能特点 Markdown解析&#xff1a;自动解析Markdown文档结构PPT模板分析&#xff1a;分析PPT模板的布局和风格智能布局决策&#xff1a;匹配内容与合适的PPT布局自动…...

论文浅尝 | 基于判别指令微调生成式大语言模型的知识图谱补全方法(ISWC2024)

笔记整理&#xff1a;刘治强&#xff0c;浙江大学硕士生&#xff0c;研究方向为知识图谱表示学习&#xff0c;大语言模型 论文链接&#xff1a;http://arxiv.org/abs/2407.16127 发表会议&#xff1a;ISWC 2024 1. 动机 传统的知识图谱补全&#xff08;KGC&#xff09;模型通过…...

RNN避坑指南:从数学推导到LSTM/GRU工业级部署实战流程

本文较长&#xff0c;建议点赞收藏&#xff0c;以免遗失。更多AI大模型应用开发学习视频及资料&#xff0c;尽在聚客AI学院。 本文全面剖析RNN核心原理&#xff0c;深入讲解梯度消失/爆炸问题&#xff0c;并通过LSTM/GRU结构实现解决方案&#xff0c;提供时间序列预测和文本生成…...

今日学习:Spring线程池|并发修改异常|链路丢失|登录续期|VIP过期策略|数值类缓存

文章目录 优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器并发修改异常并发修改异常简介实现机制设计原因及意义 使用线程池造成的链路丢失问题线程池导致的链路丢失问题发生原因 常见解决方法更好的解决方法设计精妙之处 登录续期登录续期常见实现方式特…...

高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数

高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数 在软件开发中,单例模式(Singleton Pattern)是一种常见的设计模式,确保一个类仅有一个实例,并提供一个全局访问点。在多线程环境下,实现单例模式时需要注意线程安全问题,以防止多个线程同时创建实例,导致…...

NXP S32K146 T-Box 携手 SD NAND(贴片式TF卡):驱动汽车智能革新的黄金组合

在汽车智能化的汹涌浪潮中&#xff0c;车辆不再仅仅是传统的交通工具&#xff0c;而是逐步演变为高度智能的移动终端。这一转变的核心支撑&#xff0c;来自于车内关键技术的深度融合与协同创新。车载远程信息处理盒&#xff08;T-Box&#xff09;方案&#xff1a;NXP S32K146 与…...

【Go语言基础【12】】指针:声明、取地址、解引用

文章目录 零、概述&#xff1a;指针 vs. 引用&#xff08;类比其他语言&#xff09;一、指针基础概念二、指针声明与初始化三、指针操作符1. &&#xff1a;取地址&#xff08;拿到内存地址&#xff09;2. *&#xff1a;解引用&#xff08;拿到值&#xff09; 四、空指针&am…...