ciyidogan commited on
Commit
b6cbef8
·
verified ·
1 Parent(s): 23e8d8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -13
app.py CHANGED
@@ -1,22 +1,158 @@
1
- from fastapi import FastAPI
2
- from controllers import chat_controller, test_controller, admin_controller, health_controller
3
- from core import service_config, session_store
4
  from log import log
5
- import os
6
- import warnings
 
 
 
 
 
 
7
 
8
- warnings.simplefilter(action='ignore', category=FutureWarning)
 
 
 
 
 
 
 
9
 
10
  app = FastAPI()
11
 
12
- app.include_router(health_controller.router)
13
- app.include_router(chat_controller.router)
14
- app.include_router(test_controller.router)
15
- app.include_router(admin_controller.router)
16
 
17
- log("🌐 Intent-service başlatılıyor...")
18
- service_config.load(is_reload=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  if __name__ == "__main__":
21
- import uvicorn
22
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, Request, Header
2
+ from fastapi.responses import JSONResponse
3
+ import threading
4
  from log import log
5
+ from service_config import ServiceConfig
6
+ from session import SessionStore
7
+ from prompt_engine import PromptEngine
8
+ from llm_connector import LLMConnector
9
+ from api_connector import APIConnector
10
+ from validation_engine import ValidationEngine
11
+ import traceback
12
+ import uvicorn
13
 
14
+ # Initialize core components
15
+ service_config = ServiceConfig()
16
+ service_config.load()
17
+ session_store = SessionStore()
18
+ prompt_engine = PromptEngine(service_config)
19
+ llm_connector = LLMConnector(service_config)
20
+ api_connector = APIConnector(service_config)
21
+ validation_engine = ValidationEngine()
22
 
23
  app = FastAPI()
24
 
 
 
 
 
25
 
26
+ @app.get("/")
27
+ def health_check():
28
+ return {"status": "ok"}
29
+
30
+
31
+ @app.post("/start_chat")
32
+ def start_chat(request: Request):
33
+ project_name = request.query_params.get("project_name")
34
+ if not project_name:
35
+ return {"error": "Missing project_name parameter."}
36
+
37
+ session = session_store.create_session(project_name)
38
+ return {"session_id": session.session_id}
39
+
40
+
41
+ @app.post("/chat")
42
+ async def chat(request: Request, x_session_id: str = Header(None)):
43
+ if not x_session_id:
44
+ return {"error": "Missing X-Session-ID header."}
45
+
46
+ session = session_store.get_session(x_session_id)
47
+ if not session:
48
+ return {"error": "Invalid or expired session."}
49
+
50
+ try:
51
+ body = await request.json()
52
+ user_input = body.get("user_input", "").strip()
53
+ if not user_input:
54
+ return {"error": "Empty user input."}
55
+
56
+ session.chat_history.append({"role": "user", "content": user_input})
57
+ project_name = session.project_name
58
+
59
+ if session.state == "intent_detection":
60
+ prompt = prompt_engine.build_intent_prompt(project_name)
61
+ llm_response = llm_connector.call_spark(project_name, prompt, session.chat_history)
62
+ if llm_response is None:
63
+ return {"error": "Failed to get intent detection result."}
64
+
65
+ intent = llm_response.get("intent")
66
+ params = llm_response.get("params", {})
67
+ missing = llm_response.get("missing", [])
68
+
69
+ session.last_intent = intent
70
+ session.variables.update(params)
71
+ session.awaiting_parameters = missing
72
+
73
+ if missing:
74
+ session.state = "parameter_extraction"
75
+ return {"response": f"Please provide: {', '.join(missing)}"}
76
+
77
+ session.state = "validation"
78
+
79
+ if session.state == "parameter_extraction":
80
+ prompt = prompt_engine.build_parameter_prompt(project_name, session.last_intent, session.awaiting_parameters)
81
+ llm_response = llm_connector.call_spark(project_name, prompt, session.chat_history)
82
+ if llm_response is None:
83
+ return {"error": "Failed to extract parameters."}
84
+
85
+ params = llm_response.get("params", {})
86
+ missing = llm_response.get("missing", [])
87
+
88
+ session.variables.update(params)
89
+ session.awaiting_parameters = missing
90
+
91
+ if missing:
92
+ return {"response": f"Please provide: {', '.join(missing)}"}
93
+
94
+ session.state = "validation"
95
+
96
+ if session.state == "validation":
97
+ intent_def = next((i for i in service_config.get_project_intents(project_name) if i["name"] == session.last_intent), None)
98
+ if not intent_def:
99
+ return {"error": f"Intent definition not found: {session.last_intent}"}
100
+
101
+ is_valid, errors = validation_engine.validate_parameters(intent_def, session.variables)
102
+ if not is_valid:
103
+ return {"response": " ".join(errors)}
104
+
105
+ session.state = "api_call"
106
+
107
+ if session.state == "api_call":
108
+ intent_def = next((i for i in service_config.get_project_intents(project_name) if i["name"] == session.last_intent), None)
109
+ api_response = api_connector.call_api(intent_def, session)
110
+ if "fallback" in api_response:
111
+ return {"response": api_response["fallback"]}
112
+
113
+ session.state = "humanization"
114
+ session.variables["api_result"] = api_response
115
+
116
+ if session.state == "humanization":
117
+ prompt = prompt_engine.build_humanization_prompt(project_name, session.last_intent)
118
+ chat_history = [{"role": "system", "content": str(session.variables["api_result"])}]
119
+ humanized_response = llm_connector.call_spark(project_name, prompt, chat_history)
120
+ if humanized_response is None:
121
+ return {"error": "Failed to humanize response."}
122
+
123
+ session.chat_history.append({"role": "assistant", "content": humanized_response.get("answer")})
124
+ session.state = "intent_detection" # reset state
125
+ session.last_intent = None
126
+ session.variables = {}
127
+ session.awaiting_parameters = []
128
+
129
+ return {"response": humanized_response.get("answer")}
130
+
131
+ except Exception as e:
132
+ log(f"❌ Error in chat: {e}")
133
+ traceback.print_exc()
134
+ return JSONResponse(content={"error": str(e)}, status_code=500)
135
+
136
+
137
+ @app.post("/reload_config")
138
+ def reload_config():
139
+ def background_reload():
140
+ try:
141
+ service_config.load()
142
+ log("✅ Service config reloaded successfully.")
143
+ except Exception as e:
144
+ log(f"❌ Error reloading config: {e}")
145
+
146
+ threading.Thread(target=background_reload, daemon=True).start()
147
+ return {"status": "accepted", "message": "Config reload started in background."}
148
+
149
+
150
+ @app.post("/run_tests")
151
+ def run_tests():
152
+ log("🚦 /run_tests endpoint called. (Test runner needs to be implemented.)")
153
+ return {"status": "not_implemented", "message": "Test runner is not yet implemented."}
154
+
155
 
156
  if __name__ == "__main__":
157
+ log("🌐 Starting Flare Intent Service...")
158
  uvicorn.run(app, host="0.0.0.0", port=7860)