Using LangSearch in LangChain

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 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