import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage
20 Build ChatBot
From: Build ChatBot Tutorial
= ChatOpenAI(model="gpt-3.5-turbo") model
= model.invoke([HumanMessage(content="Hi! I'm Bob")])
resp1 resp1.content
'Hello Bob! How can I assist you today?'
model.invoke(
[="Hi! I'm Bob"),
HumanMessage(content="Hello Bob! How can I assist you today?"),
AIMessage(content="What's my name?"),
HumanMessage(content
] )
AIMessage(content='Your name is Bob. How can I assist you today, Bob?', response_metadata={'token_usage': {'completion_tokens': 14, 'prompt_tokens': 35, 'total_tokens': 49}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-c115acb1-9703-4b61-8dcc-291b330f0de0-0')
20.1 Message History
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
= {}
store
def get_session_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in store:
= ChatMessageHistory()
store[session_id] return store[session_id]
= RunnableWithMessageHistory(model, get_session_history) with_message_history
= {"configurable": {"session_id": "abc2"}} config
= with_message_history.invoke(
response ="Hi! I'm Bob")],
[HumanMessage(content=config,
config
)
response.content
'Hello Bob! How can I assist you today?'
= with_message_history.invoke(
response ="What's my name?")],
[HumanMessage(content=config,
config
)
response.content
'Your name is Bob, as you mentioned earlier. How can I help you, Bob?'
20.2 Prompt Template
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
= ChatPromptTemplate.from_messages(
prompt
[
("system",
"You are a helpful assistant. Answer all questions to the best of your ability.",
),="messages"),
MessagesPlaceholder(variable_name
]
)
= prompt | model chain
= chain.invoke({"messages": [HumanMessage(content="hi! I'm bob")]})
response response.content
'Hello Bob! How can I assist you today?'
= ChatPromptTemplate.from_messages(
prompt
[
("system",
"You are a helpful assistant. Answer all questions to the best of your ability in {language}.",
),="messages"),
MessagesPlaceholder(variable_name
]
)
= prompt | model chain
= chain.invoke(
response "messages": [HumanMessage(content="hi! I'm bob")], "language": "Spanish"}
{
)
response.content
'¡Hola, Bob! ¿En qué puedo ayudarte hoy?'