File size: 1,333 Bytes
05e53ee
 
918b89d
05e53ee
 
 
918b89d
 
05e53ee
 
 
 
 
 
918b89d
05e53ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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)