Implement Intelligent Search with the LangSearch Web Search API in LangChain.
To successfully integrate the LangSearch Web Search API into LangChain and achieve intelligent search functionality, follow these steps:
Get an API Key
Visit the LangSearch(https://langsearch.com) and register or log in to your developer account. Navigate to the "API Key Management" page in the console and create a new application to obtain your exclusive API Key. Keep this key secure, as it will be used for authorizing subsequent API calls.
Define LangSearch Web Search API as a Tool in LangChain
Use the following example code to integrate the LangSearch Web Search API into LangChain by defining it as a custom Tool. This will allow LangChain to call the LangSearch search API when processing requests, enabling real-time information retrieval.
import requestsfrom langchain.agents import AgentExecutor, create_tool_calling_agentfrom langchain_core.prompts.chat import ChatPromptTemplatefrom langchain_openai import ChatOpenAIfrom langchain.tools import toolOPENAI_API_KEY =""LANGSEARCH_API_KEY =""# Define LangSearch Web Search tool@tooldeflangsearch_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"]!=200ornot json_response["data"]:returnf"Search API request failed, reason: {response.msg or'Unknown error'}" webpages = json_response["data"]["webPages"]["value"]ifnot webpages:return"No relevant results found." formatted_results =""for idx, page inenumerate(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()exceptExceptionas e:returnf"Search API request failed, reason: Failed to parse search results {str(e)}"else:returnf"Search API request failed, status code: {response.status_code}, error message: {response.text}"# Create LangChain toolstools = [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 modelmodel =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 toolsagent =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
{'input':'why the sky is blue?', 'output': "The sky appears blue due to a phenomenon called Rayleigh scattering. Here's how it works:\n\n1. **Sunlight Composition**: Sunlight, or white light, is made up of different colors, each with different wavelengths. The colors range from red (longer wavelengths) to violet (shorter wavelengths).\n\n2. **Atmospheric Interaction**: When sunlight enters the Earth's atmosphere, it collides with molecules and small particles in the air. This interaction causes the light to scatter in different directions.\n\n3. **Scattering of Colors**: Shorter wavelengths of light (blue and violet) scatter more than longer wavelengths (red and yellow). Although violet light scatters even more than blue, our eyes are more sensitive to blue light, and some of the violet light is absorbed by the ozone layer.\n\n4. **Resulting Color**: As a result of this scattering, when we look up at the sky during the day, we see a predominance of blue light, making the sky appear blue.\n\nThis effect is more pronounced when the sun is higher in the sky, and it can change during sunrise and sunset when the light has to pass through more atmosphere, scattering shorter wavelengths and allowing longer wavelengths (reds and oranges) to dominate."}