# haystack-brave-search

[![PyPI version](https://img.shields.io/pypi/v/haystack-brave-search.svg)](https://pypi.org/project/haystack-brave-search/)
[![Python versions](https://img.shields.io/pypi/pyversions/haystack-brave-search.svg)](https://pypi.org/project/haystack-brave-search/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A [Haystack](https://haystack.deepset.ai/) component for web search using the [Brave Search API](https://brave.com/search/api/).

## Installation

```bash
pip install haystack-brave-search
```

## Requirements

* Python 3.12+
* A ```Brave Search API key```

## Usage
### Standalone

```python
from haystack_brave_search import BraveWebSearch

searcher = BraveWebSearch(api_key="your-api-key", top_k=5, country="BE", language="en")
result = searcher.run(query="Haystack AI framework")

for doc in result["documents"]:
    print(doc.meta["title"])
    print(doc.meta["url"])
    print(doc.content)
```
### In a Haystack Pipeline

```python
from haystack import Pipeline
from haystack.components.builders import PromptBuilder
from haystack_brave_search import BraveWebSearch

prompt_template = """
Given the following search results:
{% for doc in documents %}
- {{ doc.meta.title }}: {{ doc.content }}
{% endfor %}

Answer the question: {{ query }}
"""

pipe = Pipeline()
pipe.add_component("search", BraveWebSearch(api_key="your-api-key", top_k=5))
pipe.add_component("prompt", PromptBuilder(template=prompt_template))

pipe.connect("search.documents", "prompt.documents")

result = pipe.run({
    "search": {"query": "What is RAG?"},
    "prompt": {"query": "What is RAG?"}
})

print(result["prompt"]["prompt"])
```

### With AsyncPipeline

```python
from haystack import AsyncPipeline
from haystack_brave_search import BraveWebSearch

pipe = AsyncPipeline()
pipe.add_component("search", BraveWebSearch(api_key="your-api-key", top_k=5))
```

### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str` | required | Your Brave Search API key |
| `top_k` | `int` | `5` | Number of results to return |
| `country` | `str` | `None` | Country code to localise results (e.g. `"BE"`, `"GR"`) |
| `language` | `str` | `None` | Language code for search results using ISO 639-1 (e.g. `"en"`, `"el"`, ...) |

### Output

The ```run()``` method returns a dict with a ```documents``` key containing a list of Haystack ```Document``` objects:

* ```document.content``` — snippet/description of the result

* ```document.meta["title"]``` — page title

* ```document.meta["url"]``` — page URL

### Environment Variable

You can avoid hardcoding the API key by using an environment variable:

```python
import os
from haystack_brave_search import BraveWebSearch

searcher = BraveWebSearch(api_key=os.environ["BRAVE_API_KEY"])
```

### License

MIT