Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,31 @@ for result in search.results:
print(f"{result.title}: {result.url}")
```

### Search with country filtering

You can restrict search results to specific countries using the `country` parameter:

```python
# Search for results from the United States
search_us = client.search.create(
query="latest tech news",
country="US", # ISO 3166-1 alpha-2 country code
max_results=5
)

# Search for results from the United Kingdom
search_uk = client.search.create(
query="weather forecast",
country="GB", # UK country code
max_results=5
)

for result in search_us.results:
print(f"{result.title}: {result.url}")
```

The `country` parameter accepts ISO 3166-1 alpha-2 country codes (e.g., "US", "GB", "CA", "DE", "FR", "JP", "AU", "IN").

## Chat Completions

The full API of this library can be found in [api.md](api.md).
Expand Down Expand Up @@ -509,4 +534,4 @@ Python 3.8 or higher.

## Contributing

See [the contributing documentation](./CONTRIBUTING.md).
See [the contributing documentation](./CONTRIBUTING.md).
115 changes: 115 additions & 0 deletions examples/search_with_country.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""
Example demonstrating the use of the country parameter in Perplexity search API.

This example shows how to use the newly added country parameter to restrict
search results to specific countries.

Before running this example:
1. Set your PERPLEXITY_API_KEY environment variable
2. Install the perplexity package: pip install perplexityai

Usage:
python examples/search_with_country.py
"""

import os
from perplexity import Perplexity


def main():
# Initialize the Perplexity client
client = Perplexity(
api_key=os.environ.get("PERPLEXITY_API_KEY")
)

# Example 1: Search with US country filter
print("🇺🇸 Searching for 'latest tech news' with country='US'")
print("-" * 60)

try:
search_us = client.search.create(
query="latest tech news",
country="US", # This is the new parameter!
max_results=3
)

for i, result in enumerate(search_us.results, 1):
print(f"{i}. {result.title}")
print(f" URL: {result.url}")
print()

except Exception as e:
print(f"Error: {e}")
print("Note: You need a valid PERPLEXITY_API_KEY to run this example.")
return

print("\n" + "=" * 60 + "\n")

# Example 2: Search with UK country filter
print("🇬🇧 Searching for 'weather forecast' with country='GB'")
print("-" * 60)

try:
search_uk = client.search.create(
query="weather forecast",
country="GB", # UK country code
max_results=3
)

for i, result in enumerate(search_uk.results, 1):
print(f"{i}. {result.title}")
print(f" URL: {result.url}")
print()

except Exception as e:
print(f"Error: {e}")

print("\n" + "=" * 60 + "\n")

# Example 3: Async usage with country parameter
print("🌍 Demonstrating async usage with country parameter")
print("-" * 60)

import asyncio
from perplexity import AsyncPerplexity

async def async_search_example():
async_client = AsyncPerplexity(
api_key=os.environ.get("PERPLEXITY_API_KEY")
)

try:
search = await async_client.search.create(
query="popular restaurants",
country="CA", # Canada
max_results=2
)

print("🇨🇦 Canadian restaurant search results:")
for i, result in enumerate(search.results, 1):
print(f"{i}. {result.title}")
print(f" URL: {result.url}")
print()

except Exception as e:
print(f"Async error: {e}")

# Run the async example
asyncio.run(async_search_example())

print("✅ Country parameter examples completed!")
print("\nNote: The country parameter accepts ISO 3166-1 alpha-2 country codes:")
print("- US (United States)")
print("- GB (United Kingdom)")
print("- CA (Canada)")
print("- DE (Germany)")
print("- FR (France)")
print("- JP (Japan)")
print("- AU (Australia)")
print("- IN (India)")
print("- And many more...")


if __name__ == "__main__":
main()
10 changes: 9 additions & 1 deletion src/perplexity/resources/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def create(
self,
*,
query: Union[str, SequenceNotStr[str]],
country: Optional[str] | Omit = omit,
display_server_time: bool | Omit = omit,
max_results: int | Omit = omit,
max_tokens: int | Omit = omit,
Expand All @@ -68,6 +69,8 @@ def create(
Search the web and retrieve relevant web page contents.

Args:
country: Country code to restrict search results to a specific country (e.g., "US", "GB", "CA")

extra_headers: Send extra headers

extra_query: Add additional query parameters to the request
Expand All @@ -81,6 +84,7 @@ def create(
body=maybe_transform(
{
"query": query,
"country": country,
"display_server_time": display_server_time,
"max_results": max_results,
"max_tokens": max_tokens,
Expand Down Expand Up @@ -124,6 +128,7 @@ async def create(
self,
*,
query: Union[str, SequenceNotStr[str]],
country: Optional[str] | Omit = omit,
display_server_time: bool | Omit = omit,
max_results: int | Omit = omit,
max_tokens: int | Omit = omit,
Expand All @@ -144,6 +149,8 @@ async def create(
Search the web and retrieve relevant web page contents.

Args:
country: Country code to restrict search results to a specific country (e.g., "US", "GB", "CA")

extra_headers: Send extra headers

extra_query: Add additional query parameters to the request
Expand All @@ -157,6 +164,7 @@ async def create(
body=await async_maybe_transform(
{
"query": query,
"country": country,
"display_server_time": display_server_time,
"max_results": max_results,
"max_tokens": max_tokens,
Expand Down Expand Up @@ -209,4 +217,4 @@ def __init__(self, search: AsyncSearchResource) -> None:

self.create = async_to_streamed_response_wrapper(
search.create,
)
)
4 changes: 3 additions & 1 deletion src/perplexity/types/search_create_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
class SearchCreateParams(TypedDict, total=False):
query: Required[Union[str, SequenceNotStr[str]]]

country: Optional[str]

display_server_time: bool

max_results: int
Expand All @@ -29,4 +31,4 @@ class SearchCreateParams(TypedDict, total=False):

search_mode: Optional[Literal["web", "academic", "sec"]]

search_recency_filter: Optional[Literal["hour", "day", "week", "month", "year"]]
search_recency_filter: Optional[Literal["hour", "day", "week", "month", "year"]]