In [1]:
from dotenv import load_dotenv
load_dotenv()
Out[1]:
True
In [2]:
import os, asyncio, json
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.messages import HumanMessage, AIMessage
from langchain.tools import tool, ToolRuntime
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.checkpoint.memory import InMemorySaver
from typing import Dict, Any
from tavily import TavilyClient
from pprint import pprint
from dataclasses import dataclass
DEEPSEEK_MODEL = "deepseek-chat"
DEEPSEEK_BASE_URL = "https://api.deepseek.com"
def deepseek_model(model: str = DEEPSEEK_MODEL, max_tokens=1000, **kwargs):
return init_chat_model(
model=model,
# DeepSeek uses LangChain's OpenAI-compatible transport.
model_provider="openai",
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url=DEEPSEEK_BASE_URL,
max_tokens=max_tokens,
**kwargs,
)
In [3]:
@dataclass
class ColourContext:
favourite_colour: str = "blue"
least_favourite_colour: str = "yellow"
In [4]:
agent = create_agent(
model=deepseek_model(),
context_schema=ColourContext # the agent can receive a context_schema arg with the format of ColourContext
)
In [5]:
#不过要注意:仅仅传入 context_schema 和 context=ColourContext(),不一定代表模型会自动知道怎么使用这个 context。
#通常还需要在 system prompt 或 tools/middleware 里明确告诉 agent 如何读取 context。
response = agent.invoke(
{"messages": [HumanMessage(content="What is my favourite colour?")]},
context=ColourContext(),
system_prompt="Use the runtime context to answer questions about the user's preferences." # to tell model to use the contxt
)
In [7]:
print(response['messages'][-1].content)
I don't actually know what your favourite colour is, since you haven't told me yet. But if you'd like to share it, I'd be happy to remember it for this conversation!
Accessing Context¶
In [14]:
@tool
def get_favourite_colour(runtime: ToolRuntime) -> str:
"""Get the favourite colour of the user"""
return runtime.context.favourite_colour
@tool
def get_least_favourite_colour(runtime: ToolRuntime) -> str:
"""Get the least favourite colour of the user"""
return runtime.context.least_favourite_colour
In [15]:
agent = create_agent(
model=deepseek_model(),
tools=[get_favourite_colour, get_least_favourite_colour],
context_schema=ColourContext
)
In [16]:
response = agent.invoke(
{"messages": [HumanMessage(content="What is my favourite colour?")]},
context=ColourContext()
)
/path/to/.venv/lib/python3.13/site-packages/pydantic/main.py:464: UserWarning: Pydantic serializer warnings: PydanticSerializationUnexpectedValue(Expected `none` - serialized value may not be as expected [field_name='context', input_value=ColourContext(favourite_c...vourite_colour='yellow'), input_type=ColourContext]) return self.__pydantic_serializer__.to_python(
In [17]:
print(response['messages'][-1].content)
Your favourite colour is **blue**!
In [20]:
response = agent.invoke(
{"messages": [HumanMessage(content="What is my favourite colour?")]},
context=ColourContext(favourite_colour="green")
)
/path/to/.venv/lib/python3.13/site-packages/pydantic/main.py:464: UserWarning: Pydantic serializer warnings: PydanticSerializationUnexpectedValue(Expected `none` - serialized value may not be as expected [field_name='context', input_value=ColourContext(favourite_c...vourite_colour='yellow'), input_type=ColourContext]) return self.__pydantic_serializer__.to_python(
In [21]:
print(response['messages'][-1].content)
Your favourite colour is **green**!
In [ ]: