pyinterviewbot-ai 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyinterviewbot-ai
3
+ Version: 0.1.0
4
+ Summary: Local ASR/LLM/TTS + evidence-engine orchestration service for PyInterviewBot
5
+ Author: Georgi Mammen Mullassery
6
+ Author-email: Georgi Mammen Mullassery <mullassery@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: aiosqlite>=0.22.1
10
+ Requires-Dist: fastapi>=0.141.1
11
+ Requires-Dist: faster-whisper>=1.2.1
12
+ Requires-Dist: ollama>=0.6.2
13
+ Requires-Dist: piper-tts>=1.8.0
14
+ Requires-Dist: pydantic>=2.13.5
15
+ Requires-Dist: python-multipart>=0.0.32
16
+ Requires-Dist: uvicorn[standard]>=0.53.0
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+
20
+ # pyinterviewbot-ai
21
+
22
+ The ASR/LLM/TTS orchestration + evidence-engine service for
23
+ [PyInterviewBot](../README.md). See the root README for setup/run
24
+ instructions and [`../docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md) for
25
+ the design.
@@ -0,0 +1,6 @@
1
+ # pyinterviewbot-ai
2
+
3
+ The ASR/LLM/TTS orchestration + evidence-engine service for
4
+ [PyInterviewBot](../README.md). See the root README for setup/run
5
+ instructions and [`../docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md) for
6
+ the design.
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "pyinterviewbot-ai"
3
+ version = "0.1.0"
4
+ description = "Local ASR/LLM/TTS + evidence-engine orchestration service for PyInterviewBot"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Georgi Mammen Mullassery", email = "mullassery@gmail.com" }
10
+ ]
11
+ requires-python = ">=3.11"
12
+ dependencies = [
13
+ "aiosqlite>=0.22.1",
14
+ "fastapi>=0.141.1",
15
+ "faster-whisper>=1.2.1",
16
+ "ollama>=0.6.2",
17
+ "piper-tts>=1.8.0",
18
+ "pydantic>=2.13.5",
19
+ "python-multipart>=0.0.32",
20
+ "uvicorn[standard]>=0.53.0",
21
+ ]
22
+
23
+ [project.scripts]
24
+ pyinterviewbot-ai = "pyinterviewbot_ai.main:main"
25
+
26
+ [build-system]
27
+ requires = ["uv_build>=0.11.32,<0.12.0"]
28
+ build-backend = "uv_build"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "httpx>=0.28.1",
33
+ "pytest>=9.1.1",
34
+ "pytest-asyncio>=1.4.0",
35
+ "websockets>=17.1",
36
+ ]
@@ -0,0 +1,152 @@
1
+ """The interview agent: adaptive question generation + evidence extraction
2
+ (spec §13/§14/§30). One LLM call per turn produces both — the gateway only
3
+ ever sees the resulting question text and a completion flag; everything
4
+ else here stays server-side.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from uuid import UUID, uuid4
11
+
12
+ from . import db, llm
13
+ from .evidence import EvidenceGraphState
14
+ from .models import TurnResponse
15
+ from .resume import seed_claim
16
+
17
+ MAX_TURNS = int(os.environ.get("PYINTERVIEWBOT_MAX_TURNS", "6"))
18
+
19
+ FALLBACK_CLOSING_REMARK = (
20
+ "That's a great place to stop — thank you for walking me through all of that in such detail."
21
+ )
22
+
23
+ SYSTEM_PROMPT = """You are a senior technical interviewer conducting a live spoken interview.
24
+ Your tone is professional, calm, intelligent, neutral, and conversational — never a checklist,
25
+ never a quiz show. The candidate cannot see anything you're thinking; they only hear what you say.
26
+
27
+ You are assessing exactly one competency right now: RAG (Retrieval-Augmented Generation)
28
+ Architecture, grounded in a specific claim from the candidate's resume. Your job is to listen,
29
+ understand, and adaptively probe until you have real evidence — not to work through a fixed
30
+ script.
31
+
32
+ Evidence nodes for this competency (do not mention these names or ids to the candidate):
33
+ - retrieval_design: how retrieval is designed — what's fetched vs. handled directly by the model
34
+ - relevance_handling: what happens when retrieval returns irrelevant or low-quality documents
35
+ - production_scaling: how the system behaves and is investigated under a large traffic/latency increase
36
+
37
+ Rules:
38
+ 1. Ask exactly ONE natural question or statement per turn.
39
+ 2. Never reveal scores, evidence status, confidence, or your internal reasoning to the candidate.
40
+ 3. Ground every question in what the candidate actually just said — reference specifics.
41
+ 4. Choose a follow-up strategy that fits what's missing: clarification ("when you say X, roughly
42
+ what scale?"), ownership ("what part did you personally build?"), technical depth ("how did you
43
+ handle Y?"), trade-off ("why that approach over the alternative?"), production ("what happened
44
+ once this was live?"), failure ("what was the most serious failure?"), evidence ("walk me
45
+ through a specific example"), or challenge ("what if load increased tenfold?").
46
+ 5. Do not penalize the candidate for topics outside this competency. Only probe RAG architecture.
47
+ 6. Once retrieval_design and relevance_handling both have real evidence, transition to
48
+ production_scaling by posing it as a hypothetical scenario (e.g. "Let's shift into a scenario:
49
+ traffic just increased twenty-fold and latency has spiked. Walk me through what you'd
50
+ investigate first."), not a plain question.
51
+ 7. Once all three nodes have real evidence (not "not_addressed"), wrap up warmly in one or two
52
+ sentences, thank them, and set is_complete to true. Do not ask a further question in that turn.
53
+ 8. Always fill in evidence_updates for any node the candidate's last answer gave you signal on,
54
+ using status: "confirmed" (clear, specific, credible), "weak" (vague/generic/hand-wavy),
55
+ "contradicted" (conflicts with something said earlier), or leave a node out of
56
+ evidence_updates entirely if this turn didn't touch it.
57
+
58
+ Respond only with the structured JSON you've been constrained to produce."""
59
+
60
+
61
+ def _opening_prompt(claim_text: str) -> str:
62
+ return (
63
+ f'The candidate\'s resume includes this claim: "{claim_text}"\n\n'
64
+ "This is the very first turn. Open the interview by warmly referencing this claim and "
65
+ "asking them to walk you through the architecture. Leave evidence_updates empty and "
66
+ "is_complete false."
67
+ )
68
+
69
+
70
+ def _turn_prompt(
71
+ claim_text: str,
72
+ graph: EvidenceGraphState,
73
+ history: list[tuple[str, str]],
74
+ latest_answer: str,
75
+ force_conclude: bool,
76
+ ) -> str:
77
+ transcript = "\n".join(f"{'Interviewer' if s == 'ai' else 'Candidate'}: {t}" for s, t in history)
78
+ closing_instruction = (
79
+ "\n\nThis is the FINAL turn regardless of evidence coverage — the interview time is up. "
80
+ "question_text must NOT be a question — it must be 1-2 warm closing sentences thanking the "
81
+ "candidate and telling them the interview is complete. question_text must not be empty. "
82
+ "Set is_complete to true."
83
+ if force_conclude
84
+ else ""
85
+ )
86
+ return (
87
+ f'Resume claim under discussion: "{claim_text}"\n\n'
88
+ f"Evidence gathered so far:\n{graph.summary_for_prompt()}\n\n"
89
+ f"Conversation so far:\n{transcript}\n\n"
90
+ f"Candidate's latest answer: \"{latest_answer}\"\n\n"
91
+ "Decide evidence_updates from that answer, then produce your next question per the rules."
92
+ f"{closing_instruction}"
93
+ )
94
+
95
+
96
+ async def _load_graph(session_id: UUID) -> EvidenceGraphState:
97
+ graph = EvidenceGraphState()
98
+ for record in await db.get_evidence(session_id):
99
+ graph.apply(record.node, record.status, record.note)
100
+ return graph
101
+
102
+
103
+ async def start_session() -> tuple[UUID, str]:
104
+ session_id = uuid4()
105
+ claim = seed_claim()
106
+ await db.create_session(session_id, claim)
107
+
108
+ decision = await llm.decide_turn(SYSTEM_PROMPT, _opening_prompt(claim.text))
109
+
110
+ await db.append_transcript(session_id, 0, "ai", decision.question_text)
111
+ await db.set_turn_count(session_id, 0)
112
+
113
+ return session_id, decision.question_text
114
+
115
+
116
+ async def take_turn(session_id: UUID, transcript: str) -> TurnResponse:
117
+ row = await db.get_session_row(session_id)
118
+ if row is None:
119
+ raise ValueError(f"unknown session {session_id}")
120
+
121
+ turn_number = row["turn_count"] + 1
122
+ claim_text = row["resume_claim"]
123
+
124
+ await db.append_transcript(session_id, turn_number, "candidate", transcript)
125
+
126
+ graph = await _load_graph(session_id)
127
+ history = [(s.speaker, s.text) for s in await db.get_transcript(session_id) if s.turn_number < turn_number]
128
+
129
+ force_conclude = turn_number >= MAX_TURNS
130
+ decision = await llm.decide_turn(
131
+ SYSTEM_PROMPT, _turn_prompt(claim_text, graph, history, transcript, force_conclude)
132
+ )
133
+
134
+ for update in decision.evidence_updates:
135
+ graph.apply(update.node, update.status, update.note)
136
+ await db.record_evidence(session_id, update.node, update.status, update.note, turn_number)
137
+
138
+ is_complete = decision.is_complete or force_conclude
139
+ ai_text = decision.question_text.strip()
140
+ if not ai_text:
141
+ # Defensive fallback, same spirit as the gateway's ASR-failure
142
+ # fallback (spec §28) — the primary path is always real LLM output;
143
+ # this only fires if the model returns nothing for the closing turn.
144
+ ai_text = FALLBACK_CLOSING_REMARK if is_complete else "Could you tell me a bit more about that?"
145
+
146
+ await db.append_transcript(session_id, turn_number, "ai", ai_text)
147
+ await db.set_turn_count(session_id, turn_number)
148
+
149
+ if is_complete:
150
+ await db.mark_complete(session_id)
151
+
152
+ return TurnResponse(ai_text=ai_text, is_complete=is_complete)
@@ -0,0 +1,47 @@
1
+ """ASR provider (spec §31): local faster-whisper. Per-turn transcription of
2
+ a complete VAD-delimited utterance — not token-level streaming partials.
3
+ See docs/ARCHITECTURE.md for why that's an intentional MVP simplification
4
+ of the §11/§27 streaming pipeline (faster-whisper has no native incremental
5
+ decode mode; a real streaming-partials setup would periodically re-decode a
6
+ growing buffer, which added complexity this slice skips since nothing
7
+ candidate-facing depends on partial transcripts anyway).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import os
14
+
15
+ import numpy as np
16
+ from faster_whisper import WhisperModel
17
+
18
+ MODEL_SIZE = os.environ.get("WHISPER_MODEL", "small.en")
19
+ DEVICE = os.environ.get("WHISPER_DEVICE", "cpu")
20
+ COMPUTE_TYPE = os.environ.get("WHISPER_COMPUTE_TYPE", "int8")
21
+
22
+ _model: WhisperModel | None = None
23
+
24
+
25
+ def _get_model() -> WhisperModel:
26
+ global _model
27
+ if _model is None:
28
+ _model = WhisperModel(MODEL_SIZE, device=DEVICE, compute_type=COMPUTE_TYPE)
29
+ return _model
30
+
31
+
32
+ def _pcm16_bytes_to_float32(pcm16: bytes) -> np.ndarray:
33
+ samples = np.frombuffer(pcm16, dtype="<i2")
34
+ return samples.astype(np.float32) / 32768.0
35
+
36
+
37
+ def _transcribe_sync(pcm16_16khz: bytes) -> str:
38
+ audio = _pcm16_bytes_to_float32(pcm16_16khz)
39
+ if audio.size == 0:
40
+ return ""
41
+ segments, _info = _get_model().transcribe(audio, language="en", vad_filter=False)
42
+ return " ".join(segment.text.strip() for segment in segments).strip()
43
+
44
+
45
+ async def transcribe(pcm16_16khz: bytes) -> str:
46
+ # faster-whisper is synchronous/CPU-bound; keep it off the event loop.
47
+ return await asyncio.to_thread(_transcribe_sync, pcm16_16khz)
@@ -0,0 +1,173 @@
1
+ """SQLite persistence — the system of record for interview domain data
2
+ (spec §34: state must not live only inside the LLM context). One file per
3
+ deployment; path configurable via PYINTERVIEWBOT_DB_PATH.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from contextlib import asynccontextmanager
10
+ from datetime import datetime, timezone
11
+ from uuid import UUID
12
+
13
+ import aiosqlite
14
+
15
+ from .evidence import COMPETENCY
16
+ from .models import EvidenceRecord, EvidenceStatus, SessionListItem, TranscriptSegment
17
+ from .resume import ResumeClaim
18
+
19
+ DB_PATH = os.environ.get("PYINTERVIEWBOT_DB_PATH", "data/pyinterviewbot.db")
20
+
21
+ SCHEMA = """
22
+ CREATE TABLE IF NOT EXISTS sessions (
23
+ id TEXT PRIMARY KEY,
24
+ created_at TEXT NOT NULL,
25
+ resume_claim TEXT NOT NULL,
26
+ turn_count INTEGER NOT NULL DEFAULT 0,
27
+ is_complete INTEGER NOT NULL DEFAULT 0
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS transcript_segments (
31
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
32
+ session_id TEXT NOT NULL REFERENCES sessions(id),
33
+ turn_number INTEGER NOT NULL,
34
+ speaker TEXT NOT NULL,
35
+ text TEXT NOT NULL,
36
+ created_at TEXT NOT NULL
37
+ );
38
+
39
+ CREATE TABLE IF NOT EXISTS evidence (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ session_id TEXT NOT NULL REFERENCES sessions(id),
42
+ competency TEXT NOT NULL,
43
+ node TEXT NOT NULL,
44
+ status TEXT NOT NULL,
45
+ note TEXT NOT NULL,
46
+ turn_number INTEGER NOT NULL,
47
+ created_at TEXT NOT NULL
48
+ );
49
+ """
50
+
51
+
52
+ async def init_db() -> None:
53
+ os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
54
+ async with aiosqlite.connect(DB_PATH) as db:
55
+ await db.executescript(SCHEMA)
56
+ await db.commit()
57
+
58
+
59
+ @asynccontextmanager
60
+ async def connect():
61
+ db = await aiosqlite.connect(DB_PATH)
62
+ try:
63
+ yield db
64
+ finally:
65
+ await db.close()
66
+
67
+
68
+ def _now() -> str:
69
+ return datetime.now(timezone.utc).isoformat()
70
+
71
+
72
+ async def create_session(session_id: UUID, claim: ResumeClaim) -> None:
73
+ async with connect() as db:
74
+ await db.execute(
75
+ "INSERT INTO sessions (id, created_at, resume_claim) VALUES (?, ?, ?)",
76
+ (str(session_id), _now(), claim.text),
77
+ )
78
+ await db.commit()
79
+
80
+
81
+ async def append_transcript(session_id: UUID, turn_number: int, speaker: str, text: str) -> None:
82
+ async with connect() as db:
83
+ await db.execute(
84
+ "INSERT INTO transcript_segments (session_id, turn_number, speaker, text, created_at) "
85
+ "VALUES (?, ?, ?, ?, ?)",
86
+ (str(session_id), turn_number, speaker, text, _now()),
87
+ )
88
+ await db.commit()
89
+
90
+
91
+ async def record_evidence(session_id: UUID, node: str, status: EvidenceStatus, note: str, turn_number: int) -> None:
92
+ async with connect() as db:
93
+ await db.execute(
94
+ "INSERT INTO evidence (session_id, competency, node, status, note, turn_number, created_at) "
95
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
96
+ (str(session_id), COMPETENCY, node, status, note, turn_number, _now()),
97
+ )
98
+ await db.commit()
99
+
100
+
101
+ async def set_turn_count(session_id: UUID, turn_count: int) -> None:
102
+ async with connect() as db:
103
+ await db.execute(
104
+ "UPDATE sessions SET turn_count = ? WHERE id = ?",
105
+ (turn_count, str(session_id)),
106
+ )
107
+ await db.commit()
108
+
109
+
110
+ async def mark_complete(session_id: UUID) -> None:
111
+ async with connect() as db:
112
+ await db.execute("UPDATE sessions SET is_complete = 1 WHERE id = ?", (str(session_id),))
113
+ await db.commit()
114
+
115
+
116
+ async def list_sessions() -> list[SessionListItem]:
117
+ async with connect() as db:
118
+ db.row_factory = aiosqlite.Row
119
+ cursor = await db.execute(
120
+ "SELECT id, created_at, resume_claim, is_complete, turn_count FROM sessions "
121
+ "ORDER BY created_at DESC LIMIT 50"
122
+ )
123
+ rows = await cursor.fetchall()
124
+ return [
125
+ SessionListItem(
126
+ session_id=r["id"],
127
+ created_at=r["created_at"],
128
+ resume_claim=r["resume_claim"],
129
+ is_complete=bool(r["is_complete"]),
130
+ turn_count=r["turn_count"],
131
+ )
132
+ for r in rows
133
+ ]
134
+
135
+
136
+ async def get_session_row(session_id: UUID) -> aiosqlite.Row | None:
137
+ async with connect() as db:
138
+ db.row_factory = aiosqlite.Row
139
+ cursor = await db.execute("SELECT * FROM sessions WHERE id = ?", (str(session_id),))
140
+ return await cursor.fetchone()
141
+
142
+
143
+ async def get_transcript(session_id: UUID) -> list[TranscriptSegment]:
144
+ async with connect() as db:
145
+ db.row_factory = aiosqlite.Row
146
+ cursor = await db.execute(
147
+ "SELECT turn_number, speaker, text FROM transcript_segments "
148
+ "WHERE session_id = ? ORDER BY id ASC",
149
+ (str(session_id),),
150
+ )
151
+ rows = await cursor.fetchall()
152
+ return [TranscriptSegment(turn_number=r["turn_number"], speaker=r["speaker"], text=r["text"]) for r in rows]
153
+
154
+
155
+ async def get_evidence(session_id: UUID) -> list[EvidenceRecord]:
156
+ async with connect() as db:
157
+ db.row_factory = aiosqlite.Row
158
+ cursor = await db.execute(
159
+ "SELECT competency, node, status, note, turn_number FROM evidence "
160
+ "WHERE session_id = ? ORDER BY id ASC",
161
+ (str(session_id),),
162
+ )
163
+ rows = await cursor.fetchall()
164
+ return [
165
+ EvidenceRecord(
166
+ competency=r["competency"],
167
+ node=r["node"],
168
+ status=r["status"],
169
+ note=r["note"],
170
+ turn_number=r["turn_number"],
171
+ )
172
+ for r in rows
173
+ ]
@@ -0,0 +1,48 @@
1
+ """The competency/evidence graph (spec §21) for this slice's one demo
2
+ competency: RAG Architecture. A production system would load this from a
3
+ job-description-driven competency library; here it's a fixed definition
4
+ matching the §36 demo scenario exactly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+ from .models import EvidenceStatus
12
+
13
+ COMPETENCY = "rag_architecture"
14
+
15
+ NODES: dict[str, str] = {
16
+ "retrieval_design": "How retrieval is designed — what's fetched vs. handled directly by the model",
17
+ "relevance_handling": "What happens when retrieval returns irrelevant or low-quality documents",
18
+ "production_scaling": "How the system behaves and is investigated under a large traffic/latency increase",
19
+ }
20
+
21
+
22
+ @dataclass
23
+ class NodeState:
24
+ status: EvidenceStatus = "not_addressed"
25
+ note: str = ""
26
+
27
+
28
+ @dataclass
29
+ class EvidenceGraphState:
30
+ nodes: dict[str, NodeState] = field(default_factory=lambda: {n: NodeState() for n in NODES})
31
+
32
+ def apply(self, node: str, status: EvidenceStatus, note: str) -> None:
33
+ if node not in self.nodes:
34
+ # The LLM invented a node id we don't track — ignore rather than
35
+ # crash the turn; the raw note is still visible in the transcript.
36
+ return
37
+ self.nodes[node] = NodeState(status=status, note=note)
38
+
39
+ def sufficiently_covered(self) -> bool:
40
+ addressed = [n for n in self.nodes.values() if n.status != "not_addressed"]
41
+ return len(addressed) == len(self.nodes)
42
+
43
+ def summary_for_prompt(self) -> str:
44
+ lines = []
45
+ for node_id, description in NODES.items():
46
+ state = self.nodes[node_id]
47
+ lines.append(f"- {node_id} ({description}): {state.status}" + (f" — {state.note}" if state.note else ""))
48
+ return "\n".join(lines)
@@ -0,0 +1,32 @@
1
+ """LLM provider (spec §31: interchangeable behind a narrow interface).
2
+ Only implementation right now is local Ollama; ASR/TTS have their own
3
+ similarly narrow wrappers in asr.py/tts.py. Nothing outside this module
4
+ imports `ollama` directly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+
12
+ import ollama
13
+
14
+ from .models import AgentTurnDecision
15
+
16
+ MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:7b-instruct")
17
+
18
+ _client = ollama.AsyncClient()
19
+
20
+
21
+ async def decide_turn(system_prompt: str, user_prompt: str) -> AgentTurnDecision:
22
+ response = await _client.chat(
23
+ model=MODEL,
24
+ messages=[
25
+ {"role": "system", "content": system_prompt},
26
+ {"role": "user", "content": user_prompt},
27
+ ],
28
+ format=AgentTurnDecision.model_json_schema(),
29
+ options={"temperature": 0.4},
30
+ )
31
+ content = response.message.content
32
+ return AgentTurnDecision.model_validate(json.loads(content))
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import asynccontextmanager
4
+ from uuid import UUID
5
+
6
+ from fastapi import FastAPI, HTTPException, Request
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import StreamingResponse
9
+
10
+ from . import agent, asr, db, tts
11
+ from .models import (
12
+ SessionListItem,
13
+ SessionSummary,
14
+ StartSessionRequest,
15
+ StartSessionResponse,
16
+ SynthesizeRequest,
17
+ TranscribeResponse,
18
+ TurnRequest,
19
+ TurnResponse,
20
+ )
21
+
22
+
23
+ @asynccontextmanager
24
+ async def lifespan(_app: FastAPI):
25
+ await db.init_db()
26
+ yield
27
+
28
+
29
+ app = FastAPI(title="PyInterviewBot ai-service", lifespan=lifespan)
30
+
31
+ app.add_middleware(
32
+ CORSMiddleware,
33
+ allow_origins=["*"],
34
+ allow_methods=["*"],
35
+ allow_headers=["*"],
36
+ )
37
+
38
+
39
+ @app.get("/health")
40
+ async def health() -> dict[str, str]:
41
+ return {"status": "ok"}
42
+
43
+
44
+ @app.post("/sessions", response_model=StartSessionResponse)
45
+ async def create_session(_req: StartSessionRequest) -> StartSessionResponse:
46
+ session_id, question_text = await agent.start_session()
47
+ return StartSessionResponse(session_id=session_id, question_text=question_text)
48
+
49
+
50
+ @app.post("/sessions/{session_id}/turn", response_model=TurnResponse)
51
+ async def turn(session_id: UUID, req: TurnRequest) -> TurnResponse:
52
+ try:
53
+ return await agent.take_turn(session_id, req.transcript)
54
+ except ValueError as exc:
55
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
56
+
57
+
58
+ @app.get("/sessions", response_model=list[SessionListItem])
59
+ async def list_sessions() -> list[SessionListItem]:
60
+ return await db.list_sessions()
61
+
62
+
63
+ @app.get("/sessions/{session_id}/summary", response_model=SessionSummary)
64
+ async def summary(session_id: UUID) -> SessionSummary:
65
+ row = await db.get_session_row(session_id)
66
+ if row is None:
67
+ raise HTTPException(status_code=404, detail=f"unknown session {session_id}")
68
+ return SessionSummary(
69
+ session_id=session_id,
70
+ resume_claim=row["resume_claim"],
71
+ is_complete=bool(row["is_complete"]),
72
+ transcript=await db.get_transcript(session_id),
73
+ evidence=await db.get_evidence(session_id),
74
+ )
75
+
76
+
77
+ @app.post("/asr/transcribe", response_model=TranscribeResponse)
78
+ async def transcribe(request: Request) -> TranscribeResponse:
79
+ pcm16 = await request.body()
80
+ text = await asr.transcribe(pcm16)
81
+ return TranscribeResponse(transcript=text)
82
+
83
+
84
+ @app.post("/tts/synthesize")
85
+ async def synthesize(req: SynthesizeRequest) -> StreamingResponse:
86
+ return StreamingResponse(
87
+ tts.synthesize_stream(req.text),
88
+ media_type=f"audio/L16;rate={tts.SAMPLE_RATE};channels=1",
89
+ )
90
+
91
+
92
+ def main() -> None:
93
+ import uvicorn
94
+
95
+ uvicorn.run("pyinterviewbot_ai.main:app", host="127.0.0.1", port=8000, reload=False)
@@ -0,0 +1,92 @@
1
+ """Pydantic schemas: the HTTP contract with the Rust gateway, plus the
2
+ structured-output schema the LLM is constrained to when deciding a turn.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Literal
8
+ from uuid import UUID
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+ EvidenceStatus = Literal["confirmed", "weak", "contradicted", "not_addressed"]
13
+ NextAction = Literal["probe", "clarify", "challenge", "move_on", "simulate", "conclude"]
14
+
15
+
16
+ class StartSessionRequest(BaseModel):
17
+ resume_seed: bool = True
18
+
19
+
20
+ class StartSessionResponse(BaseModel):
21
+ session_id: UUID
22
+ question_text: str
23
+
24
+
25
+ class TurnRequest(BaseModel):
26
+ transcript: str
27
+
28
+
29
+ class TurnResponse(BaseModel):
30
+ ai_text: str
31
+ is_complete: bool
32
+
33
+
34
+ class TranscribeResponse(BaseModel):
35
+ transcript: str
36
+
37
+
38
+ class SynthesizeRequest(BaseModel):
39
+ text: str
40
+
41
+
42
+ class EvidenceUpdate(BaseModel):
43
+ """One evidence-graph node update the LLM produces after hearing an answer."""
44
+
45
+ node: str = Field(description="Evidence node id this update applies to")
46
+ status: EvidenceStatus
47
+ note: str = Field(description="One sentence: what the candidate said that supports this status")
48
+
49
+
50
+ class AgentTurnDecision(BaseModel):
51
+ """The full structured output the interview agent LLM call must produce
52
+ each turn. The gateway never sees this — only `question_text` (as
53
+ `ai_text`) and `is_complete` cross the HTTP boundary back to it.
54
+ """
55
+
56
+ evidence_updates: list[EvidenceUpdate]
57
+ next_action: NextAction
58
+ question_text: str
59
+ is_complete: bool
60
+
61
+
62
+ class TranscriptSegment(BaseModel):
63
+ turn_number: int
64
+ speaker: Literal["ai", "candidate"]
65
+ text: str
66
+
67
+
68
+ class EvidenceRecord(BaseModel):
69
+ competency: str
70
+ node: str
71
+ status: EvidenceStatus
72
+ note: str
73
+ turn_number: int
74
+
75
+
76
+ class SessionListItem(BaseModel):
77
+ session_id: UUID
78
+ created_at: str
79
+ resume_claim: str
80
+ is_complete: bool
81
+ turn_count: int
82
+
83
+
84
+ class SessionSummary(BaseModel):
85
+ """Recruiter-facing view — the one place all this detail is allowed to
86
+ surface (spec §24)."""
87
+
88
+ session_id: UUID
89
+ resume_claim: str
90
+ is_complete: bool
91
+ transcript: list[TranscriptSegment]
92
+ evidence: list[EvidenceRecord]
@@ -0,0 +1,26 @@
1
+ """Resume claim seeding.
2
+
3
+ This MVP slice does not implement resume upload or a real resume parser
4
+ (spec §15 describes claim extraction from an uploaded document generally —
5
+ that's out of scope here). Instead it seeds the one claim used by the §36
6
+ demo scenario. A future resume parser would produce `ResumeClaim` objects
7
+ the same shape as this one; nothing downstream needs to change.
8
+ """
9
+
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ResumeClaim:
15
+ competency: str
16
+ text: str
17
+
18
+
19
+ SEED_CLAIM = ResumeClaim(
20
+ competency="rag_architecture",
21
+ text="Designed an enterprise RAG platform using Azure OpenAI, Azure AI Search and AKS.",
22
+ )
23
+
24
+
25
+ def seed_claim() -> ResumeClaim:
26
+ return SEED_CLAIM
@@ -0,0 +1,65 @@
1
+ """TTS provider (spec §31): local Piper. Synthesizes and streams raw
2
+ PCM16LE mono audio chunk-by-chunk as they're produced, rather than
3
+ buffering the whole utterance — this is what lets the gateway start
4
+ forwarding audio to the browser before the sentence has finished
5
+ synthesizing (spec §27).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import os
12
+ import queue
13
+ import threading
14
+ from collections.abc import AsyncIterator
15
+
16
+ from piper.voice import PiperVoice
17
+
18
+ MODEL_PATH = os.environ.get("PIPER_MODEL_PATH", "models/en_US-lessac-medium.onnx")
19
+
20
+ _voice: PiperVoice | None = None
21
+ _lock = threading.Lock()
22
+
23
+ SAMPLE_RATE = 22050 # must match the loaded voice's config; asserted at load time
24
+
25
+
26
+ def _get_voice() -> PiperVoice:
27
+ global _voice
28
+ with _lock:
29
+ if _voice is None:
30
+ voice = PiperVoice.load(MODEL_PATH)
31
+ assert voice.config.sample_rate == SAMPLE_RATE, (
32
+ f"voice sample rate {voice.config.sample_rate} != expected {SAMPLE_RATE}; "
33
+ "update tts.SAMPLE_RATE and the candidate client's playback rate together"
34
+ )
35
+ _voice = voice
36
+ return _voice
37
+
38
+
39
+ _SENTINEL = object()
40
+
41
+
42
+ def _synthesize_worker(text: str, out_queue: "queue.Queue[object]") -> None:
43
+ try:
44
+ voice = _get_voice()
45
+ for chunk in voice.synthesize(text):
46
+ out_queue.put(chunk.audio_int16_bytes)
47
+ except Exception as exc: # noqa: BLE001 — surfaced to the caller via the queue
48
+ out_queue.put(exc)
49
+ finally:
50
+ out_queue.put(_SENTINEL)
51
+
52
+
53
+ async def synthesize_stream(text: str) -> AsyncIterator[bytes]:
54
+ out_queue: "queue.Queue[object]" = queue.Queue()
55
+ thread = threading.Thread(target=_synthesize_worker, args=(text, out_queue), daemon=True)
56
+ thread.start()
57
+
58
+ loop = asyncio.get_event_loop()
59
+ while True:
60
+ item = await loop.run_in_executor(None, out_queue.get)
61
+ if item is _SENTINEL:
62
+ break
63
+ if isinstance(item, Exception):
64
+ raise item
65
+ yield item # type: ignore[misc]