search
HomeTechnology peripheralsAISetting up Custom Tools and Agents in LangChain

This tutorial demonstrates building a versatile conversational AI agent using LangChain, a powerful framework that integrates Large Language Models (LLMs) with external tools and APIs. This agent can perform diverse tasks, from generating random numbers and offering philosophical musings to dynamically retrieving and processing information from webpages. The combination of pre-built and custom tools enables real-time, context-aware, and informative responses.

Key Learning Outcomes

  • Master LangChain's integration with LLMs and external resources.
  • Develop and implement custom tools for specialized functions within your conversational agent.
  • Efficiently fetch and process live web data for accurate responses.
  • Build a conversational agent that retains context for coherent interactions.

*This article is part of the***Data Science Blogathon.

Table of Contents

  • Why Combine LangChain, OpenAI, and DuckDuckGo?
  • Installing Necessary Packages
  • Configuring API Access
  • Connecting LangChain to OpenAI Models
  • Integrating a Web Search Tool
  • Creating Custom Functions
  • Building the Conversational Agent with Custom Tools
  • Utilizing the Tool Class for Web Scraping
  • Conclusion
  • Frequently Asked Questions

Why Combine LangChain, OpenAI, and DuckDuckGo?

The synergy of LangChain, OpenAI, and DuckDuckGo allows for sophisticated conversational AI. OpenAI's LLMs provide natural language processing, while DuckDuckGo offers a privacy-focused search API. This combination enables the AI to generate contextually relevant responses and retrieve real-time data, enhancing its adaptability and accuracy. This powerful toolkit is ideal for creating intelligent chatbots or virtual assistants capable of handling diverse user inquiries.

Installing Necessary Packages

Begin by installing required Python packages using pip:

<code>!pip -q install langchain==0.3.4 openai
pip install langchain
!pip -q install duckduckgo-search</code>

Verify LangChain's installation:

<code>!pip show langchain</code>

Setting up Custom Tools and Agents in LangChain

Configuring API Access

Obtain your OpenAI API key and set it as an environment variable:

<code>import os

os.environ["OPENAI_API_KEY"] = "your_openai_key_here"</code>

Replace "your_openai_key_here" with your actual key. This is crucial for interacting with the GPT-3.5-turbo model.

Connecting LangChain to OpenAI Models

Establish a connection to OpenAI's model using LangChain:

<code>from langchain import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.chains.conversation.memory import ConversationBufferWindowMemory

# Configure the GPT-4o LLM
turbo_llm = ChatOpenAI(
    temperature=0,
    model_name='gpt-4o'
)</code>

A low temperature (temperature=0) ensures consistent responses.

Integrating a Web Search Tool

Enhance your agent's capabilities by adding the DuckDuckGo search tool:

<code>from langchain.tools import DuckDuckGoSearchTool
from langchain.agents import Tool
from langchain.tools import BaseTool

search = DuckDuckGoSearchTool()

# Define the tool
tools = [
    Tool(
        name = "search",
        func=search.run,
        description="Best for questions about current events.  Use precise queries."
    )
]</code>

This tool, described as ideal for current events, is added to the agent's toolkit.

Creating Custom Functions

Extend your agent's functionality with custom tools:

Custom Tool: Meaning of Life

This function provides a playful response to the question of life's meaning:

<code>def meaning_of_life(input=""):
    return 'The meaning of life is 42 (approximately!)'

life_tool = Tool(
    name='Meaning of Life',
    func= meaning_of_life,
    description="Use for questions about the meaning of life. Input: 'MOL'"
)</code>

Custom Tool: Random Number Generator

This tool generates random integers between 0 and 5:

<code>import random

def random_num(input=""):
    return random.randint(0,5)

random_tool = Tool(
    name='Random number',
    func= random_num,
    description="Use to get a random number. Input: 'random'"
)</code>

Building the Conversational Agent with Custom Tools

Creating a conversational agent with custom tools allows for highly tailored interactions.

Agent Initialization

Import initialize_agent and define the tools:

<code>from langchain.agents import initialize_agent

tools = [search, random_tool, life_tool]</code>

Agent Memory

Implement memory using ConversationBufferWindowMemory:

<code>from langchain.chains.conversation.memory import ConversationBufferWindowMemory

