Spaces:
Sleeping

oshul commited on
Commit
b7007e2
·
1 Parent(s): 5f28550
Files changed (3) hide show
  1. app/agent/nodes.py +43 -3
  2. app/main.py +7 -0
  3. app/routers/session.py +27 -2
app/agent/nodes.py CHANGED
@@ -1,6 +1,8 @@
1
  """LangGraph graph node implementations."""
2
 
3
  import json
 
 
4
  from langchain_core.messages import HumanMessage, SystemMessage
5
 
6
  from app.agent.state import AgentState
@@ -8,17 +10,41 @@ from app.agent import prompts
8
  from app.services.llm import get_llm
9
  from app.services.file_generator import file_generator
10
 
 
 
11
 
12
  def _parse_json_response(text: str) -> dict:
13
- """Parse JSON from LLM response, handling markdown code blocks."""
 
14
  text = text.strip()
 
15
  # Remove markdown code block markers if present
16
  if text.startswith("```"):
17
  lines = text.split("\n")
18
  # Remove first line (```json) and last line (```)
19
  lines = [l for l in lines if not l.strip().startswith("```")]
20
- text = "\n".join(lines)
21
- return json.loads(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
 
24
  # ============================================================
@@ -111,6 +137,18 @@ def analyze_round(state: AgentState) -> dict:
111
  if a["round_number"] == round_num
112
  ]
113
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  qa_text = ""
115
  for answer in current_round_answers:
116
  qa_text += (
@@ -128,7 +166,9 @@ def analyze_round(state: AgentState) -> dict:
128
  HumanMessage(content=prompt),
129
  ]
130
 
 
131
  response = llm.invoke(messages)
 
132
  parsed = _parse_json_response(response.content)
133
 
134
  new_summaries = list(state["round_summaries"]) + [parsed["summary"]]
 
1
  """LangGraph graph node implementations."""
2
 
3
  import json
4
+ import logging
5
+ import re
6
  from langchain_core.messages import HumanMessage, SystemMessage
7
 
8
  from app.agent.state import AgentState
 
10
  from app.services.llm import get_llm
11
  from app.services.file_generator import file_generator
12
 
13
+ logger = logging.getLogger(__name__)
14
+
15
 
16
  def _parse_json_response(text: str) -> dict:
17
+ """Parse JSON from LLM response, handling markdown code blocks and quirks."""
18
+ raw = text
19
  text = text.strip()
20
+
21
  # Remove markdown code block markers if present
22
  if text.startswith("```"):
23
  lines = text.split("\n")
24
  # Remove first line (```json) and last line (```)
25
  lines = [l for l in lines if not l.strip().startswith("```")]
26
+ text = "\n".join(lines).strip()
27
+
28
+ # Try direct parse first
29
+ try:
30
+ return json.loads(text)
31
+ except json.JSONDecodeError:
32
+ pass
33
+
34
+ # Try to extract JSON object via regex (handles trailing text, etc.)
35
+ match = re.search(r'\{[\s\S]*\}', text)
36
+ if match:
37
+ try:
38
+ return json.loads(match.group())
39
+ except json.JSONDecodeError:
40
+ pass
41
+
42
+ # Nothing worked — raise with details
43
+ preview = raw[:500] if len(raw) > 500 else raw
44
+ raise ValueError(
45
+ f"LLM returned non-JSON response. Preview: {preview}"
46
+ )
47
+
48
 
49
 
50
  # ============================================================
 
137
  if a["round_number"] == round_num
138
  ]
139
 
140
+ logger.info(
141
+ "analyze_round: round=%d, total_answers=%d, current_round_answers=%d",
142
+ round_num, len(state["all_answers"]), len(current_round_answers),
143
+ )
144
+
145
+ if not current_round_answers:
146
+ logger.warning(
147
+ "No answers found for round %d. All answers round_numbers: %s",
148
+ round_num,
149
+ [a.get("round_number") for a in state["all_answers"]],
150
+ )
151
+
152
  qa_text = ""
153
  for answer in current_round_answers:
154
  qa_text += (
 
166
  HumanMessage(content=prompt),
167
  ]
168
 
