2  Simple LLM App

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
model = ChatOpenAI(model="gpt-4")
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 = [
    SystemMessage(content="Translate the following from English into Italian"),
    HumanMessage(content="hi!"),
]

resp1 = model.invoke(messages)
resp1.content
'ciao!'

2.2 OutputParsers

from langchain_core.output_parsers import StrOutputParser

parser = StrOutputParser()
parser.invoke(resp1)
'ciao!'

2.3 Create Chain

chain = model | parser
resp2 = chain.invoke(messages)
resp2
'Ciao!'

2.4 Prompt Template

from langchain_core.prompts import ChatPromptTemplate
system_template = "Translate the following into {language}:"

prompt_template = ChatPromptTemplate.from_messages(
    [("system", system_template), 
     ("user", "{text}")]
)

Inspect prompt

prompt3 = prompt_template.invoke({"language": "italian", "text": "hi"})
prompt3.to_messages()
[SystemMessage(content='Translate the following into italian:'),
 HumanMessage(content='hi')]

Create Chain

chain = prompt_template | model | parser

resp3 = chain.invoke({"language": "italian", "text": "hi"})
resp3
'ciao'