Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| GROQ_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| SERP_URL = "https://serpapi.com/search" | |
| class GroqClient: | |
| def __init__(self, api_key=None): | |
| self.api_key = api_key or os.getenv("GROQ_API_KEY") | |
| if not self.api_key: | |
| raise Exception("Set GROQ_API_KEY in Space secrets.") | |
| self.headers = {"Authorization": f"Bearer {self.api_key}"} | |
| def ask(self, messages, model, max_tokens=4096): | |
| payload = { | |
| "model": model, | |
| "messages": messages, | |
| "max_tokens": max_tokens, | |
| "temperature": 0 | |
| } | |
| r = requests.post(GROQ_URL, json=payload, headers=self.headers) | |
| data = r.json() | |
| try: | |
| return data["choices"][0]["message"]["content"] | |
| except: | |
| return str(data) | |
| class SerpClient: | |
| def __init__(self, api_key=None): | |
| self.api_key = api_key or os.getenv("SERPAPI_KEY") | |
| if not self.api_key: | |
| raise Exception("Set SERPAPI_KEY in Space secrets.") | |
| def search(self, query): | |
| params = {"q": query, "api_key": self.api_key} | |
| r = requests.get(SERP_URL, params=params) | |
| return r.json().get("organic_results", []) | |