169
+ logger.info("Calling LLM for analyze_round (round %d)...", round_num)
170
  response = llm.invoke(messages)
171
+ logger.debug("LLM response for analyze_round: %s", response.content[:500])
172
  parsed = _parse_json_response(response.content)
173
 
174
  new_summaries = list(state["round_summaries"]) + [parsed["summary"]]
app/main.py CHANGED
@@ -1,5 +1,6 @@
1
  """FastAPI application entry point."""
2
 
 
3
  from contextlib import asynccontextmanager
4
  from fastapi import FastAPI
5
  from fastapi.middleware.cors import CORSMiddleware
@@ -8,6 +9,12 @@ from app.config import get_settings
8
  from app.services.transcription import transcription_service
9
  from app.routers import health, session
10
 
 
 
 
 
 
 
11
 
12
  @asynccontextmanager
13
  async def lifespan(app: FastAPI):
 
1
  """FastAPI application entry point."""
2
 
3
+ import logging
4
  from contextlib import asynccontextmanager
5
  from fastapi import FastAPI
6
  from fastapi.middleware.cors import CORSMiddleware
 
9
  from app.services.transcription import transcription_service
10
  from app.routers import health, session
11
 
12
+ # Configure logging
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
16
+ )
17
+
18
 
19
  @asynccontextmanager
20
  async def lifespan(app: FastAPI):
app/routers/session.py CHANGED
@@ -1,12 +1,16 @@
1
  """Session API endpoints."""
2
 
 
3
  import time
 
4
  from typing import Annotated
5
 
6
  from fastapi import APIRouter, HTTPException, UploadFile, File, Form
7
  from fastapi.responses import StreamingResponse
8
  import io
9
 
 
 
10
  from app.models.session import (
11
  SessionData,
12
  StartResponse,
@@ -58,7 +62,17 @@ async def start_session():
58
 
59
  # Build agent state and invoke question generation graph
60
  agent_state = _session_to_agent_state(session)
61
- result = generate_questions_graph.invoke(agent_state)
 
 
 
 
 
 
 
 
 
 
62
 
63
  # Update session with generated questions
64
  session.current_questions = [
@@ -134,7 +148,18 @@ async def submit_round(
134
 
135
  # Build agent state and invoke process round graph
136
  agent_state = _session_to_agent_state(session)
137
- result = process_round_graph.invoke(agent_state)
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  # Update session from result
140
  session.round_summaries = result.get("round_summaries", session.round_summaries)
 
1
  """Session API endpoints."""
2
 
3
+ import logging
4
  import time
5
+ import traceback
6
  from typing import Annotated
7
 
8
  from fastapi import APIRouter, HTTPException, UploadFile, File, Form
9
  from fastapi.responses import StreamingResponse
10
  import io
11
 
12
+ logger = logging.getLogger(__name__)
13
+
14
  from app.models.session import (
15
  SessionData,
16
  StartResponse,
 
62
 
63
  # Build agent state and invoke question generation graph
64
  agent_state = _session_to_agent_state(session)
65
+ try:
66
+ result = generate_questions_graph.invoke(agent_state)
67
+ except Exception as e:
68
+ logger.error(
69
+ "Failed to generate initial questions for session %s: %s\n%s",
70
+ session.session_id, str(e), traceback.format_exc(),
71
+ )
72
+ raise HTTPException(
73
+ status_code=500,
74
+ detail=f"Ошибка генерации вопросов: {str(e)}",
75
+ )
76
 
77
  # Update session with generated questions
78
  session.current_questions = [
 
148
 
149
  # Build agent state and invoke process round graph
150
  agent_state = _session_to_agent_state(session)
151
+ try:
152
+ result = process_round_graph.invoke(agent_state)
153
+ except Exception as e:
154
+ logger.error(
155
+ "Failed to process round %d for session %s: %s\n%s",
156
+ session.current_round, session_id, str(e),
157
+ traceback.format_exc(),
158
+ )
159
+ raise HTTPException(
160
+ status_code=500,
161
+ detail=f"Ошибка анализа ответов раунда {session.current_round}: {str(e)}",
162
+ )
163
 
164
  # Update session from result
165
  session.round_summaries = result.get("round_summaries", session.round_summaries)