Spaces:
Sleeping
Sleeping
| import requests | |
| api_key = "sw-xyz1234567891213" # Replace with your actual API key | |
| def call_api(prompt: str) -> str: | |
| """ | |
| Call an API with the given prompt and return the response. | |
| Note: This assumes a generic API endpoint. Adjust the URL and payload based on your API. | |
| """ | |
| headers = { | |
| 'Authorization': f'Bearer {api_key}', | |
| 'Content-Type': 'application/json' | |
| } | |
| payload = { | |
| 'model': 'gpt-3.5-turbo', # Adjust model based on your API | |
| 'messages': [{'role': 'user', 'content': prompt}], | |
| 'max_tokens': 500 | |
| } | |
| try: | |
| response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=payload, timeout=10) | |
| response.raise_for_status() | |
| result = response.json()['choices'][0]['message']['content'] | |
| return result | |
| except requests.exceptions.RequestException as e: | |
| print(f"API Request Error: {str(e)}") | |
| return f"Error: Failed to connect to API - {str(e)}" | |
| except KeyError as e: | |
| print(f"Parsing Error: {str(e)}. Raw response: {response.text}") | |
| return f"Error: Failed to parse API response - {str(e)}" | |
| # Example usage (uncomment to test locally) | |
| # if __name__ == "__main__": | |
| # prompt = "Generate a short description." | |
| # result = call_api(prompt) | |
| # print(result) |