Bird
Raised Fist0
LangChainframework~10 mins

Custom agent logic in LangChain - Step-by-Step Execution

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
Concept Flow - Custom agent logic
Start: Receive user input
Agent parses input
Check if input matches custom logic
Run custom logic
Generate custom response
Return response
The agent receives input, decides if custom logic applies, runs it or defaults, then returns the response.
Execution Sample
LangChain
from langchain.agents import Agent

class CustomAgent(Agent):
    def plan(self, input):
        if "hello" in input.lower():
            return "Say hi back"
        return super().plan(input)
This code defines a custom agent that replies specially when input contains 'hello', otherwise uses default logic.
Execution Table
StepInputCondition CheckedBranch TakenActionOutput
1"Hello, agent!""hello" in input.lower()?YesReturn custom response 'Say hi back'"Say hi back"
2"What is the time?""hello" in input.lower()?NoCall default agent plan method"Default response"
3N/AN/AN/AEnd of processingN/A
💡 Input processed by either custom or default logic, then response returned.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
inputNone"Hello, agent!""What is the time?"N/A
conditionFalseTrueFalseN/A
responseNone"Say hi back""Default response"N/A
Key Moments - 2 Insights
Why does the agent return a custom response only when 'hello' is in the input?
Because the condition '"hello" in input.lower()' is checked at each input (see execution_table step 1 and 2). If true, custom logic runs; otherwise, default logic runs.
What happens if the input does not match the custom condition?
The agent calls the default plan method (see execution_table step 2), so it behaves like a normal agent without custom logic.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when input is 'Hello, agent!'?
A"Say hi back"
B"Default response"
C"Hello, agent!"
DNo output
💡 Hint
Check step 1 output column in the execution_table.
At which step does the agent decide to use default logic?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Branch Taken' column for step 2 in the execution_table.
If the condition checked was changed to check for 'bye' instead of 'hello', what would happen at step 1?
AAgent crashes
BCustom logic runs for input 'Hello, agent!'
CDefault logic runs for input 'Hello, agent!'
DNo response
💡 Hint
Refer to the condition in variable_tracker and execution_table step 1.
Concept Snapshot
Custom agent logic lets you add your own rules to decide how the agent responds.
Check input, run your code if condition matches, else use default.
Override methods like plan() to insert custom behavior.
Always return a response string.
This helps tailor agent answers to special cases.
Full Transcript
Custom agent logic in Langchain means you write your own rules inside the agent to handle inputs differently. The agent first gets the input, then checks if it matches your custom condition. If yes, it runs your special code and returns a custom response. If not, it falls back to the normal agent behavior. This way, you can make the agent say or do exactly what you want for certain inputs. The example code shows overriding the plan method to check if the input contains 'hello'. If it does, it returns a special message. Otherwise, it calls the original plan method. The execution table traces this decision for two inputs: one with 'hello' and one without. Variables like input, condition, and response change as the agent processes each input. This helps beginners see how the agent chooses which logic to run and what output it produces. The quizzes test understanding of when custom logic runs and what outputs appear. The snapshot summarizes the key idea: check input, run custom code if needed, else default. This approach makes agents flexible and easy to customize.

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