跳到主要内容
Context 为 LLM 驱动的产品和功能提供用户分析。
使用 Context,您可以在 30 分钟内开始了解您的用户并改善他们的体验。 在本指南中,我们将向您展示如何与 Context 集成。

安装和设置

pip install -qU  langchain langchain-openai langchain-community context-python

获取 API 凭证

获取您的 Context API 令牌
  1. 前往您 Context 账户的设置页面 (with.context.ai/settings)。
  2. 生成一个新的 API 令牌。
  3. 将此令牌安全地存储起来。

设置上下文

要使用 ContextCallbackHandler,请从 LangChain 导入处理程序,并使用您的 Context API 令牌对其进行实例化。 在使用处理程序之前,请确保您已安装 context-python 包。
from langchain_community.callbacks.context_callback import ContextCallbackHandler
import os

token = os.environ["CONTEXT_API_TOKEN"]

context_callback = ContextCallbackHandler(token)

用法

聊天模型中的上下文回调

Context 回调处理程序可用于直接记录用户与 AI 助手之间的对话。
import os

from langchain.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI

token = os.environ["CONTEXT_API_TOKEN"]

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 回调处理程序还可用于记录链的输入和输出。请注意,链的中间步骤不会被记录——只记录起始输入和最终输出。 注意:确保将相同的上下文对象传递给聊天模型和链。 错误示例:
chat = ChatOpenAI(temperature=0.9, callbacks=[ContextCallbackHandler(token)])
chain = LLMChain(llm=chat, prompt=chat_prompt_template, callbacks=[ContextCallbackHandler(token)])
正确
handler = ContextCallbackHandler(token)
chat = ChatOpenAI(temperature=0.9, callbacks=[callback])
chain = LLMChain(llm=chat, prompt=chat_prompt_template, callbacks=[callback])
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"]

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"))

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.