File size: 2,348 Bytes
0266783
 
 
7d52a74
 
0266783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d52a74
 
 
 
 
 
 
 
 
 
 
 
 
0266783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cd9915
7d52a74
 
 
 
 
 
 
 
 
 
 
 
 
 
0266783
7d52a74
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import os
import random
import time
import requests
from PIL import Image

import openai
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

openai.api_key = os.getenv('OPENAI_API_KEY')

def chat_completion(messages: list) -> str:
    try:
        completion = openai.ChatCompletion.create(
            model='gpt-3.5-turbo',
            messages=messages
        )
        return completion['choices'][0]['message']['content']
    except:
        return 'We are facing a technical issue at this moment.'

def dalle_image_generation(prompt: str) -> Image.Image:
    try:
        response = openai.Image.create(
            model="image-alpha-001",  # Replace with the appropriate DALL-E model name
            prompt=prompt
        )
        image_url = response['url']
        image_data = requests.get(image_url).content
        image = Image.open(io.BytesIO(image_data))
        return image
    except:
        return None

def generate_messages(messages: list, query: str) -> list:
    formated_messages = [
        {
            'role': 'system',
            'content': 'You are a helpful Network Design assistant.'
        }
    ]
    for m in messages:
        formated_messages.append({
            'role': 'user',
            'content': m[0]
        })
        formated_messages.append({
            'role': 'assistant',
            'content': m[1]
        })
    formated_messages.append(
        {
            'role': 'user',
            'content': query
        }
    )
    return formated_messages

def generate_response(query: str, chat_history: list) -> tuple:
    messages = generate_messages(chat_history, query)
    bot_message = chat_completion(messages)

    # Check if the user wants an image
    if "generate image" in query.lower():
        # Assuming the user wants an image, generate an image using DALL-E
        image_generation_prompt = "Generate an image of " + query
        generated_image = dalle_image_generation(image_generation_prompt)

        if generated_image:
            # Do something with the generated image (e.g., save or display it)
            generated_image.show()
            # Save the image to a file
            generated_image.save('generated_image.jpg')

        time.sleep(random.randint(0, 5))

    chat_history.append((query, bot_message))
    return '', chat_history