Bird
Raised Fist0
LangChainframework~20 mins

LangChain vs direct API calls - Practice Questions

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
LangChain Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the main difference in output when using LangChain's chain vs direct API call?

Consider a LangChain chain that calls an LLM with a prompt template versus a direct API call to the same LLM with the same prompt. What difference in output behavior would you expect?

LangChain
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
prompt = PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"])
chain = LLMChain(llm=llm, prompt=prompt)

result_chain = chain.run(text="Hello")

# Direct API call
result_direct = llm("Translate 'Hello' to French.")
ALangChain output is a Python dict, direct API call returns a string.
BLangChain output includes extra metadata, while direct API call returns only the raw text.
CLangChain output is always JSON, direct API call returns plain text.
DBoth outputs are identical strings because LangChain just wraps the API call with formatting.
Attempts:
2 left
💡 Hint

Think about what LangChain adds on top of the API call.

state_output
intermediate
2:00remaining
What happens to state when using LangChain chains vs direct API calls?

When you run multiple prompts in sequence, how does LangChain manage state compared to direct API calls?

LangChain
from langchain import ConversationChain
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
conv = ConversationChain(llm=llm)

response1 = conv.predict(input="Hello!")
response2 = conv.predict(input="How are you?")

# Direct calls
resp1 = llm("Hello!")
resp2 = llm("How are you?")
ADirect API calls keep conversation history; LangChain chains do not.
BBoth LangChain and direct API calls keep conversation history automatically.
CLangChain ConversationChain keeps conversation history automatically; direct API calls do not.
DNeither LangChain nor direct API calls keep conversation history automatically.
Attempts:
2 left
💡 Hint

Think about how conversation context is preserved.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly creates a LangChain chain that calls OpenAI with a prompt template?

Identify the correct code to create a LangChain LLMChain with a prompt template that asks for a summary.

A
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(template="Summarize: {text}", input_variables=["text"])
llm = OpenAI()
chain = LLMChain(llm=llm, prompt=prompt)
B
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(template="Summarize: {text}", input_variables=["text"])
llm = OpenAI()
chain = LLMChain(prompt, llm)
C
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(template="Summarize: {text}", input_variables=["text"])
llm = OpenAI()
chain = LLMChain(llm=llm)
D
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(template="Summarize: {text}", input_variables=["text"])
llm = OpenAI()
chain = LLMChain(prompt=prompt)
Attempts:
2 left
💡 Hint

Check the order and presence of required arguments in LLMChain constructor.

🔧 Debug
advanced
2:00remaining
Why does this LangChain code raise a KeyError when running a chain?

Given this code, why does running chain.run() raise a KeyError?

LangChain
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(template="Answer: {question}", input_variables=["question"])
llm = OpenAI()
chain = LLMChain(llm=llm, prompt=prompt)

result = chain.run()
ABecause OpenAI LLM is not initialized with an API key.
BBecause <code>run()</code> requires the 'question' argument but none was provided.
CBecause <code>LLMChain</code> does not support <code>run()</code> method.
DBecause the prompt template is invalid and missing a colon.
Attempts:
2 left
💡 Hint

Check the input variables required by the prompt template.

🧠 Conceptual
expert
2:00remaining
Which advantage does LangChain provide over direct API calls for building complex applications?

Choose the best advantage LangChain offers compared to making direct API calls to language models.

ALangChain automatically manages prompt templates, chains, memory, and integrations, simplifying complex workflows.
BLangChain reduces API latency by caching all responses locally.
CLangChain replaces the need for API keys by using open-source models only.
DLangChain guarantees 100% accurate outputs from language models.
Attempts:
2 left
💡 Hint

Think about what LangChain adds beyond just calling the API.

Practice

(1/5)
1. What is the main advantage of using LangChain over direct API calls?
easy
A. LangChain simplifies building complex language model applications by wrapping API calls.
B. LangChain requires more manual setup than direct API calls.
C. LangChain offers less control over API parameters than direct calls.
D. LangChain is only useful for simple scripts without complex logic.

Solution

  1. Step 1: Understand LangChain's purpose

    LangChain is designed to wrap API calls to make using language models easier and more powerful.
  2. Step 2: Compare with direct API calls

    Direct API calls require manual setup and offer full control but are more complex to manage.
  3. Final Answer:

    LangChain simplifies building complex language model applications by wrapping API calls. -> Option A
  4. Quick Check:

    LangChain simplifies API use = C [OK]
