Tst / app.py
Niansuh's picture
Update app.py
4279de7 verified
import requests
import json
# Define the URL for the API
url = 'https://ap-northeast-2.apistage.ai/v1/web/demo/chat/completions'
# Define the headers (the same ones from the curl command)
headers = {
'accept': '*/*',
'accept-language': 'en-US,en;q=0.9,ru;q=0.8',
'content-type': 'application/json',
'origin': 'https://console.upstage.ai',
'priority': 'u=1, i',
'referer': 'https://console.upstage.ai/',
'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'cross-site',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'x-csrf-token': 'MTczMjAyMjY0MzI4OS5hMjM5OTFmZGRiYmQ1Yjk4ODFjY2Q0NDhlYTk0YTdiODg5OWYzZWY1NWFlOWQ2ZjEzOWU3ODkwNmMzM2I4MjM0'
}
# Define the data (payload) to be sent in the POST request
data = {
'stream': True,
'messages': [
{
'role': 'user',
'content': 'Hi'
}
],
'model': 'solar-pro'
}
# Send the POST request to the API
response = requests.post(url, headers=headers, json=data)
# Check if the request was successful
if response.status_code == 200:
# Parse the response JSON
api_response = response.json()
# Assuming the API response structure contains 'message' field under 'choices'
# Convert the response to OpenAI format
openai_response = {
"id": api_response.get("id", "unknown_id"), # You can use 'id' or generate your own
"object": "chat.completion",
"created": api_response.get("created", 0), # Timestamp if available
"model": data['model'], # The model you used
"usage": {
"prompt_tokens": api_response.get("prompt_tokens", 0), # This might be in your API response
"completion_tokens": api_response.get("completion_tokens", 0), # This too
"total_tokens": api_response.get("total_tokens", 0)
},
"choices": [
{
"message": {
"role": api_response.get("messages", [{}])[0].get('role', 'user'), # Role from the response
"content": api_response.get("messages", [{}])[0].get('content', 'No response content')
},
"finish_reason": "stop", # This can be dynamic based on the response
"index": 0 # Default for single response
}
]
}
# Print the OpenAI formatted response
print(json.dumps(openai_response, indent=2))
else:
# If the request fails, print the error message
print(f'Failed to get a response. Status code: {response.status_code}')
print(response.text)