使用langchain进行LLM封装调用
【代码】使用langchain进行LLM封装调用。
·
import os
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
os.environ['OPENAI_BASE_URL']='https://dashscope.aliyuncs.com/compatible-mode/v1'
os.environ['OPENAI_API_KEY']=os.getenv("DASHSCOPE_API_KEY")
model=init_chat_model('qwen-plus',model_provider='openai')
# 方法1:单条消息,调用llm
print(model.invoke('hello').content)
# 方法2:多组消息数据,调用llm
messages = [
{"role": "system", "content": "回复不超过10个字"},
{"role": "user", "content": "hello"}
]
print(model.invoke(messages).content)
# 方法3:使用message对象
messages=[
SystemMessage("回复不超过10个字"),
HumanMessage("hello")
]
print(model.invoke(messages).content)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)