From 8a5f7a5ead73d0eacdadcc56d855bfc3d91f074d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Magnus=20M=C3=BCller?= <67061560+MagMueller@users.noreply.github.com> Date: Sun, 25 May 2025 16:46:08 +0200 Subject: [PATCH] Refactor perplexity search to use httpx for asynchronous requests This update replaces the synchronous requests library with httpx for making asynchronous API calls in the perplexity search function. The change improves performance and error handling by utilizing async capabilities, ensuring better integration with the overall asynchronous architecture. --- .../custom-functions/perplexity_search.py | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/examples/custom-functions/perplexity_search.py b/examples/custom-functions/perplexity_search.py index 597b25841..b87f71ce9 100644 --- a/examples/custom-functions/perplexity_search.py +++ b/examples/custom-functions/perplexity_search.py @@ -37,9 +37,7 @@ controller = Controller(exclude_actions=['search_google'], output_model=PersonLi @controller.registry.action('Search the web for a specific query with perplexity') async def search_web(query: str): - import json - - import requests + import httpx url = 'https://api.perplexity.ai/chat/completions' @@ -52,14 +50,15 @@ async def search_web(query: str): } headers = {'Authorization': f'Bearer {PERPLEXITY_API_KEY}', 'Content-Type': 'application/json'} - response = requests.request('POST', url, json=payload, headers=headers) - - response_json = json.loads(response.text) - content = response_json['choices'][0]['message']['content'] - citations = response_json['citations'] - output = f'{content}\n\nCitations:\n' + '\n'.join(citations) - logger.info(output) - return ActionResult(extracted_content=output, include_in_memory=True) + async with httpx.AsyncClient() as client: + response = await client.post(url, json=payload, headers=headers) + response.raise_for_status() + response_json = response.json() + content = response_json['choices'][0]['message']['content'] + citations = response_json['citations'] + output = f'{content}\n\nCitations:\n' + '\n'.join(citations) + logger.info(output) + return ActionResult(extracted_content=output, include_in_memory=True) names = [