|
import os |
|
import openai |
|
import gradio as gr |
|
|
|
|
|
api_key = os.getenv('OPENAI_API_KEY') |
|
if not api_key: |
|
raise ValueError("OpenAI API key not found. Please set it in the environment variables.") |
|
openai.api_key = api_key |
|
|
|
def chatbot(input_text): |
|
print(f"Received input: {input_text}") |
|
try: |
|
response = openai.chat.completions.create( |
|
model="gpt-3.5-turbo", |
|
messages=[ |
|
{"role": "system", "content": "You are a helpful assistant."}, |
|
{"role": "user", "content": input_text} |
|
] |
|
) |
|
'''''' |
|
print("Response object type:", type(response)) |
|
print("Response object:", response) |
|
|
|
print("Choices type:", type(response.choices)) |
|
print("First choice type:", type(response.choices[0])) |
|
print("First choice:", response.choices[0]) |
|
|
|
print("Message type:", type(response.choices[0].message)) |
|
print("Message:", response.choices[0].message) |
|
|
|
print("Content type:", type(response.choices[0].message.content)) |
|
print("Content:", response.choices[0].message.content) |
|
'''''' |
|
answer = response.choices[0].message.content |
|
if isinstance(answer, str): |
|
answer = answer.strip() |
|
|
|
print(f"Final answer: {answer}") |
|
return answer |
|
except Exception as e: |
|
print(f"Error: {e}") |
|
return f"An error occurred: {e}" |
|
|
|
|
|
iface = gr.Interface( |
|
fn=chatbot, |
|
inputs="text", |
|
outputs="text", |
|
title="My Chatbot", |
|
description="Ask anything!" |
|
) |
|
|
|
|
|
iface.launch() |
|
|