Bird
Raised Fist0
LangChainframework~20 mins

Custom agent logic in LangChain - Practice Problems & Coding Challenges

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 Custom Agent Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this custom LangChain agent logic?
Consider this LangChain custom agent code snippet. What will be printed when the agent runs the input 'Hello'?
LangChain
from langchain.agents import AgentExecutor, Tool
from langchain.schema import AgentAction, AgentFinish

class CustomAgent:
    def plan(self, intermediate_steps, **kwargs):
        if len(intermediate_steps):
            return self.finish(intermediate_steps, **kwargs)
        return AgentAction(tool="echo", tool_input=kwargs.get("input", ""), log="Echoing input")

    def finish(self, intermediate_steps, **kwargs):
        print("Done")
        return AgentFinish(return_values={"output": "Done"}, log="Finished")

class EchoTool:
    def run(self, input_text):
        print(f"Echo: {input_text}")
        return input_text

agent = CustomAgent()
tool = Tool(name="echo", func=EchoTool().run, description="Echoes input")
executor = AgentExecutor(agent=agent, tools=[tool])
executor.run("Hello")
AEcho: Hello
B
Echo: Hello
Done
C
Hello
Done
DDone
Attempts:
2 left
💡 Hint
Look at what the EchoTool prints and what the agent returns as output.
state_output
intermediate
2:00remaining
What is the final output value of this LangChain custom agent?
Given this custom agent logic, what is the final output returned by the agent executor?
LangChain
from langchain.agents import AgentExecutor, Tool
from langchain.schema import AgentAction, AgentFinish

class IncrementAgent:
    def __init__(self):
        self.counter = 0

    def plan(self, intermediate_steps, **kwargs):
        self.counter += 1
        if self.counter < 3:
            return AgentAction(tool="increment", tool_input=self.counter, log=f"Increment to {self.counter}")
        else:
            return AgentFinish(return_values={"output": self.counter}, log="Done")

class IncrementTool:
    def run(self, input_num):
        return input_num + 1

agent = IncrementAgent()
tool = Tool(name="increment", func=IncrementTool().run, description="Increments number")
executor = AgentExecutor(agent=agent, tools=[tool])
result = executor.run(0)
A0
B4
C2
D3
Attempts:
2 left
💡 Hint
Count how many times the agent plans and what it returns at finish.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this LangChain custom agent code?
Identify which code snippet will cause a syntax error when defining a custom agent in LangChain.
A
class MyAgent
    def plan(self, intermediate_steps, **kwargs):
        return AgentAction(tool="search", tool_input=kwargs.get("query"), log="Searching")
B
class MyAgent:
    def plan(self, intermediate_steps, **kwargs):
        return AgentAction(tool="search", tool_input=kwargs.get("query"), log="Searching")
    def finish(self, intermediate_steps, **kwargs):
        return AgentFinish(return_values={"output": "done"}, log="Finished")
