File size: 1,721 Bytes
8b87498
 
 
 
1243081
8b87498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
import os
import openai
import gradio as gr

# Retrieve and verify the OpenAI API key from the environment variable.
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}"

# Create the Gradio interface
iface = gr.Interface(
    fn=chatbot, 
    inputs="text", 
    outputs="text",
    title="My Chatbot",
    description="Ask anything!"
)

# Launch the interface
iface.launch()