FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
CodeHelperNET/backend/api_server.py at main · AndNikDev/CodeHelperNET · GitHub
AndNikDev
/
CodeHelperNET
Public
forked from
gaby0398/CodeHelperNET
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
CodeHelperNET
/
backend
/
api_server.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
254 lines (218 loc) · 7.55 KB
Breadcrumbs
CodeHelperNET
/
backend
/
api_server.py
Copy path
File metadata and controls
254 lines (218 loc) · 7.55 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/env python3
"""
Servidor API para CodeHelperNET con Ollama
Expone el chatbot RAG como una API REST
"""
from
flask
import
Flask
,
request
,
jsonify
from
flask_cors
import
CORS
import
sys
import
os
import
logging
from
datetime
import
datetime
from
dotenv
import
load_dotenv
import
requests
# Cargar variables de entorno
load_dotenv
(
'config.env'
)
# Agregar el directorio actual al path para importar módulos
sys
.
path
.
append
(
os
.
path
.
dirname
(
os
.
path
.
abspath
(
__file__
)))
# Importar el chatbot
from
rag_chatbot
import
RAGChatbot
# Configurar logging
logging
.
basicConfig
(
level
=
logging
.
INFO
)
logger
=
logging
.
getLogger
(
__name__
)
app
=
Flask
(
__name__
)
CORS
(
app
)
# Habilitar CORS para el frontend
# Inicializar el chatbot
chatbot
=
None
def
check_ollama_status
():
"""Verificar el estado de Ollama"""
try
:
response
=
requests
.
get
(
"http://localhost:11434/api/tags"
,
timeout
=
5
)
if
response
.
status_code
==
200
:
models
=
response
.
json
().
get
(
'models'
, [])
return
{
'status'
:
'running'
,
'models'
: [
model
[
'name'
]
for
model
in
models
],
'model_count'
:
len
(
models
)
}
else
:
return
{
'status'
:
'error'
,
'message'
:
f'HTTP
{
response
.
status_code
}
'
}
except
Exception
as
e
:
return
{
'status'
:
'error'
,
'message'
:
str
(
e
)}
def
initialize_chatbot
():
"""Inicializar el chatbot RAG"""
global
chatbot
try
:
logger
.
info
(
"Inicializando CodeHelperNET chatbot..."
)
chatbot
=
RAGChatbot
()
logger
.
info
(
"Chatbot inicializado exitosamente"
)
return
True
except
Exception
as
e
:
logger
.
error
(
f"Error inicializando chatbot:
{
e
}
"
)
return
False
@
app
.
route
(
'/health'
,
methods
=
[
'GET'
])
def
health_check
():
"""Endpoint de salud del servidor"""
ollama_status
=
check_ollama_status
()
return
jsonify
({
'status'
:
'healthy'
,
'timestamp'
:
datetime
.
now
().
isoformat
(),
'chatbot_ready'
:
chatbot
is
not
None
,
'ollama'
:
ollama_status
,
'version'
:
'2.0.0'
,
'backend'
:
'Ollama + RAG'
})
@
app
.
route
(
'/chat'
,
methods
=
[
'POST'
])
def
chat
():
"""Endpoint principal para el chat"""
try
:
# Verificar que el chatbot esté inicializado
if
chatbot
is
None
:
return
jsonify
({
'error'
:
'Chatbot no inicializado'
,
'message'
:
'El servidor está iniciando, por favor espera un momento.'
}),
503
# Obtener el mensaje del request
data
=
request
.
get_json
()
if
not
data
or
'message'
not
in
data
:
return
jsonify
({
'error'
:
'Mensaje requerido'
,
'message'
:
'Debes enviar un mensaje en el campo "message"'
}),
400
user_message
=
data
[
'message'
].
strip
()
if
not
user_message
:
return
jsonify
({
'error'
:
'Mensaje vacío'
,
'message'
:
'El mensaje no puede estar vacío'
}),
400
logger
.
info
(
f"Mensaje recibido:
{
user_message
[:
100
]
}
..."
)
# Procesar el mensaje con el chatbot
response
=
chatbot
.
chat
(
user_message
)
logger
.
info
(
f"Respuesta generada:
{
len
(
response
)
}
caracteres"
)
return
jsonify
({
'response'
:
response
,
'timestamp'
:
datetime
.
now
().
isoformat
(),
'backend'
:
'Ollama + RAG'
})
except
Exception
as
e
:
logger
.
error
(
f"Error procesando mensaje:
{
e
}
"
)
return
jsonify
({
'error'
:
'Error interno del servidor'
,
'message'
:
'Ocurrió un error procesando tu mensaje. Por favor, intenta de nuevo.'
,
'details'
:
str
(
e
)
}),
500
@
app
.
route
(
'/ollama/status'
,
methods
=
[
'GET'
])
def
ollama_status
():
"""Endpoint para verificar el estado de Ollama"""
status
=
check_ollama_status
()
return
jsonify
(
status
)
@
app
.
route
(
'/ollama/models'
,
methods
=
[
'GET'
])
def
ollama_models
():
"""Endpoint para listar modelos disponibles"""
try
:
response
=
requests
.
get
(
"http://localhost:11434/api/tags"
,
timeout
=
5
)
if
response
.
status_code
==
200
:
models
=
response
.
json
().
get
(
'models'
, [])
return
jsonify
({
'models'
:
models
,
'count'
:
len
(
models
)
})
else
:
return
jsonify
({
'error'
:
'No se pudo obtener la lista de modelos'
,
'status_code'
:
response
.
status_code
}),
500
except
Exception
as
e
:
return
jsonify
({
'error'
:
'Error conectando con Ollama'
,
'message'
:
str
(
e
)
}),
500
@
app
.
route
(
'/info'
,
methods
=
[
'GET'
])
def
get_info
():
"""Endpoint para obtener información del chatbot"""
if
chatbot
is
None
:
return
jsonify
({
'error'
:
'Chatbot no inicializado'
}),
503
ollama_status
=
check_ollama_status
()
return
jsonify
({
'name'
:
'CodeHelperNET'
,
'description'
:
'Asistente especializado en C# y .NET con Ollama'
,
'version'
:
'2.0.0'
,
'backend'
:
'Ollama + RAG'
,
'ollama_status'
:
ollama_status
,
'topics'
: [
'C# Fundamentals'
,
'ASP.NET Core'
,
'Entity Framework'
,
'Design Patterns'
,
'Testing'
,
'Security'
,
'Performance'
,
'Cloud Development'
,
'Microservices'
,
'DevOps'
],
'documents_count'
:
len
(
chatbot
.
collection
.
get
()[
'documents'
])
if
hasattr
(
chatbot
,
'collection'
)
else
0
})
@
app
.
route
(
'/test'
,
methods
=
[
'POST'
])
def
test_chat
():
"""Endpoint de prueba para verificar el funcionamiento"""
try
:
test_message
=
"¿Cómo crear un bucle for en C#?"
logger
.
info
(
"Ejecutando prueba con mensaje de ejemplo..."
)
if
chatbot
is
None
:
return
jsonify
({
'error'
:
'Chatbot no inicializado'
}),
503
response
=
chatbot
.
chat
(
test_message
)
return
jsonify
({
'test_message'
:
test_message
,
'response'
:
response
,
'response_length'
:
len
(
response
),
'success'
:
True
,
'timestamp'
:
datetime
.
now
().
isoformat
()
})
except
Exception
as
e
:
logger
.
error
(
f"Error en prueba:
{
e
}
"
)
return
jsonify
({
'error'
:
'Error en prueba'
,
'message'
:
str
(
e
),
'success'
:
False
}),
500
@
app
.
errorhandler
(
404
)
def
not_found
(
error
):
"""Manejar rutas no encontradas"""
return
jsonify
({
'error'
:
'Endpoint no encontrado'
,
'message'
:
'La ruta solicitada no existe'
}),
404
@
app
.
errorhandler
(
500
)
def
internal_error
(
error
):
"""Manejar errores internos"""
return
jsonify
({
'error'
:
'Error interno del servidor'
,
'message'
:
'Ocurrió un error inesperado'
}),
500
if
__name__
==
'__main__'
:
# Inicializar el chatbot al arrancar
if
not
initialize_chatbot
():
logger
.
error
(
"No se pudo inicializar el chatbot. Saliendo..."
)
sys
.
exit
(
1
)
# Verificar Ollama
ollama_status
=
check_ollama_status
()
if
ollama_status
[
'status'
]
==
'running'
:
logger
.
info
(
f"Ollama está ejecutándose con
{
ollama_status
[
'model_count'
]
}
modelos"
)
else
:
logger
.
warning
(
f"Ollama no está disponible:
{
ollama_status
[
'message'
]
}
"
)
# Configurar el servidor
port
=
int
(
os
.
environ
.
get
(
'PORT'
,
5000
))
debug
=
os
.
environ
.
get
(
'FLASK_ENV'
)
==
'development'
logger
.
info
(
f"Iniciando servidor en puerto
{
port
}
"
)
logger
.
info
(
f"Modo debug:
{
debug
}
"
)
app
.
run
(
host
=
'0.0.0.0'
,
port
=
port
,
debug
=
debug
,
threaded
=
True
)
Back
|
FazBrowse Home
|
New Git URL