Use Desearch AI Search with OpenAI

    Use Desearch AI Search with OpenAI

    Use Desearch AI Search to fetch fresh web results and X posts, then pass them to an OpenAI chat completion as context. This page uses the async desearch-py client and the openai Python package.

    Get Started

    1. Installation

    BASH
    pip install openai desearch-py==1.2.1

    2. Set Up Clients

    PYTHON
    from openai import OpenAI
    from desearch_py import Desearch
    
    openai_client = OpenAI(api_key="YOUR_OPENAI_API_KEY")
    desearch = Desearch(api_key="YOUR_DESEARCH_API_KEY")

    3. Search with Desearch

    ai_search is async. It calls POST /desearch/ai/search and returns search (web results) and tweets (X posts) for the tools you pass.

    PYTHON
    import asyncio
    from desearch_py import Desearch
    
    async def fetch_sources(question: str):
        async with Desearch(api_key="YOUR_DESEARCH_API_KEY") as desearch:
            return await desearch.ai_search(
                prompt=question,
                tools=["web", "twitter"],
                date_filter=None,
                result_type="ONLY_LINKS",
                count=10,
            )

    4. Pass Results to OpenAI

    Turn the results into a context block and send it with the user question:

    PYTHON
    def to_context(result) -> str:
        data = result if isinstance(result, dict) else result.model_dump()
        lines = []
        for item in data.get("search") or []:
            lines.append(f"- {item.get('title')}: {item.get('link')}\n  {item.get('snippet', '')}")
        for tweet in data.get("tweets") or []:
            lines.append(f"- X post: {tweet.get('url')}\n  {tweet.get('text', '')}")
        return "\n".join(lines)
    
    question = "What are the latest developments in quantum computing?"
    result = asyncio.run(fetch_sources(question))
    
    completion = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Answer using the sources below. Cite links.\n\n" + to_context(result)},
            {"role": "user", "content": question},
        ],
    )
    print(completion.choices[0].message.content)

    ai_search can return a typed object or a plain dict, so to_context handles both.

    5. Complete Code Example

    Copy this into a script or notebook:

    PYTHON
    import asyncio
    from openai import OpenAI
    from desearch_py import Desearch
    
    openai_client = OpenAI(api_key="YOUR_OPENAI_API_KEY")
    
    async def fetch_sources(question: str):
        async with Desearch(api_key="YOUR_DESEARCH_API_KEY") as desearch:
            return await desearch.ai_search(
                prompt=question,
                tools=["web", "twitter"],
                date_filter=None,
                result_type="ONLY_LINKS",
                count=10,
            )
    
    def to_context(result) -> str:
        data = result if isinstance(result, dict) else result.model_dump()
        lines = []
        for item in data.get("search") or []:
            lines.append(f"- {item.get('title')}: {item.get('link')}\n  {item.get('snippet', '')}")
        for tweet in data.get("tweets") or []:
            lines.append(f"- X post: {tweet.get('url')}\n  {tweet.get('text', '')}")
        return "\n".join(lines)
    
    def answer(question: str) -> str:
        result = asyncio.run(fetch_sources(question))
        completion = openai_client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "Answer using the sources below. Cite links.\n\n" + to_context(result)},
                {"role": "user", "content": question},
            ],
        )
        return completion.choices[0].message.content
    
    print(answer("What are the latest breakthroughs in nuclear fusion?"))

    6. Handling Multiple Questions

    PYTHON
    questions = [
        "What progress has been made in CRISPR gene editing recently?",
        "How are autonomous vehicles handling extreme weather conditions?",
    ]
    
    for question in questions:
        print(f"Question: {question}")
        print(f"Answer: {answer(question)}")
        print("-" * 50)

    The snippets below use await, so run them inside an async function like fetch_sources above.

    Information Source Selection

    Pick which sources to search with the tools parameter of ai_search:

    PYTHON
    result = await desearch.ai_search(
        prompt=question,
        tools=["web", "twitter"],
        date_filter=None,
    )

    Supported tools: web, twitter. Other values are unsupported and may be rejected (for example, youtube returns 422).

    Time Relevance

    Filter results by date with the date_filter parameter. On AI Search, date filtering applies to X results.

    PYTHON
    
    result = await desearch.ai_search(
        prompt="What are people saying about quantum computing this week?",
        tools=["twitter"],
        date_filter="PAST_WEEK",
    )

    Response Format

    Control how results are returned with the result_type parameter:

    PYTHON
    result = await desearch.ai_search(
        prompt=question,
        tools=["web", "twitter"],
        date_filter=None,
        result_type="LINKS_WITH_FINAL_SUMMARY",
    )

    With LINKS_WITH_FINAL_SUMMARY, the response also includes a written summary in completion.