> ## Documentation Index
> Fetch the complete documentation index at: https://docs.linkup.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Langchain

> How to use Linkup with our Langchain SDK

## Overview

Linkup can be used with [LangChain](https://www.langchain.com/) as a [Retriever](https://python.langchain.com/api_reference/core/retrievers.html). The integration retrieves contextual information from the web inside a LangChain pipeline.

## Getting Started with Linkup in LangChain

**1. Install the LangChain integration**

```shell theme={"system"}
pip install langchain-linkup
```

**2. Get your Linkup API Key**

> [card] [Get your API key](https://app.linkup.so)
>
> Create a Linkup account for free to get your API key.

**3. Create and use the Linkup Retriever**

```python theme={"system"}
from langchain_linkup import LinkupSearchRetriever
import os

os.environ["LINKUP_API_KEY"] = "PASTE_YOUR_API_KEY_HERE"

retriever = LinkupSearchRetriever(
depth="deep",  # "flash", "fast", "standard" or "deep"
)

# Perform a search query
documents = retriever.invoke(input="What is Linkup, the new French AI startup?")
print(documents)
```

> [!NOTE]
>
> | Parameter | Options | Description |
> | - | - | - |
> | `depth` | `"flash"`, `"fast"`, `"standard"`, `"deep"` | Controls search depth. `"flash"` is currently in alpha and offers the lowest latency (under 200 ms, no LLM). `"fast"` is higher-quality one-shot retrieval (\~1s, no LLM). `"standard"` leverages agentic search. `"deep"` performs more thorough research. |
> | `outputType` | `"searchResults"`, `"sourcedAnswer"`, `"structured"` | Determines the format of returned information. |

## Example Project: RAG Pipeline with OpenAI

**1. Install dependencies**

```shell theme={"system"}
pip install langchain-openai python-dotenv
```

**2. Set up API keys**

> [!NOTE]
>
> You need API keys for both Linkup and OpenAI. You can get an OpenAI API key [here](https://openai.com/index/openai-api/).

```python theme={"system"}
import os
from dotenv import load_dotenv

# Load from .env file if available
load_dotenv()

# Or set manually
os.environ["LINKUP_API_KEY"] = "YOUR_LINKUP_API_KEY"
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
```

**3. Create the RAG pipeline**

```python theme={"system"}
from typing import Any, Literal
from langchain_core.documents import Document
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import Runnable, RunnableLambda, RunnablePassthrough
from langchain_openai import ChatOpenAI
from langchain_linkup import LinkupSearchRetriever

# Configuration
query: str = "What is Linkup, the new French AI startup?"
linkup_depth: Literal["flash", "fast", "standard", "deep"] = "standard"
open_ai_model: str = "gpt-4o-mini"

# Initialize retriever
retriever = LinkupSearchRetriever(depth=linkup_depth)

# Format documents helper function
def format_retrieved_documents(docs: list[Document]) -> str:
    return "\n\n".join(
        [
            f"{document.metadata['name']} ({document.metadata['url']}):\n{document.page_content}"
            for document in docs
        ]
    )

# Debug helper function
def inspect_context(state: dict[str, Any]) -> dict[str, Any]:
    print(f"Context: {state['context']}\n\n")
    return state

# Create prompt and model
generation_prompt_template = """Answer the question based only on the following context:

{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(generation_prompt_template)
model = ChatOpenAI(model=open_ai_model)
```

**4. Run the pipeline**

```python theme={"system"}
# Build and execute the chain
chain: Runnable[Any, str] = (
    {"context": retriever | format_retrieved_documents, "question": RunnablePassthrough()}
    | RunnableLambda(inspect_context)
    | prompt
    | model
    | StrOutputParser()
)

# Get response
response = chain.invoke(input=query)
print(f"Response: {response}")
```

**Example Response**

```
Context: Linkup (https://www.linkup.fr):
Linkup is a French AI startup that provides a search API for LLMs, enabling them to search the web and access up-to-date information.

Response: Linkup is a French AI startup that has developed a search API specifically designed for Large Language Models (LLMs). Their technology allows LLMs to search the web and access current information, which helps overcome the limitation of outdated training data that many AI models face. This enables applications built with LLMs to provide more accurate and up-to-date responses by connecting them to real-time information from the internet.
```

> [!NOTE]
>
> **Need help?** Email `support@linkup.so`, ping us on [Discord](https://discord.com/invite/9q9mCYJa86), or [talk to us](https://calendar.app.google/zNUZz7RxgMMk9pKW7).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.