Langchain Tools and Agents use cases with examples

This is the third in the series made for your understanding of LangChain. View the other 2 below:

LangChain—a revolutionary framework designed to simplify and enhance the development of language-based AI applications. In this blog post, we’ll explore the core components of LangChain, specifically focusing on its powerful tools and agents that make it a game-changer for developers and businesses alike.

Whether you’re a seasoned developer or just starting, LangChain provides the tools and resources you need to build powerful language model applications.

Tool

Tools are interfaces that an agent, chain, or LLM can use to interact with the world. They combine a few things:

  1. The name of the tool
  2. A description of what the tool is
  3. JSON schema of what the inputs to the tool are
  4. The function to call
  5. Whether the result of a tool should be returned directly to the user

Review the documentation for the tools here: https://python.langchain.com/v0.1/docs/modules/tools/

The built in list of tools are here: https://python.langchain.com/v0.1/docs/integrations/tools/

An example of a Wikipedia API wrapper that is built into LangChain is as follows:

from langchain.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
wikipedia.run("Harry Potter and the Philosopher's Stone")
#output for the above code 
Page: Harry Potter and the Philosopher's Stone (film)
Summary: Harry Potter and the Philosopher's Stone (also known as Harry Potter and the Sorcerer's Stone in the United States) is a 2001 fantasy film directed by Chris Columbus and produced by David Heyman, from a screenplay by Steve Kloves, based on the 1997 novel of the same name by J. K. Rowling. It is the first instalment in the Harry Potter film series. The film stars Daniel Radcliffe as Harry Potter, with Rupert Grint as Ron Weasley, and Emma Watson as Hermione Granger. Its story follows Harry's first year at Hogwarts School of Witchcraft and Wizardry as he discovers that he is a famous wizard and begins his formal wizarding education.
Warner Bros. Pictures bought the film rights to the book in 1999 for a reported £1 million ($1.65 million). Production began in the United Kingdom in 2000, with Columbus being chosen to helm the film from a short list of directors that included Steven Spielberg and Rob Reiner. Rowling insisted that the entire cast be British and Irish, with the three leads chosen in August 2000 following open casting calls. Filming took place at Leavesden Film Studios and historic buildings around the United Kingdom from September 2000 to March 2001.
Harry Potter and the Philosopher's Stone was released to cinemas in the United Kingdom and Ireland on 10 and 11 November 2001 for two days of previews. The film opened on 16 November in the United States, Canada, and Taiwan as well as officially in the United Kingdom and Ireland. It became a critical and commercial success, grossing $974 million at the worldwide box office during its initial run, and over $1 billion with subsequent re-releases. It became the highest-grossing film of 2001 and the

Agents

The core idea of agents is to use a language model to choose a sequence of actions to take. In chains, a sequence of actions is hardcoded (in code). In agents, a language model is used as a reasoning engine to determine which actions to take and in which order.

Review the documentation for the tools here: https://python.langchain.com/v0.1/docs/modules/agents/

A simple example of how you can use tools and agents

The loader can be used to load the documents. I made a consice list for you to glance through. The details are in this link.

  1. Web based:
    • Ex: WebBaseLoader(“https://docs.smith.langchain.com/”)
  2. Text file:
    • Ex: TextLoader(“speech.txt”)
  3. PDF document
    • PyPDFLoader(“layout-parser-paper.pdf”)
  4. CSV:
    • CSVLoader(file_path=’./example_data/mlb_teams_2012.csv’)
  5. File Directory:
    • DirectoryLoader(‘../’, glob=”**/*.md”)
  6. HTML:
    • UnstructuredHTMLLoader(“example_data/fake-content.html”)
  7. JSON:
    • json.loads(Path(file_path).read_text())
  8. Markdown:
    • UnstructuredMarkdownLoader(markdown_path)
  9. Loading docx,ppt, xlsx:
    • AzureAIDocumentIntelligenceLoaderapi_endpoint=endpoint, api_key=key, file_path=file_path, api_model=”prebuilt-layout”)
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

loader=WebBaseLoader("https://www.webmd.com/")
docs=loader.load()
documents=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200).split_documents(docs)
vectordb=FAISS.from_documents(documents,OpenAIEmbeddings())
#Retriever is an interface that returns documents given an unstructured query.
retriever=vectordb.as_retriever()

The above code block reads from the link, loads it into ‘docs’, Splits the text into ‘documents’. OpenAIEmbeddings()initializes the embedding model using your OpenAI API key to convert the text chunks into vector embeddings which are essential for similarity searches.
Create an index using FAISS based on the documents and embedding model to enable fast similarity searches within your dataset.

Create a retriever tool

from langchain.tools.retriever import create_retriever_tool
retriever_tool=create_retriever_tool(retriever,"Webmd", "Search for information about Causes and Symptoms")
retriever_tool.name
tools=[wiki,retriever_tool]

Pull an existing prompt from hub

from langchain import hub

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")
prompt.messages
Output

[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are a helpful assistant')),
 MessagesPlaceholder(variable_name='chat_history', optional=True),
 HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')),
 MessagesPlaceholder(variable_name='agent_scratchpad')]

Create an agent

### Agents
from langchain.agents import create_openai_tools_agent
agent=create_openai_tools_agent(llm,tools,prompt)

Create an agent executor to invoke

## Agent Executer
from langchain.agents import AgentExecutor
agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True)
agent_executor.invoke({"input":"Tell me about the symptoms of eczema"})

This access and retrieves the information about the symptoms of eczema based on the sources specified.

Real-World Applications

The combination of LangChain tools and agents opens up a world of possibilities for various industries. Here are a few examples of how LangChain can be applied:

1. Customer Support

By utilizing context-aware agents, businesses can provide exceptional customer support. Agents can handle inquiries, troubleshoot issues, and even escalate complex problems to human agents when necessary.

2. Content Creation

LangChain can assist in generating high-quality content for blogs, social media, and marketing campaigns. With customizable pipelines, businesses can tailor the output to match their brand voice and style.

3. Data Analysis

Agents can automate data extraction and analysis tasks, providing valuable insights without the need for extensive manual effort. This is particularly useful for industries like finance, healthcare, and market research.

4. Personal Assistants

Building intelligent personal assistants becomes straightforward with LangChain. Agents can manage schedules, set reminders, and even interact with other applications to streamline daily tasks.

Conclusion

In conclusion, LangChain’s tools and agents represent a significant leap forward in the development of AI applications. By combining robust building blocks with intelligent orchestrators, LangChain empowers developers to create dynamic, context-aware, and scalable solutions that can transform industries and enhance user experiences. Start exploring LangChain today and unlock the full potential of language-based AI.