Table of Contents
Key Learning Outcomes
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
Custom Tool: Meaning of Life
Custom Tool: Random Number Generator
Building the Conversational Agent with Custom Tools
Agent Initialization
Agent Memory
Agent Construction
Agent Testing
Customizing the System Prompt
Utilizing the Tool Class for Web Scraping
Creating a WebPageTool Class
Conclusion
Key Takeaways
Frequently Asked Questions
Home Technology peripherals AI Setting up Custom Tools and Agents in LangChain

Setting up Custom Tools and Agents in LangChain

Mar 20, 2025 am 10:19 AM

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>
Copy after login

Verify LangChain's installation:

<code>!pip show langchain</code>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

Apply the modified prompt:

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

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>
Copy after login

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) ...
Copy after login

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/?")
Copy after login

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to Build MultiModal AI Agents Using Agno Framework? How to Build MultiModal AI Agents Using Agno Framework? Apr 23, 2025 am 11:30 AM

While working on Agentic AI, developers often find themselves navigating the trade-offs between speed, flexibility, and resource efficiency. I have been exploring the Agentic AI framework and came across Agno (earlier it was Phi-

How to Add a Column in SQL? - Analytics Vidhya How to Add a Column in SQL? - Analytics Vidhya Apr 17, 2025 am 11:43 AM

SQL's ALTER TABLE Statement: Dynamically Adding Columns to Your Database In data management, SQL's adaptability is crucial. Need to adjust your database structure on the fly? The ALTER TABLE statement is your solution. This guide details adding colu

OpenAI Shifts Focus With GPT-4.1, Prioritizes Coding And Cost Efficiency OpenAI Shifts Focus With GPT-4.1, Prioritizes Coding And Cost Efficiency Apr 16, 2025 am 11:37 AM

The release includes three distinct models, GPT-4.1, GPT-4.1 mini and GPT-4.1 nano, signaling a move toward task-specific optimizations within the large language model landscape. These models are not immediately replacing user-facing interfaces like

Beyond The Llama Drama: 4 New Benchmarks For Large Language Models Beyond The Llama Drama: 4 New Benchmarks For Large Language Models Apr 14, 2025 am 11:09 AM

Troubled Benchmarks: A Llama Case Study In early April 2025, Meta unveiled its Llama 4 suite of models, boasting impressive performance metrics that positioned them favorably against competitors like GPT-4o and Claude 3.5 Sonnet. Central to the launc

New Short Course on Embedding Models by Andrew Ng New Short Course on Embedding Models by Andrew Ng Apr 15, 2025 am 11:32 AM

Unlock the Power of Embedding Models: A Deep Dive into Andrew Ng's New Course Imagine a future where machines understand and respond to your questions with perfect accuracy. This isn't science fiction; thanks to advancements in AI, it's becoming a r

How ADHD Games, Health Tools & AI Chatbots Are Transforming Global Health How ADHD Games, Health Tools & AI Chatbots Are Transforming Global Health Apr 14, 2025 am 11:27 AM

Can a video game ease anxiety, build focus, or support a child with ADHD? As healthcare challenges surge globally — especially among youth — innovators are turning to an unlikely tool: video games. Now one of the world’s largest entertainment indus

Rocket Launch Simulation and Analysis using RocketPy - Analytics Vidhya Rocket Launch Simulation and Analysis using RocketPy - Analytics Vidhya Apr 19, 2025 am 11:12 AM

Simulate Rocket Launches with RocketPy: A Comprehensive Guide This article guides you through simulating high-power rocket launches using RocketPy, a powerful Python library. We'll cover everything from defining rocket components to analyzing simula

Google Unveils The Most Comprehensive Agent Strategy At Cloud Next 2025 Google Unveils The Most Comprehensive Agent Strategy At Cloud Next 2025 Apr 15, 2025 am 11:14 AM

Gemini as the Foundation of Google’s AI Strategy Gemini is the cornerstone of Google’s AI agent strategy, leveraging its advanced multimodal capabilities to process and generate responses across text, images, audio, video and code. Developed by DeepM

See all articles