Created
December 31, 2025 12:48
-
-
Save larkintuckerllc/8cebc550327cf52bbf8970737e1069b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from dataclasses import dataclass | |
| from langchain.agents import create_agent | |
| from langchain.agents.middleware import dynamic_prompt, ModelRequest | |
| from langchain.messages import HumanMessage | |
| @dataclass | |
| class LanguageContext: | |
| user_language: str = "English" | |
| @dynamic_prompt | |
| def user_language_prompt(request: ModelRequest) -> str: | |
| """Generate system prompt based on user role.""" | |
| user_language = request.runtime.context.user_language | |
| base_prompt = "You are a helpful assistant." | |
| if user_language != "English": | |
| return f"{base_prompt} only respond in {user_language}." | |
| elif user_language == "English": | |
| return base_prompt | |
| agent = create_agent( | |
| model="gpt-5-nano", | |
| context_schema=LanguageContext, | |
| middleware=[user_language_prompt] | |
| ) | |
| response = agent.invoke( | |
| {"message": [HumanMessage(content="Hello, how are you?")]}, | |
| context=LanguageContext() | |
| ) | |
| print(response["messages"][-1].content) | |
| response = agent.invoke( | |
| {"message": [HumanMessage(content="Hello, how are you?")]}, | |
| context=LanguageContext(user_language="Spanish") | |
| ) | |
| print(response["messages"][-1].content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment