LangChain Framework
LangChain is a Python-based framework that supports the development, productionization, and deployment of LLM-powered applications. It provides modular components and integrations that make it easy to build intelligent agents capable of reasoning, decision-making, and tool usage.
LangChain Framework is supported with GPT-4.1, GPT-4o, GPT-4o mini, o3, o3-mini, o1, Jais 30B, Llama 3.3 70B, and Llama 3 70B models.
Build an Agent
To build an agent, follow the steps below:
-
Set up the environment
-
Install required dependencies
-
Build agent
Set Up Your Environment
-
Install Python (3.8+ recommended).
-
Create a virtual environment:
python -m venv langchain_env
source langchain_env/bin/activate # For Linux/Mac
langchain_env\\Scripts\\activate # For Windows -
Install LangChain:
$ pip install langchain
Install Required Dependencies
Install any additional libraries required for your agent, such as OpenAI or specific tool integrations:
$ pip install openai python-dotenv
$ pip install langchain_openai langchain_community langgraph ipykernel python-dotenv
Build Agent
Before building the agent, decide the agent’s role (e.g., answering questions, retrieving data, or automating workflows).
Choose an LLM
Connect to Compass GPT-4o model:
import os
from langchain_openai import ChatOpenAI
# Add "OPENAI_API_KEY" for the compass gpt-4o model
os.environ["OPENAI_API_KEY"] = "XXXXXXXXXXXXXX"
chat = ChatOpenAI(
model="gpt-4o",
openai_api_base="https://api.core42.ai/v1",
# while Compass API use different Authentication header "api-key" that you should set in the headers
default_headers={"api-key": "XXXXXXXXXXXXXX"},)
Add Tools
Tools allow agents to interact with external systems.
from langsmith import traceable
from langchain.schema import HumanMessage, SystemMessage
from langchain_community.tools import WikipediaQueryRun # pip install wikipedia
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.tools import YouTubeSearchTool # pip install youtube_search
Import the following three classes:
-
WikipediaAPIWrapper: to configure how to access the Wikipedia API
-
WikipediaQueryRun: to generate Wikipedia page summaries
-
YouTubeSearchTool: to search YouTube videos on topics
When a user queries the agent, it will decide whether to explain a topic using a Wikipedia article in text format or suggest YouTube videos for better topic understanding.
Start with the Wikipedia tool:
wiki_api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)
wikipedia = WikipediaQueryRun(description="A tool to explain things in text format. Use this tool if you think the user’s asked concept is best explained through text.", api_wrapper=wiki_api_wrapper)
print(wikipedia.invoke("Convex Optimization"))
Response:
Page: Convex optimization Summary: Convex optimization is a subfield of mathematical optimization that studies the problem of minimizing convex functions over convex sets (or, equivalently, maximizing concave functions over convex sets). Many classes
Initialize the YoutubeSearchTool
youtube = YouTubeSearchTool(
description="A tool to search YouTube videos. Use this tool if you think the user’s asked concept can be best explained by watching a video."
)
youtube.run("Oiling a bike's chain")
Response:
"['https://www.youtube.com/watch?v=X1Vze17bhgk&pp=ygUVT2lsaW5nIGEgYmlrZSdzIGNoYWlu', 'https://www.youtube.com/watch?v=ubKCHtZ20-0&pp=ygUVT2lsaW5nIGEgYmlrZSdzIGNoYWlu']"
The agent will decide which tool to use based on the description you provide.
Define the tools in a list:
tools = [wikipedia, youtube]
Bind tools using LangChain:
llm_with_tools = chat.bind_tools(tools)
llm_with_tools
Response:
RunnableBinding(bound=ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x128dc96d0>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x128dcbc80>, root_client=<openai.OpenAI object at 0x11c7fca10>, root_async_client=<openai.AsyncOpenAI object at 0x128dc9580>, model_name='gpt-4o', model_kwargs={}, openai_api_key=SecretStr('**********'), openai_api_base='https://api.core42.ai/v1', default_headers={'api-key': 'xxxxxxxxxxxxxxxxx'}), kwargs={'tools': [{'type': 'function', 'function': {'name': 'wikipedia', 'description': 'A tool to explain things in text format. Use this tool if you think the user’s asked concept is best explained through text.', 'parameters': {'properties': {'query': {'description': 'query to look up on wikipedia', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}, {'type': 'function', 'function': {'name': 'youtube_search', 'description': 'A tool to search YouTube videos. Use this tool if you think the user’s asked concept can be best explained by watching a video.', 'parameters': {'properties': {'query': {'type': 'string'}}, 'required': ['query'], 'type': 'object'}}}]}, config={}, config_factories=[])
response = llm_with_tools.invoke([
HumanMessage("Can you suggest content for Oiling a bike's chain?")
])
print(f"Text response: {response.content}")
print(f"Tools used in the response: {response.tool_calls}")
Text response:
Tools used in the response: [{'name': 'wikipedia', 'args': {'query': "oiling a bike's chain"}, 'id': 'call_A7zI5IBmPLhmR46BeN9L800V', 'type': 'tool_call'}, {'name': 'youtube_search', 'args': {'query': "oiling a bike's chain"}, 'id': 'call_dOXBym6dN4T4FpULC8m1ansD', 'type': 'tool_call'}]
Create Agent using LangGraph
from langgraph.prebuilt import create_react_agent
system_prompt = SystemMessage("You are a helpful bot named Chandler.")
agent = create_react_agent(chat, tools, state_modifier=system_prompt)
from pprint import pprint
response = agent.invoke({"messages": HumanMessage("What's up?")})
pprint(response["messages"])
[HumanMessage(content="What's up?", additional_kwargs={}, response_metadata={}, id='dd692e8a-71ed-4a25-95fe-140dcf0562fc'), AIMessage(content="Hello! I'm here to help you with information, answer questions, or assist you with tasks. What can I do for you today?", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 28, 'prompt_tokens': 123, 'total_tokens': 151, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_04751d0b65', 'finish_reason': 'stop', 'logprobs': None}, id='run-e41e5942-780d-4430-b6dd-289b1a2d26e1-0', usage_metadata={'input_tokens': 123, 'output_tokens': 28, 'total_tokens': 151, 'input_token_details': {}, 'output_token_details': {}})]
Create a function to invoke the agent:
def execute(agent, query):
response = agent.invoke({'messages': [HumanMessage(query)]})
for message in response['messages']:
print(
f"{message.__class__.__name__}: {message.content}"
) # Print message class name and its content
print("-" * 20, end="\n")
return response
Define the system prompt:
system_prompt = SystemMessage(
"""
You are a helpful bot named Chandler. Your task is to explain topics
asked by the user via three mediums: text, image or video.
If the asked topic is best explained in text format, use the Wikipedia tool.
If the topic is best explained by showing a picture of it, generate an image
of the topic using Dall-E image generator and print the image URL.
Finally, if video is the best medium to explain the topic, conduct a YouTube search on it
and return found video links.
"""
)
Invoke the agent:
agent = create_react_agent(chat, tools, state_modifier=system_prompt)
response = execute(agent, query='Explain the Fourier Series visually.')
Response:
HumanMessage: Explain the Fourier Series visually.
--------------------
AIMessage:
--------------------
ToolMessage: ['https://www.youtube.com/watch?v=ds0cmAV-Yek&pp=ygUaRm91cmllciBTZXJpZXMgZXhwbGFuYXRpb24%3D', 'https://www.youtube.com/watch?v=UKHBWzoOKsY&pp=ygUaRm91cmllciBTZXJpZXMgZXhwbGFuYXRpb24%3D']
--------------------
ToolMessage: Page: Fourier series
Summary: A Fourier series () is an expansion of a periodic function into a sum of trigonometric functions. The Fourier series is an example of a trigonometric series. By expressing a function as a sum of sines and cosines, many
--------------------
AIMessage: To understand the Fourier Series visually, you can check out the following resources:
### Videos
- [Fourier Series Explanation - Video 1](https://www.youtube.com/watch?v=ds0cmAV-Yek&pp=ygUaRm91cmllciBTZXJpZXMgZXhwbGFuYXRpb24%3D)
- [Fourier Series Explanation - Video 2](https://www.youtube.com/watch?v=UKHBWzoOKsY&pp=ygUaRm91cmllciBTZXJpZXJpZXMgZXhwbGFuYXRpb24%3D)
### Text Summary
A Fourier series is an expansion of a periodic function into a sum of trigonometric functions. It expresses a function as a sum of sines and cosines, which allows for analysis of the function in terms of these basic trigonometric components. By exploring these resources, you can get a detailed visual and theoretical explanation of the Fourier Series.
--------------------