File size: 6,402 Bytes
8161c55
b2548e5
8a4d350
809791b
1387ef8
7a09325
8161c55
 
 
b2548e5
 
 
 
 
 
 
 
 
 
 
 
 
48d9602
b2548e5
 
 
 
 
 
 
48d9602
b2548e5
 
 
48d9602
b2548e5
48d9602
 
b2548e5
48d9602
 
 
b2548e5
48d9602
1387ef8
48d9602
 
b2548e5
 
 
8161c55
 
b2548e5
8161c55
8a4d350
8161c55
 
b2548e5
7a09325
8161c55
b2548e5
 
8161c55
7a09325
b2548e5
 
8161c55
b2548e5
8a4d350
 
 
7a09325
 
 
 
8161c55
7a09325
 
 
8161c55
 
8a4d350
809791b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1387ef8
809791b
 
 
 
8161c55
b2548e5
8161c55
b2548e5
 
 
 
 
 
 
 
 
 
 
809791b
 
b2548e5
809791b
 
b2548e5
809791b
 
 
 
 
8a4d350
8161c55
7a09325
 
 
b2548e5
7a09325
b2548e5
 
 
 
 
 
 
 
 
 
 
7a09325
 
 
 
 
b2548e5
7a09325
 
 
b2548e5
c2139f1
 
b2548e5
c2139f1
b2548e5
 
 
 
 
c2139f1
 
 
b2548e5
 
 
 
 
7a09325
b2548e5
c2139f1
b2548e5
7a09325
 
 
b2548e5
 
 
7a09325
b2548e5
 
 
 
 
 
 
 
7a09325
809791b
b2548e5
809791b
b2548e5
 
809791b
2962f9a
 
8161c55
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import os
import re
import google.generativeai as genai
from flask import Flask, redirect, render_template, request
from user_data import get_user_history, user_histories
from logs import save_log

app = Flask(__name__)


# Função para configurar a chave de API
def genai_configuration():
    try:
        genai.configure(api_key=os.environ['GOOGLE_API_KEY'])

        # Testa se a chave principal está disponível
        test_model = genai.GenerativeModel("gemini-1.5-flash")
        test_model.start_chat().send_message("ping")

        return

    except Exception:
        print("⚠️  Falha com a chave principal, tentando chave reserva 1.")

        try:
            genai.configure(api_key=os.environ['GOOGLE_API_KEY_2'])

            # Testa se a chave reserva 1 está disponível
            test_model = genai.GenerativeModel("gemini-1.5-flash")
            test_model.start_chat().send_message("ping")

            return

        except Exception:
            print("⚠️  Falha com a chave reserva 1, tentando chave reserva 2.")

            try:
                genai.configure(api_key=os.environ['GOOGLE_API_KEY_3'])

                # Testa se a chave reserva 2 está disponível
                test_model = genai.GenerativeModel("gemini-1.5-flash")
                test_model.start_chat().send_message("ping")

                return

            except Exception:
                print("❌ Todas as chaves falharam.")


genai_configuration()

# Definir o modelo generativo com as funções disponíveis
magical_if = genai.GenerativeModel("gemini-1.5-flash")


def ia_decision(user_id, history):
    business_rules = """
    Analise o histórico de compras do usuário e recomende livros a ele.

    Regras:
    1. Se o usuário demonstrou interesse em ficção, recomende ficção.
    2. Se o usuário demonstrou interesse em não ficção, recomende não-ficção.
    3. Se o usuário demonstrou interesse em ciência, recomende ciência.
    4. Se o usuário demonstrou interesse em fantasia, recomende fantasia.
    5. Se o usuário não demonstrou interesse em nenhuma categoria, recomende
      os livros mais vendidos no último mês.
    """

    user_decision = magical_if.start_chat(
        enable_automatic_function_calling=True
    )

    message = (
        f"Histórico do usuário {user_id}: {history}\n"
        f"Regras de negócio:\n{business_rules}"
    )

    response = user_decision.send_message(message)

    return response.text


@app.route('/', methods=['GET', 'POST'])
def inicio():
    if request.method == 'POST':
        name = request.form.get('name')
        preferences = request.form.getlist('preferences')

        # Simula criação de novo ID
        new_id = max(user_histories.keys()) + 1
        user_histories[new_id] = {
            'fiction': 0,
            'non_fiction': 0,
            'science': 0,
            'fantasy': 0,
            'name': name,
            'preferences': preferences
        }

        return redirect(f'/chat/{new_id}')

    return render_template('start.html', profiles=user_histories)


@app.route('/perfil/<int:user_id>', methods=['GET', 'POST'])
def perfil(user_id):
    history = get_user_history(user_id)

    if not history:
        return '''
            <html>
            <head>
                <meta http-equiv="refresh" content="2;url=/">
            </head>
            <body>
                <h2>Ops, algo deu errado por aqui.</h2>
                <p>Vou te levar de volta para a página inicial.</p>
            </body>
            </html>
        '''

    if request.method == 'POST':

        name = request.form.get('name')
        preferences = request.form.getlist('preferences')

        # aqui vamos salvar nome e preferências
        history['name'] = name
        history['preferences'] = preferences

    return render_template('profile.html', user_id=user_id, history=history)


@app.route('/chat/<int:user_id>', methods=['GET', 'POST'])
def chat(user_id):
    history = get_user_history(user_id)

    if not history:
        return '''
            <html>
            <head>
                <meta http-equiv="refresh" content="2;url=/">
            </head>
            <body>
                <h2>Ops, algo deu errado por aqui.</h2>
                <p>Vou te levar de volta para a página inicial.</p>
            </body>
            </html>
        '''

    response = None

    if request.method == 'POST':
        question = request.form.get('question')

        user_decision = magical_if.start_chat(
            enable_automatic_function_calling=True
        )

        name = history.get("name", f"Usuário {user_id}")
        preferences = history.get("preferences", [])

        prompt = (
            f"Você é uma especialista em livros e pode conversar livremente "
            f"sobre obras literárias, personagens, enredos, gêneros e autores."
            f" O nome do usuário é {name} e seu ID é {user_id}. A informação "
            f"sobre o id é somente para você, não mencione nada sobre isso ao "
            f"usuário. As preferências dele são: "
            f"{', '.join(preferences) or 'nenhuma preferência registrada'}. "
            f"Histórico de compras: {history}. "
            f"Pergunta: {question}"
            f"Responda na mesma língua em que foi feita a pergunta."
            f"Sempre fale com o usuário se dirigindo diretamente a ele, "
            f"não se refira a ele em terceira pessoa, como se estivesse "
            f"falando de outra pessoa."
            f" Dê respostas com no máximo 500 caracteres."
        )

        gemini_response = user_decision.send_message(prompt)
        response = gemini_response.text

        save_log(user_id, history, response)

    formatted_response = None
    if response:
        formatted_response = response.replace('\n', '<br>')

        formatted_response = re.sub(
            r'(?<=<br>)\s*(Ficção|Não[- ]Ficção|Ciência|Fantasia)\s*:(?=<br>)',
            r'<b>\1:</b>',
            f"<br>{formatted_response}<br>"
        )[4:-4]

        formatted_response = formatted_response.replace('**', '')
        formatted_response = formatted_response.replace('* ', '• ')

    return render_template(
        'chat.html',
        user_id=user_id,
        response=formatted_response,
        history=history
    )


if __name__ == '__main__':
    app.run(debug=True)