memory = ConversationBufferWindowMemory(
    memory_key='chat_history',
    k=3,
    return_messages=True
)</code>

This allows the agent to recall recent conversation turns (up to 3).

Agent Construction

Initialize the agent:

<code>conversational_agent = initialize_agent(
    agent='chat-conversational-react-description',
    tools=tools,
    llm=turbo_llm,
    verbose=True,
    max_iterations=3,
    early_stopping_method='generate',
    memory=memory
)</code>

The parameters specify the agent type, tools, LLM, verbosity, iteration limit, early stopping, and memory.

Agent Testing

Interact with the agent:

<code>conversational_agent("What time is it in London?")
conversational_agent("Can you give me a random number?")
conversational_agent("What is the meaning of life?")</code>

Setting up Custom Tools and Agents in LangChain Setting up Custom Tools and Agents in LangChain Setting up Custom Tools and Agents in LangChain

Customizing the System Prompt

Refine the agent's behavior by adjusting the system prompt:

<code># system prompt
conversational_agent.agent.llm_chain.prompt.messages[0].prompt.template</code>

Setting up Custom Tools and Agents in LangChain

<code>fixed_prompt = '''Assistant is a large language model... [modified prompt instructing the agent to use tools appropriately]'''</code>

Apply the modified prompt:

<code>conversational_agent.agent.llm_chain.prompt.messages[0].prompt.template = fixed_prompt</code>

Retest the agent.

Setting up Custom Tools and Agents in LangChain Setting up Custom Tools and Agents in LangChain

Utilizing the Tool Class for Web Scraping

Create a custom tool to extract plain text from webpages:

<code>from bs4 import BeautifulSoup
import requests
from langchain.agents import Tool

def stripped_webpage(webpage):
    # ... (function to fetch and clean webpage text) ...

web_scraper_tool = Tool(
    name='Web Scraper',
    func=stripped_webpage,
    description="Fetches and cleans webpage text (limited to 4000 characters)."
)</code>

Integrate this tool into your agent.

Creating a WebPageTool Class

A more robust solution involves creating a custom WebPageTool class:

from langchain.tools import BaseTool
from bs4 import BeautifulSoup
import requests

class WebPageTool(BaseTool):
    # ... (class definition as in original response) ...

Reinitialize the agent with the new tool and updated system prompt. Test with examples like:

conversational_agent.run("Is there an article about Clubhouse on https://techcrunch.com/? today")
conversational_agent.run("What are the top stories on www.cbsnews.com/?")

Setting up Custom Tools and Agents in LangChain Setting up Custom Tools and Agents in LangChain Setting up Custom Tools and Agents in LangChain

Conclusion

This tutorial demonstrates building a highly adaptable conversational agent using LangChain. The modular design allows for easy expansion and customization. This agent showcases the power of combining AI with real-time data access.

Key Takeaways

  • LangChain enables modular agent construction.
  • Web scraping and search tools provide up-to-date information.
  • Custom tools tailor the agent to specific needs.
  • Memory features maintain conversational context.

Frequently Asked Questions

(Same FAQs as in the original response, reworded for better flow and conciseness.)

The above is the detailed content of Setting up Custom Tools and Agents in LangChain. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Can't use ChatGPT! Explaining the causes and solutions that can be tested immediately [Latest 2025]Can't use ChatGPT! Explaining the causes and solutions that can be tested immediately [Latest 2025]May 14, 2025 am 05:04 AM

ChatGPT is not accessible? This article provides a variety of practical solutions! Many users may encounter problems such as inaccessibility or slow response when using ChatGPT on a daily basis. This article will guide you to solve these problems step by step based on different situations. Causes of ChatGPT's inaccessibility and preliminary troubleshooting First, we need to determine whether the problem lies in the OpenAI server side, or the user's own network or device problems. Please follow the steps below to troubleshoot: Step 1: Check the official status of OpenAI Visit the OpenAI Status page (status.openai.com) to see if the ChatGPT service is running normally. If a red or yellow alarm is displayed, it means Open

Calculating The Risk Of ASI Starts With Human MindsCalculating The Risk Of ASI Starts With Human MindsMay 14, 2025 am 05:02 AM

On 10 May 2025, MIT physicist Max Tegmark told The Guardian that AI labs should emulate Oppenheimer’s Trinity-test calculus before releasing Artificial Super-Intelligence. “My assessment is that the 'Compton constant', the probability that a race to

