Spaces:
Running
Running
File size: 1,627 Bytes
9d3e192 |
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
"""
A direct implementation using requests to bypass the OpenAI SDK entirely.
This avoids any issues with the OpenAI client configuration.
"""
import requests
import json
def generate_completion(api_key, system_prompt, user_text, model="gpt-4"):
"""
Generate a completion by directly calling the OpenAI API using requests.
This bypasses the OpenAI SDK entirely.
"""
if not api_key or not system_prompt or not user_text:
return "Please provide an API key, select a transformation, and enter some text."
try:
# OpenAI API endpoint
url = "https://api.openai.com/v1/chat/completions"
# Headers with API key
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# Request payload
payload = {
"model": model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_text}
],
"temperature": 0.7,
"max_tokens": 2000
}
# Make the API call directly using requests
response = requests.post(url, headers=headers, json=payload)
# Check if the request was successful
if response.status_code == 200:
response_data = response.json()
return response_data["choices"][0]["message"]["content"]
else:
return f"Error: API returned status code {response.status_code}. {response.text}"
except Exception as e:
return f"Error: {str(e)}"
|