C
)"dehsiniF"=gol ,}"enod" :"tuptuo"{=seulav_nruter(hsiniFtnegA nruter        
:)sgrawk** ,spets_etaidemretni ,fles(hsinif fed    
)"gnihcraeS"=gol ,)"yreuq"(teg.sgrawk=tupni_loot ,"hcraes"=loot(noitcAtnegA nruter        
:)sgrawk** ,spets_etaidemretni ,fles(nalp fed    
:tnegAyM ssalc
D
class MyAgent:
    def plan(self, intermediate_steps, **kwargs):
        return AgentAction(tool="search", tool_input=kwargs.get("query"), log="Searching")
Attempts:
2 left
💡 Hint
Check the class definition syntax carefully.
🔧 Debug
advanced
2:00remaining
Which option will cause a runtime error when running this LangChain custom agent?
Given this custom agent and tool setup, which option will cause a runtime error when the agent executor runs?
LangChain
from langchain.agents import AgentExecutor, Tool
from langchain.schema import AgentAction, AgentFinish

class FaultyAgent:
    def plan(self, intermediate_steps, **kwargs):
        return AgentAction(tool="missing_tool", tool_input="test", log="Trying missing tool")

agent = FaultyAgent()
tool = Tool(name="existing_tool", func=lambda x: x, description="A working tool")
executor = AgentExecutor(agent=agent, tools=[tool])
executor.run("input")
ARuntimeError: Tool 'missing_tool' not found
BTypeError: 'NoneType' object is not callable
CNo error, returns 'test'
DSyntaxError: invalid syntax
Attempts:
2 left
💡 Hint
Check if the tool name used by the agent matches any tool in the executor.
🧠 Conceptual
expert
2:00remaining
How does custom agent logic affect LangChain's decision-making process?
Which statement best describes the role of custom agent logic in LangChain's agent execution?
ACustom agent logic replaces the entire LangChain framework and runs independently.
BCustom agent logic only formats the final output without influencing tool selection or planning.
CCustom agent logic defines how the agent chooses tools and processes intermediate steps to decide next actions.
DCustom agent logic is responsible for loading external data sources automatically without user input.
Attempts:
2 left
💡 Hint
Think about what planning and finishing methods control in an agent.

Practice

(1/5)
1. What is the main purpose of creating custom agent logic in Langchain?
easy
A. To define specific rules for how the agent plans and acts
B. To change the user interface of the agent
C. To improve the speed of the Langchain library
D. To add new data sources automatically

Solution

  1. Step 1: Understand the role of custom agent logic

    Custom agent logic is about controlling how the agent decides what to do next.
  2. Step 2: Identify the main purpose

    It is used to write your own rules for planning and acting, not for UI or speed improvements.
  3. Final Answer:

    To define specific rules for how the agent plans and acts -> Option A
  4. Quick Check:

    Custom agent logic = planning and acting rules [OK]
Hint: Custom logic controls agent decisions, not UI or speed [OK]
Common Mistakes:
  • Thinking it changes the user interface
  • Assuming it speeds up the library
  • Believing it adds data sources automatically
2. Which method should you override to customize how an agent decides its next action in Langchain?
easy
A. run
B. plan
C. initialize
D. execute

Solution

  1. Step 1: Identify key methods for custom logic

    Langchain agents use methods like plan and run for behavior.
  2. Step 2: Determine which controls decision making

    The plan method decides the next action, so overriding it customizes decisions.
  3. Final Answer:

    plan -> Option B
  4. Quick Check:

    Decision method = plan [OK]
Hint: Override plan() to change agent's next action [OK]
Common Mistakes:
  • Overriding run() instead of plan() for decisions
  • Using initialize() which is not for planning
  • Confusing execute() with plan()
3. Given this custom agent code snippet, what will be printed?
class MyAgent:
    def plan(self, input_text):
        if 'hello' in input_text.lower():
            return 'Greet'
        return 'Ignore'

agent = MyAgent()
print(agent.plan('Hello there!'))
medium
A. Greet
B. Ignore
C. hello
D. Error

Solution

  1. Step 1: Analyze the plan method logic

    The method checks if 'hello' is in the input text (case-insensitive). If yes, returns 'Greet'.
  2. Step 2: Apply input to the method

    Input is 'Hello there!', which contains 'hello' ignoring case, so it returns 'Greet'.
  3. Final Answer:

    Greet -> Option A
  4. Quick Check:

    Input contains 'hello' -> returns 'Greet' [OK]
Hint: Check string contains 'hello' ignoring case [OK]
Common Mistakes:
  • Ignoring case sensitivity in string check
  • Expecting the method to print input text
  • Assuming method returns 'Ignore'
4. What is wrong with this custom agent code?
class CustomAgent:
    def plan(self, input_text):
        if input_text.contains('test'):
            return 'Found'
        return 'Not Found'
medium
A. Missing return statement in plan method
B. plan method should not take input_text parameter
C. Indentation error in class definition
D. Using .contains() method which does not exist in Python strings

Solution

  1. Step 1: Check string method usage

    Python strings do not have a .contains() method; use 'in' keyword instead.
  2. Step 2: Identify correct string membership check

    Correct way is: 'test' in input_text, so .contains() causes an error.
  3. Final Answer:

    Using .contains() method which does not exist in Python strings -> Option D
  4. Quick Check:

    Python strings use 'in', not .contains() [OK]
Hint: Use 'in' keyword for substring check in Python [OK]
Common Mistakes:
  • Using .contains() instead of 'in'
  • Thinking plan method can't take parameters
  • Assuming missing return statement
5. You want to create a custom Langchain agent that first plans actions based on input, then logs each action before running it. Which approach correctly combines planning and running with logging?
hard
A. Override only run() to plan, log, and execute actions
B. Override plan() to log actions and run() to decide actions
C. Override plan() to decide actions and override run() to log and execute actions
D. Use default plan() and run(), add logging outside the agent

Solution

  1. Step 1: Understand responsibilities of plan() and run()

    plan() decides what to do next; run() executes actions.
  2. Step 2: Combine logging with correct methods

    Override plan() for custom decisions; override run() to add logging before execution.
  3. Final Answer:

    Override plan() to decide actions and override run() to log and execute actions -> Option C
  4. Quick Check:

    plan() decides, run() logs and executes [OK]
Hint: Plan decides; run executes and logs actions [OK]
Common Mistakes:
  • Putting planning logic inside run() only
  • Logging inside plan() without running actions
  • Not overriding methods and logging externally