Bird
0
0

You want to send a conversation with multiple messages to the OpenAI chat model using Langchain. Which code correctly formats the messages for the invoke method?

hard📝 Application Q9 of 15
LangChain - LLM and Chat Model Integration
You want to send a conversation with multiple messages to the OpenAI chat model using Langchain. Which code correctly formats the messages for the invoke method?
Amessages = {'system': 'You are helpful.', 'user': 'Hello!'} response = chat.invoke(messages)
Bmessages = [{'role': 'system', 'content': 'You are helpful.'}, {'role': 'user', 'content': 'Hello!'}] response = chat.invoke(messages)
Cmessages = ['You are helpful.', 'Hello!'] response = chat.invoke(messages)
Dmessages = [{'content': 'You are helpful.'}, {'content': 'Hello!'}] response = chat.invoke(messages)
Step-by-Step Solution
Solution:
  1. Step 1: Understand message format

    Each message must be a dictionary with keys 'role' and 'content'. Roles can be 'system', 'user', or 'assistant'.
  2. Step 2: Check options for correct structure

    messages = [{'role': 'system', 'content': 'You are helpful.'}, {'role': 'user', 'content': 'Hello!'}] response = chat.invoke(messages) correctly uses a list of dicts with roles and content. Others use wrong structures or omit roles.
  3. Final Answer:

    messages = [{'role': 'system', 'content': 'You are helpful.'}, {'role': 'user', 'content': 'Hello!'}] response = chat.invoke(messages) -> Option B
  4. Quick Check:

    Messages must be list of dicts with role and content [OK]
Quick Trick: Messages need role and content keys in a list [OK]
Common Mistakes:
  • Using dict instead of list for messages
  • Omitting role key in messages
  • Passing list of strings instead of dicts

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LangChain Quizzes