from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
2 Simple LLM App
= ChatOpenAI(model="gpt-4")
model model
ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x10e1eb070>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x10e1eaaa0>, model_name='gpt-4', openai_api_key=SecretStr('**********'), openai_proxy='')
2.1 Simple Interaction
= [
messages ="Translate the following from English into Italian"),
SystemMessage(content="hi!"),
HumanMessage(content
]
= model.invoke(messages) resp1
resp1.content
'ciao!'
2.2 OutputParsers
from langchain_core.output_parsers import StrOutputParser
= StrOutputParser() parser
parser.invoke(resp1)
'ciao!'
2.3 Create Chain
= model | parser chain
= chain.invoke(messages) resp2
resp2
'Ciao!'
2.4 Prompt Template
from langchain_core.prompts import ChatPromptTemplate
= "Translate the following into {language}:"
system_template
= ChatPromptTemplate.from_messages(
prompt_template "system", system_template),
[("user", "{text}")]
( )
Inspect prompt
= prompt_template.invoke({"language": "italian", "text": "hi"})
prompt3 prompt3.to_messages()
[SystemMessage(content='Translate the following into italian:'),
HumanMessage(content='hi')]
Create Chain
= prompt_template | model | parser
chain
= chain.invoke({"language": "italian", "text": "hi"}) resp3
resp3
'ciao'