Langchain

langchain是一个用于开发由语言模型驱动的应用程序的框架,致力于简化AI模型应用的开发。简单来说,langchain就是一个(帮助开发者轻松完成AI模型应用开发的)框架,现在支持python和js两个版本,它集成多种大语言模型及第三方API。

1、安装langchain

#安装langchain环境
pip install langchain==0.3.3 openai -i https://mirrors.aliyun.com/pypi/simple 
#灵积模型服务
pip install dashscope -i https://mirrors.aliyun.com/pypi/simple   
#安装第三方集成,就是各种大语言模型
pip install langchain-community==0.3.2 -i https://mirrors.aliyun.com/pypi/simple 
#加载环境的工具  
pip install python-dotenv 

2.前期准备工作

第一个准备工作:拿到阿里云灵积模型服务的apikey,目前已经转为大模型服务百炼平台

传送门:阿里云开发者社区-云计算社区-阿里云 (aliyun.com)

2.1.登录或者注册

2.2 开通灵积模型服务

搜索灵积模型服务,开通服务,点击立即开通

 2.3 创建API-Key

进入产品控制台,创建api-key

3.配置环境

  如何获取API Key_大模型服务平台百炼(Model Studio)-阿里云帮助中心

  项目根目录创建 .env文件,配置 API-Key

#api-key
DASHSCOPE_API_KEY=sk-bcf39cf72ce24f41fb28XXXX

4.编码实现

4.1导包

#导入相关包
import os
from langchain_community.llms import Tongyi
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())
DASHSCOPE_API_KEY=os.environ["DASHSCOPE_API_KEY"]

4.2定义角色

  temperature=1是调节文本多样性的,让回答更加丰富,为0时就会更加准确,大于0回答的就会带有llm的思维回答(可能会胡编乱造) res['text']就是回答内容了,回答的一个字典包含了question和text

llm=Tongyi(temperature=1)
template='''
        你的名字是夏,当人问问题的时候,你都会在开头加上'我性格开朗,为人热情!',然后再回答{question}
    '''
prompt=PromptTemplate(
        template=template,
        input_variables=["question"]#这个question就是用户输入的内容,这行代码不可缺少
)
chain = LLMChain(#将llm与prompt联系起来
        llm=llm,
        prompt=prompt
        )
question='你是谁'

res=chain.invoke(question)#运行
    
print(res['text'])#打印结果

Logo

立足具身智能前沿赛道,致力于搭建全球化、开源化、全栈式技术交流与实践共创平台。

更多推荐