我的目标是将
language
占位符插入到调用方法中,但目前响应始终是英语。我遵循本教程 -> https://python.langchain.com/v0.2/docs/tutorials/chatbot/
有什么理由吗?
# Securely input the OpenAI API key
api_key = os.getenv("OPENAI_API_KEY")
# Initialize the ChatOpenAI model with the API key
model = ChatOpenAI(model="gpt-3.5-turbo", api_key=api_key, verbose=True)
def invoke_model(session_id: str, message: str):
# Define the prompt with ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant. Answer all questions to the best of your ability in {language}."),
MessagesPlaceholder(variable_name="messages"),
]
)
# Create the chain using the prompt and the model
chain = prompt | model
# Use with_message_history to handle messages
with_message_history = RunnableWithMessageHistory(chain, get_session_history, input_messages_key="messages")
human_message = HumanMessage(content=message)
session_history = get_session_history(session_id)
session_history.add_message(human_message) # Add the human message to the history
config = {"configurable": {"session_id": session_id}}
response = with_message_history.invoke({"messages": [human_message], "language": "Spanish"}, config=config)
assistant_message = AIMessage(content=response.content)
session_history.add_message(assistant_message) # Add the assistant's response to the history
return response.content
它不起作用,因为您使用的是
('system', '<your message with placeholder>')
,它相当于硬编码消息(SystemMessage
类),即它不被视为模板,因此不会为其生成输入变量。为了修复它,您需要将其替换为
prompt = ChatPromptTemplate.from_messages(
[
SystemMessageTemplate.from_template("You are a helpful assistant. Answer all questions to the best of your ability in {language}."),
MessagesPlaceholder(variable_name="messages"),
]
)