# Import necessary modules from LangChain
from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI
from langchain.tools import BaseTool
# Define a custom tool that echoes back the input text.
class EchoTool(BaseTool):
"""A simple tool that echoes the provided text."""
name = "echo_tool"
description = "A tool that echoes back any text provided to it."
def _run(self, text: str):
return f"Echo: {text}"
async def _arun(self, text: str):
# Async version; here we call the synchronous implementation.
return self._run(text)
# Initialize the language model with a moderate temperature for controlled creativity.
llm = OpenAI(temperature=0.2)
# Define the list of tools that our agent can use.
tools = [EchoTool()]
# Initialize the agent using a specific agent type.
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, # Uses zero-shot reasoning.
verbose=True
)
# Define a query for the agent to process.
query = "Please echo the message: 'Hello, LangChain!'"
# Run the agent with the query and capture the response.
response = agent.run(query)
# Print the response.
print("Agent Response:", response)
view raw agent.py hosted with ❤ by GitHub