perplexity.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from typing import Any
  2. import requests
  3. from core.tools.errors import ToolProviderCredentialValidationError
  4. from core.tools.provider.builtin.perplexity.tools.perplexity_search import PERPLEXITY_API_URL
  5. from core.tools.provider.builtin_tool_provider import BuiltinToolProviderController
  6. class PerplexityProvider(BuiltinToolProviderController):
  7. def _validate_credentials(self, credentials: dict[str, Any]) -> None:
  8. headers = {
  9. "Authorization": f"Bearer {credentials.get('perplexity_api_key')}",
  10. "Content-Type": "application/json"
  11. }
  12. payload = {
  13. "model": "llama-3.1-sonar-small-128k-online",
  14. "messages": [
  15. {
  16. "role": "system",
  17. "content": "You are a helpful assistant."
  18. },
  19. {
  20. "role": "user",
  21. "content": "Hello"
  22. }
  23. ],
  24. "max_tokens": 5,
  25. "temperature": 0.1,
  26. "top_p": 0.9,
  27. "stream": False
  28. }
  29. try:
  30. response = requests.post(PERPLEXITY_API_URL, json=payload, headers=headers)
  31. response.raise_for_status()
  32. except requests.RequestException as e:
  33. raise ToolProviderCredentialValidationError(
  34. f"Failed to validate Perplexity API key: {str(e)}"
  35. )
  36. if response.status_code != 200:
  37. raise ToolProviderCredentialValidationError(
  38. f"Perplexity API key is invalid. Status code: {response.status_code}"
  39. )