Using LangSearch in LangChain
Implement Intelligent Search with the LangSearch Web Search API in LangChain.
Get an API Key
Define LangSearch Web Search API as a Tool in LangChain
import requests
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain.tools import tool
OPENAI_API_KEY = ""
LANGSEARCH_API_KEY = ""
# Define LangSearch Web Search tool
@tool
def langsearch_websearch_tool(query: str, count: int = 10) -> str:
"""
Perform web search using LangSearch Web Search API.
Parameters:
- query: Search keywords
- count: Number of search results to return
Returns:
- Detailed information of search results, including web page title, web page URL, web page content, web page publication time, etc.
"""
url = "https://api.langsearch.com/v1/web-search"
headers = {
"Authorization": f"Bearer {LANGSEARCH_API_KEY}", # Please replace with your API key
"Content-Type": "application/json"
}
data = {
"query": query,
"freshness": "noLimit", # Search time range, e.g., "oneDay", "oneWeek", "oneMonth", "oneYear", "noLimit"
"summary": True, # Whether to return a long text summary
"count": count
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
json_response = response.json()
try:
if json_response["code"] != 200 or not json_response["data"]:
return f"Search API request failed, reason: {response.msg or 'Unknown error'}"
webpages = json_response["data"]["webPages"]["value"]
if not webpages:
return "No relevant results found."
formatted_results = ""
for idx, page in enumerate(webpages, start=1):
formatted_results += (
f"Citation: {idx}\n"
f"Title: {page['name']}\n"
f"URL: {page['url']}\n"
f"Content: {page['summary']}\n"
)
return formatted_results.strip()
except Exception as e:
return f"Search API request failed, reason: Failed to parse search results {str(e)}"
else:
return f"Search API request failed, status code: {response.status_code}, error message: {response.text}"
# Create LangChain tools
tools = [Tool(
name="LangSearchWebSearch",
func=langsearch_websearch_tool,
description="Use LangSearch Web Search API to search internet web pages. The input should be a search query string, and the output will return detailed information of search results, including web page title, web page URL, web page content, web page publication time, etc."
)]
# Initialize OpenAI language model
model = ChatOpenAI(
model="gpt-4o-mini",
temperature=0,
openai_api_key=OPENAI_API_KEY
)
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
]
)
# Initialize agent, including langsearch websearch tools
agent = create_tool_calling_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
user_question = "why the sky is blue?"
agent_executor.invoke({"input": user_question})
Result
Last updated