Hint: LangChain wraps APIs to simplify complex tasks [OK]
Common Mistakes:
  • Thinking LangChain requires more manual setup
  • Believing LangChain offers less control
  • Assuming LangChain is only for simple scripts
2. Which of the following is the correct way to create a LangChain LLM instance in Python?
easy
A. llm = OpenAI(model_name="gpt-4")
B. llm = OpenAI('gpt-4')
C. llm = OpenAI.create('gpt-4')
D. llm = OpenAI.new(model='gpt-4')

Solution

  1. Step 1: Recall LangChain LLM instantiation syntax

    LangChain uses keyword arguments to specify model parameters, e.g., model_name="gpt-4".
  2. Step 2: Check each option's syntax

    llm = OpenAI(model_name="gpt-4") uses correct keyword argument syntax; others use invalid or nonexistent methods.
  3. Final Answer:

    llm = OpenAI(model_name="gpt-4") -> Option A
  4. Quick Check:

    Correct LangChain LLM syntax = D [OK]
Hint: Use keyword args like model_name="gpt-4" to create LLM [OK]
Common Mistakes:
  • Using positional arguments instead of keywords
  • Calling nonexistent methods like create() or new()
  • Missing quotes around model name
3. Given this code using LangChain:
from langchain.llms import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo")
response = llm("Hello, how are you?")
print(response)
What will this code do compared to making a direct API call?
medium
A. It sends no request because LangChain requires explicit API calls.
B. It will raise a syntax error because llm is not callable.
C. It automatically handles API details and returns the model's text response.
D. It returns raw JSON instead of text.

Solution

  1. Step 1: Understand LangChain LLM call behavior

    Calling llm(...) sends the prompt to the API and returns the text response automatically.
  2. Step 2: Compare with direct API calls

    Direct calls require manual request setup and parsing; LangChain simplifies this.
  3. Final Answer:

    It automatically handles API details and returns the model's text response. -> Option C
  4. Quick Check:

    LangChain call returns text response = A [OK]
Hint: LangChain llm() returns text response directly [OK]
Common Mistakes:
  • Thinking llm object is not callable
  • Assuming LangChain needs manual API calls
  • Expecting raw JSON instead of text
4. You wrote this direct API call code but get an error:
import openai
response = openai.ChatCompletion.create(
  model="gpt-4",
  messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)
What is the likely cause of the error?
medium
A. The messages parameter should be a string, not a list.
B. Missing openai.api_key setup before calling the API.
C. The model name "gpt-4" is invalid in direct API calls.
D. The print statement syntax is incorrect.

Solution

  1. Step 1: Check API call requirements

    Direct API calls require setting openai.api_key before usage to authenticate requests.
  2. Step 2: Validate other parameters and syntax

    Messages as list is correct, model name is valid, and print syntax is correct.
  3. Final Answer:

    Missing openai.api_key setup before calling the API. -> Option B
  4. Quick Check:

    API key missing causes error = B [OK]
Hint: Always set openai.api_key before direct API calls [OK]
Common Mistakes:
  • Passing messages as string instead of list
  • Using invalid model names
  • Incorrect print syntax
5. You want to build a chatbot app that uses multiple language models and chains prompts together. Which approach is best and why?
hard
A. Use LangChain only if you want to avoid API keys.
B. Use direct API calls because they are simpler for chaining multiple models.
C. Use direct API calls because LangChain cannot handle multiple models.
D. Use LangChain because it provides tools to manage chains and multiple models easily.

Solution

  1. Step 1: Identify requirements for chaining and multiple models

    Building a chatbot with multiple models and prompt chains needs orchestration tools.
  2. Step 2: Compare LangChain and direct API calls for this use case

    LangChain offers built-in support for chains and managing multiple models, simplifying app building.
  3. Step 3: Evaluate incorrect options

    Direct API calls require manual chaining logic; LangChain does not avoid API keys.
  4. Final Answer:

    Use LangChain because it provides tools to manage chains and multiple models easily. -> Option D
  5. Quick Check:

    LangChain best for chaining models = A [OK]
Hint: LangChain simplifies chaining and multi-model apps [OK]
Common Mistakes:
  • Thinking direct calls are simpler for chaining
  • Believing LangChain can't handle multiple models
  • Assuming LangChain removes need for API keys