Spaces:
Sleeping
Sleeping
Create api_utils.py
Browse files- api_utils.py +34 -0
api_utils.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
|
| 3 |
+
api_key = "your_valid_openai_api_key_here" # Replace with your OpenAI API key (e.g., sk-...)
|
| 4 |
+
|
| 5 |
+
def call_api(prompt: str) -> str:
|
| 6 |
+
"""
|
| 7 |
+
Call the OpenAI API with the given prompt and return the response.
|
| 8 |
+
"""
|
| 9 |
+
headers = {
|
| 10 |
+
'Authorization': f'Bearer {api_key}',
|
| 11 |
+
'Content-Type': 'application/json'
|
| 12 |
+
}
|
| 13 |
+
payload = {
|
| 14 |
+
'model': 'gpt-3.5-turbo',
|
| 15 |
+
'messages': [{'role': 'user', 'content': prompt}],
|
| 16 |
+
'max_tokens': 500
|
| 17 |
+
}
|
| 18 |
+
try:
|
| 19 |
+
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=payload, timeout=10)
|
| 20 |
+
response.raise_for_status()
|
| 21 |
+
result = response.json()['choices'][0]['message']['content']
|
| 22 |
+
return result
|
| 23 |
+
except requests.exceptions.RequestException as e:
|
| 24 |
+
print(f"API Request Error: {str(e)}")
|
| 25 |
+
return f"Error: Failed to connect to API - {str(e)}"
|
| 26 |
+
except KeyError as e:
|
| 27 |
+
print(f"Parsing Error: {str(e)}. Raw response: {response.text}")
|
| 28 |
+
return f"Error: Failed to parse API response - {str(e)}"
|
| 29 |
+
|
| 30 |
+
# Example usage (uncomment to test locally)
|
| 31 |
+
# if __name__ == "__main__":
|
| 32 |
+
# prompt = "Generate a short description."
|
| 33 |
+
# result = call_api(prompt)
|
| 34 |
+
# print(result)
|