0
0
LangChainframework~7 mins

Custom agent logic in LangChain

Choose your learning style9 modes available
Introduction

Custom agent logic lets you control how an AI agent thinks and acts step-by-step. It helps you make the agent smarter and fit your special needs.

When you want the agent to follow a specific plan or rules.
When you need the agent to handle special tasks or data formats.
When you want to change how the agent decides what to do next.
When you want to add custom checks or stop conditions during the agent's work.
When you want to combine multiple tools or APIs in a unique way.
Syntax
LangChain
from langchain.agents import Agent

class CustomAgent(Agent):
    def plan(self, intermediate_steps, **kwargs):
        # Your custom planning logic here
        return plan

    def run(self, input):
        # Your custom run logic here
        return output

You create a new class that inherits from Agent.

Override methods like plan or run to change behavior.

Examples
This example makes the agent always choose the 'search' tool with a fixed query.
LangChain
class CustomAgent(Agent):
    def plan(self, intermediate_steps, **kwargs):
        # Always pick the first tool
        return {'tool': 'search', 'input': 'example query'}
This example changes the input before running the normal agent logic.
LangChain
class CustomAgent(Agent):
    def run(self, input):
        # Add a prefix to input before running
        modified_input = 'Check: ' + input
        return super().run(modified_input)
Sample Program

This program creates a custom agent that always uses a 'calculator' tool. The tool just reverses the input string as a fake calculation. When run with '12345', it returns '54321'.

LangChain
class CustomAgent:
    def plan(self, intermediate_steps, **kwargs):
        # Simple plan: always use tool 'calculator' with input
        return {'tool': 'calculator', 'input': kwargs.get('input', '')}

    def run(self, input):
        plan = self.plan([], input=input)
        tool = plan['tool']
        tool_input = plan['input']
        # Simulate tool execution
        if tool == 'calculator':
            # Just return the input reversed as a fake calculation
            return tool_input[::-1]
        return 'No tool executed'

agent = CustomAgent()
result = agent.run('12345')
print(result)
OutputSuccess
Important Notes

Custom agents let you control the agent's thinking steps.

Override only the methods you need to change.

Test your custom logic carefully to avoid infinite loops or errors.

Summary

Custom agent logic means writing your own rules for how the agent plans and acts.

This helps make agents fit special tasks or workflows.

It involves subclassing and overriding key methods like plan and run.