An easy-to-understand explanation of how to write and compose lyrics and recommended tools in ChatGPTAn easy-to-understand explanation of how to write and compose lyrics and recommended tools in ChatGPTMay 14, 2025 am 05:01 AM

AI music creation technology is changing with each passing day. This article will use AI models such as ChatGPT as an example to explain in detail how to use AI to assist music creation, and explain it with actual cases. We will introduce how to create music through SunoAI, AI jukebox on Hugging Face, and Python's Music21 library. Through these technologies, everyone can easily create original music. However, it should be noted that the copyright issue of AI-generated content cannot be ignored, and you must be cautious when using it. Let’s explore the infinite possibilities of AI in the music field together! OpenAI's latest AI agent "OpenAI Deep Research" introduces: [ChatGPT]Ope

What is ChatGPT-4? A thorough explanation of what you can do, the pricing, and the differences from GPT-3.5!What is ChatGPT-4? A thorough explanation of what you can do, the pricing, and the differences from GPT-3.5!May 14, 2025 am 05:00 AM

The emergence of ChatGPT-4 has greatly expanded the possibility of AI applications. Compared with GPT-3.5, ChatGPT-4 has significantly improved. It has powerful context comprehension capabilities and can also recognize and generate images. It is a universal AI assistant. It has shown great potential in many fields such as improving business efficiency and assisting creation. However, at the same time, we must also pay attention to the precautions in its use. This article will explain the characteristics of ChatGPT-4 in detail and introduce effective usage methods for different scenarios. The article contains skills to make full use of the latest AI technologies, please refer to it. OpenAI's latest AI agent, please click the link below for details of "OpenAI Deep Research"

Explaining how to use the ChatGPT app! Japanese support and voice conversation functionExplaining how to use the ChatGPT app! Japanese support and voice conversation functionMay 14, 2025 am 04:59 AM

ChatGPT App: Unleash your creativity with the AI ​​assistant! Beginner's Guide The ChatGPT app is an innovative AI assistant that handles a wide range of tasks, including writing, translation, and question answering. It is a tool with endless possibilities that is useful for creative activities and information gathering. In this article, we will explain in an easy-to-understand way for beginners, from how to install the ChatGPT smartphone app, to the features unique to apps such as voice input functions and plugins, as well as the points to keep in mind when using the app. We'll also be taking a closer look at plugin restrictions and device-to-device configuration synchronization

How do I use the Chinese version of ChatGPT? Explanation of registration procedures and feesHow do I use the Chinese version of ChatGPT? Explanation of registration procedures and feesMay 14, 2025 am 04:56 AM

ChatGPT Chinese version: Unlock new experience of Chinese AI dialogue ChatGPT is popular all over the world, did you know it also offers a Chinese version? This powerful AI tool not only supports daily conversations, but also handles professional content and is compatible with Simplified and Traditional Chinese. Whether it is a user in China or a friend who is learning Chinese, you can benefit from it. This article will introduce in detail how to use ChatGPT Chinese version, including account settings, Chinese prompt word input, filter use, and selection of different packages, and analyze potential risks and response strategies. In addition, we will also compare ChatGPT Chinese version with other Chinese AI tools to help you better understand its advantages and application scenarios. OpenAI's latest AI intelligence

5 AI Agent Myths You Need To Stop Believing Now5 AI Agent Myths You Need To Stop Believing NowMay 14, 2025 am 04:54 AM

These can be thought of as the next leap forward in the field of generative AI, which gave us ChatGPT and other large-language-model chatbots. Rather than simply answering questions or generating information, they can take action on our behalf, inter

An easy-to-understand explanation of the illegality of creating and managing multiple accounts using ChatGPTAn easy-to-understand explanation of the illegality of creating and managing multiple accounts using ChatGPTMay 14, 2025 am 04:50 AM

Efficient multiple account management techniques using ChatGPT | A thorough explanation of how to use business and private life! ChatGPT is used in a variety of situations, but some people may be worried about managing multiple accounts. This article will explain in detail how to create multiple accounts for ChatGPT, what to do when using it, and how to operate it safely and efficiently. We also cover important points such as the difference in business and private use, and complying with OpenAI's terms of use, and provide a guide to help you safely utilize multiple accounts. OpenAI

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software