xuan-luo commited on
Commit
e92c350
·
verified ·
1 Parent(s): efdebd3

Upload packaged project bundle

Browse files
Files changed (5) hide show
  1. README.md +303 -3
  2. config.yaml +136 -0
  3. install_env.sh +140 -0
  4. src.zip +3 -0
  5. start_service.sh +806 -0
README.md CHANGED
@@ -1,3 +1,303 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BioPacific MIP Research Assistant
2
+
3
+ BioPacific MIP Research Assistant is an agentic AI system designed to help researchers explore and understand scientific literature more efficiently. It combines a local LLM service, an embedding model, a Qdrant vector database, and an automated paper-processing pipeline to support paper-grounded question answering over the BioPacific literature collection.
4
+
5
+ The system can ingest papers, update the searchable database, retrieve relevant documents, and serve a session-based REST API for interactive research workflows.
6
+
7
+ ## New Features
8
+
9
+ The current version introduces several improvements for a more practical research assistant experience.
10
+
11
+ - **Multi-turn conversation support.** The agent now supports session-based conversations, so users can ask follow-up questions while preserving the context of previous turns.
12
+ - **Automatic intention recognition.** The agent can decide whether a user message actually needs retrieval. For example, it can skip retrieval for simple follow-up requests such as rephrasing, but perform retrieval when the question requires scientific evidence.
13
+ - **Automatic natural-language filters.** The agent can infer structured retrieval constraints directly from user language, including journal, time range, and author hints. For example, if a user asks for *synthetic biology papers published in PNAS in the last 4 years*, the system can translate that request into targeted retrieval filters automatically.
14
+ - **More concise and precise answers.** Before generating the final response, the agent first cleans and compresses retrieved paper content into focused summaries, then answers based on those refined inputs. This makes the final output shorter, clearer, and more relevant to the user's request.
15
+
16
+ ## Environment Setup
17
+
18
+ This project requires an **Anaconda/Conda** environment.
19
+
20
+ From the repository root, run:
21
+
22
+ ```bash
23
+ bash install_env.sh
24
+ ```
25
+
26
+ This script will automatically create a Conda environment named `biopacific` and install the required packages for the project.
27
+
28
+ After the environment is created, go to the `models/` directory. Each model folder contains its own `download_model.sh` script. Run those scripts to download the required local models:
29
+
30
+ ```bash
31
+ cd models/Qwen3-Embedding-8B
32
+ bash download_model.sh
33
+
34
+ cd ../Qwen3.5-9B
35
+ bash download_model.sh
36
+ ```
37
+
38
+ After that, activate the environment when you want to use the system:
39
+
40
+ ```bash
41
+ conda activate biopacific
42
+ ```
43
+
44
+ ## Configuration
45
+
46
+ After installing the environment, configure the project by editing `config.yaml`.
47
+
48
+ Most settings in `config.yaml` do not need to be changed for normal use. In practice, the most important items are:
49
+
50
+ - **GPU allocation**
51
+ - **Port allocation**
52
+
53
+ ### GPU Allocation
54
+
55
+ The two vLLM services are configured independently:
56
+
57
+ - `embedding.gpu`: GPU used by the embedding model
58
+ - `llm.gpu`: GPU used by the chat/completions model
59
+
60
+ By default, the config assigns:
61
+
62
+ - `embedding.gpu: "0"`
63
+ - `llm.gpu: "1"`
64
+
65
+ If your machine has at least two GPUs, this is a good default because the embedding model and the chat model can run separately. If you only have one GPU, you will need to adjust the configuration carefully based on available memory and your deployment strategy.
66
+
67
+ You may also need to tune:
68
+
69
+ - `embedding.gpu_memory_utilization`
70
+ - `llm.gpu_memory_utilization`
71
+ - `embedding.max_model_len`
72
+ - `llm.max_model_len`
73
+
74
+ If you encounter out-of-memory issues, reducing the memory utilization value is usually the first thing to try.
75
+
76
+ ### Port Allocation
77
+
78
+ The default service layout is:
79
+
80
+ - `embedding.port: 7770`
81
+ - `llm.port: 7771`
82
+ - `qdrant.port: 7772`
83
+ - `pipeline.s5_agent.service_port: 7773`
84
+
85
+ Make sure these ports are free on your machine before starting the system. If any of them conflict with another service, update the values in `config.yaml`.
86
+
87
+ ## Running the System
88
+
89
+ Once the `biopacific` environment is ready and `config.yaml` has been configured, start the system from the repository root:
90
+
91
+ ```bash
92
+ conda activate biopacific
93
+ cd /path/to/BioPacific-MIP-Rearch-Assistant
94
+ ./start_service.sh
95
+ ```
96
+
97
+ This command automatically starts the following long-running services:
98
+
99
+ - `embedding`: vLLM embedding server
100
+ - `llm`: vLLM chat/completions server
101
+ - `qdrant`: vector database
102
+ - `agent`: paper agent REST service
103
+
104
+ The startup workflow also runs the data pipeline automatically:
105
+
106
+ 1. It checks and starts the prerequisite services.
107
+ 2. It runs the paper pipeline stages.
108
+ 3. It updates the paper database if new content is available.
109
+ 4. It finally starts the agent REST service.
110
+
111
+ After the agent service is running, the system is ready to be accessed through the REST API.
112
+
113
+ ### Common Commands
114
+
115
+ Start everything:
116
+
117
+ ```bash
118
+ ./start_service.sh
119
+ ```
120
+
121
+ Stop everything:
122
+
123
+ ```bash
124
+ ./start_service.sh stop
125
+ ```
126
+
127
+ Restart everything:
128
+
129
+ ```bash
130
+ ./start_service.sh restart
131
+ ```
132
+
133
+ Check service status:
134
+
135
+ ```bash
136
+ ./start_service.sh status
137
+ ```
138
+
139
+ If you want the paper database to refresh regularly, you can schedule a monthly restart:
140
+
141
+ ```bash
142
+ ./start_service.sh restart
143
+ ```
144
+
145
+ Running this periodically is useful because each restart will trigger the automated pipeline and allow the database to update when new papers are available.
146
+
147
+ ## REST API Usage
148
+
149
+ An example client is provided in `rest-api/example_chat_session.py`.
150
+
151
+ You can run it directly after the services are up:
152
+
153
+ ```bash
154
+ python rest-api/example_chat_session.py
155
+ ```
156
+
157
+ ### Session ID and Multi-turn Conversation
158
+
159
+ The REST API is session-based. A `sessionId` identifies one conversation on the server side.
160
+
161
+ If you keep using the same `sessionId`, the agent will preserve recent conversation history and support multi-turn follow-up questions. This is what enables interactions such as:
162
+
163
+ - asking an initial literature question
164
+ - following up with "tell me more about paper [2]"
165
+ - requesting a simpler explanation of the previous answer
166
+
167
+ If you start a new `sessionId`, the server treats it as a new conversation.
168
+
169
+ ### The Three Core Methods
170
+
171
+ The API provides three main endpoints:
172
+
173
+ #### 1. Start a Session
174
+
175
+ `POST /v1/session/start`
176
+
177
+ Example request body:
178
+
179
+ ```json
180
+ {
181
+ "sessionId": "optional-session-id"
182
+ }
183
+ ```
184
+
185
+ Example response:
186
+
187
+ ```json
188
+ {
189
+ "sessionId": "your-session-id"
190
+ }
191
+ ```
192
+
193
+ If you do not want to manage session IDs yourself, the example client can generate one automatically.
194
+
195
+ #### 2. Chat
196
+
197
+ `POST /v1/chat`
198
+
199
+ Example request body:
200
+
201
+ ```json
202
+ {
203
+ "sessionId": "your-session-id",
204
+ "message": "Find synthetic biology papers published in PNAS in the last 4 years."
205
+ }
206
+ ```
207
+
208
+ Example response shape:
209
+
210
+ ```json
211
+ {
212
+ "sessionId": "your-session-id",
213
+ "response": "Final grounded answer...",
214
+ "docs": [
215
+ {
216
+ "chat_doc_id": 1,
217
+ "rank": 1,
218
+ "score": 0.91,
219
+ "paper": {
220
+ "title": "...",
221
+ "authors": ["..."],
222
+ "journal": "...",
223
+ "pub_date": "...",
224
+ "doi": "...",
225
+ "keywords": ["..."],
226
+ "abstract": "...",
227
+ "sections": [
228
+ {
229
+ "section_title": "...",
230
+ "subsections": [
231
+ {
232
+ "title": "...",
233
+ "paragraphs": ["..."]
234
+ }
235
+ ]
236
+ }
237
+ ],
238
+ "link": "https://pubmed.ncbi.nlm.nih.gov/..."
239
+ }
240
+ }
241
+ ]
242
+ }
243
+ ```
244
+
245
+ The `response` field contains the assistant answer, and `docs` contains the retrieved paper results for that turn. Each document entry currently includes:
246
+
247
+ - `chat_doc_id`: the stable paper identifier used by the assistant for inline citations during the chat session
248
+ - `rank`: the retrieval ranking for the current turn
249
+ - `score`: the retrieval similarity score returned by the agent
250
+ - `paper`: the paper payload, including `title`, `abstract`, `sections`, `authors`, `journal`, `pub_date`, `doi`, `keywords`, and a PubMed `link`
251
+
252
+ Important: citations in the agent's `response` refer to `chat_doc_id`, not to `rank`. For example, if the response cites paper `[3]`, that means the cited paper is the one whose `chat_doc_id` is `3`, not necessarily the paper whose retrieval `rank` is `3` in the current turn.
253
+
254
+ #### 3. End a Session
255
+
256
+ `POST /v1/session/end`
257
+
258
+ Example request body:
259
+
260
+ ```json
261
+ {
262
+ "sessionId": "your-session-id"
263
+ }
264
+ ```
265
+
266
+ Example response:
267
+
268
+ ```json
269
+ {
270
+ "ok": true
271
+ }
272
+ ```
273
+
274
+ Ending a session clears the conversation state associated with that session on the server.
275
+
276
+ ### Example Python Workflow
277
+
278
+ The example client exposes three corresponding methods:
279
+
280
+ - `start_session()`
281
+ - `chat()`
282
+ - `end_session()`
283
+
284
+ A typical workflow looks like this:
285
+
286
+ ```python
287
+ from example_chat_session import ExampleChatSession
288
+
289
+ session = ExampleChatSession()
290
+ session.start_session()
291
+
292
+ session.chat("Find synthetic biology papers published in PNAS in the last 4 years.")
293
+ session.chat("Now summarize the key trends from those papers.")
294
+ session.chat("Please explain the previous answer in simpler language.")
295
+
296
+ session.end_session()
297
+ ```
298
+
299
+ As long as the same session remains active, the assistant can use the conversation history to interpret follow-up questions more effectively.
300
+
301
+ ## Summary
302
+
303
+ BioPacific MIP Research Assistant provides an agentic, paper-grounded research workflow with automated paper ingestion, retrieval, summarization, and session-based conversation. With the latest updates, it now supports better multi-turn interaction, smarter retrieval decisions, more precise natural-language filtering, and cleaner final answers for literature exploration.
config.yaml ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # BioPacific service config. Single source of truth for ports, GPU assignment,
3
+ # model paths, memory budgets, and paper-search agent options.
4
+ # ./start_service.sh reads this file on every invocation; edit and re-run.
5
+ #
6
+ # Paths are resolved relative to the repository root (the directory that
7
+ # contains this file). Absolute paths are accepted too.
8
+ #
9
+ # Service port layout:
10
+ # embedding (Qwen3-Embedding-8B) : 7770
11
+ # llm (Qwen3.5-9B) : 7771
12
+ # qdrant (vector DB) : 7772
13
+ # agent (paper agent HTTP) : 7773
14
+ # ============================================================================
15
+
16
+ # ----------------------------------------------------------------------------
17
+ # Global settings
18
+ # ----------------------------------------------------------------------------
19
+
20
+ env_name: biopacific # conda env name to auto-detect for python / vllm
21
+ service_host: 0.0.0.0 # vLLM + Qdrant HTTP listen address
22
+
23
+ # ----------------------------------------------------------------------------
24
+ # Qdrant vector database
25
+ # ----------------------------------------------------------------------------
26
+ qdrant:
27
+ binary: pipeline/s4-embedding/qdrant/qdrant # path to the qdrant executable
28
+ storage_path: pipeline/s4-embedding/vectors # on-disk location of indexed vectors
29
+ port: 7772 # HTTP port
30
+
31
+ # ----------------------------------------------------------------------------
32
+ # Qwen3-Embedding-8B (embedding model, vLLM)
33
+ #
34
+ # Turns text into number vectors for search. Clients call this server on
35
+ # `port` below; only embeddings are served (no chat here).
36
+ # ----------------------------------------------------------------------------
37
+ embedding:
38
+ served_name: Qwen3-Embedding-8B
39
+ model_dir: models/Qwen3-Embedding-8B
40
+ # TCP port this embedding HTTP server listens on (must match other services).
41
+ port: 7770
42
+ # Which GPU(s) to use: "0" = first GPU. Use "0,1" only if you run multi-GPU
43
+ # tensor parallel and your start script expects several devices.
44
+ gpu: "0"
45
+ # Fraction of GPU VRAM vLLM may reserve (0.0–1.0). Lower if you run out of memory.
46
+ gpu_memory_utilization: 0.8
47
+ # Max input length in tokens for one embedding request; raise only if you need
48
+ # longer texts and your GPU has enough memory.
49
+ max_model_len: 32767
50
+
51
+ # ----------------------------------------------------------------------------
52
+ # Qwen3.5-9B (chat / completions LLM, vLLM)
53
+ #
54
+ # One model for parsing queries, refining snippets, and writing answers. Same
55
+ # OpenAI-style HTTP API as typical chat APIs. Tune sampling below for more or
56
+ # less randomness in replies.
57
+ # ----------------------------------------------------------------------------
58
+ llm:
59
+ served_name: llm
60
+ model_dir: models/Qwen3.5-9B
61
+ # TCP port for this LLM HTTP server (different from embedding and Qdrant).
62
+ port: 7771
63
+ # GPU index for this server, e.g. "1" = second GPU. Use a free GPU not used by embedding.
64
+ gpu: "1"
65
+ # How much of that GPU’s VRAM vLLM may use; reduce if you hit out-of-memory errors.
66
+ gpu_memory_utilization: 0.8
67
+ # Randomness: higher = more creative / less repeatable; lower = steadier answers.
68
+ temperature: 0.6
69
+ # Caps how adventurous word choices can be (0–1). Near 1 = broader; lower = more focused.
70
+ top_p: 0.9
71
+ # Hard cap on how many new tokens the model may generate in one reply (not input length).
72
+ max_tokens: 4096
73
+ # Max context window (prompt + history + new text) in tokens; required by ./start_service.sh.
74
+ max_model_len: 65536
75
+
76
+ pipeline:
77
+ # Stage 1: download PubMed metadata and abstracts, grouped by journal.
78
+ s1_index:
79
+ start_year: 2000 # First publication year to include.
80
+ end_year: current # Last year to include; "current" means this calendar year.
81
+ max_retries: 3 # Retry a whole journal this many times if the indexing run fails.
82
+ retry_wait_seconds: 60 # Wait this many seconds between those journal-level retries.
83
+ ncbi_api_key: "67f60f7a3eb8692d7a03168cb753b4271808" # Optional PubMed API key; allows faster requests.
84
+ output_dir: pipeline/s1-index # Where one JSON file per journal is written.
85
+ journals: # Output name -> journal ISSN used in PubMed.
86
+ nature: "0028-0836"
87
+ nature_communications: "2041-1723"
88
+ pnas: "0027-8424"
89
+ acs_synthetic_biology: "2161-5063"
90
+ # Stage 2: keep only papers relevant to the topic below.
91
+ s2_filter:
92
+ input_dir: pipeline/s1-index # Reads the per-journal JSON files from s1_index.
93
+ output_dir: pipeline/s2-filter # Writes filtered results here.
94
+ keyword: "synthetic biology" # Topic used to decide whether a paper is relevant.
95
+ batch_size: 16 # Max concurrent model API calls during filtering.
96
+ api_endpoint: "https://api.fireworks.ai/inference/v1" # OpenAI-compatible API base URL.
97
+ api_key: "utKx5V7ovmjcL62G2j0sbSC8JDAnRGkmZf35IRBBAMs5Ofse" # API key for that service.
98
+ model: "accounts/fireworks/models/qwen3-vl-30b-a3b-instruct" # Model used for yes/no relevance checks.
99
+ direct_copy_journals: # Journals to keep without LLM filtering.
100
+ - acs_synthetic_biology
101
+ filter_journals: # Journals that should go through the LLM filter.
102
+ - nature
103
+ - nature_communications
104
+ - pnas
105
+ # Stage 3: fetch full text sections when possible; otherwise keep abstracts only.
106
+ s3_fetch:
107
+ input_dir: pipeline/s2-filter # Reads relevant-paper JSON files from s2_filter.
108
+ output_dir: pipeline/s3-fetch # Writes fetched/enriched paper JSON files here.
109
+ fetch_interval: 1 # Minimum seconds per paper; helps avoid hitting sites too fast.
110
+ checkpoint_interval: 50 # Save resume progress after this many processed papers.
111
+ timeout: 90 # Per-paper timeout for DOI lookup, HTTP fetch, and browser fallback.
112
+ abstract_only_journals: # Journals that should skip full-text fetching and stay abstract-only.
113
+ - acs_synthetic_biology
114
+ fetch_journals: # Journals where DOI/full-text fetching should run.
115
+ - nature
116
+ - nature_communications
117
+ - pnas
118
+ # Stage 4: turn fetched papers into vectors and store them in Qdrant.
119
+ s4_embedding:
120
+ input_dir: pipeline/s3-fetch # Reads fetched journal JSON files from s3_fetch.
121
+ papers_dir: pipeline/s4-embedding/papers # Stores one normalized JSON file per paper (PMID.json).
122
+ manifest_path: pipeline/s4-embedding/paper-embedding-manifest.json # Local state for incremental re-indexing.
123
+ collection: papers # Qdrant collection name to create/update.
124
+ batch_size: 32 # Papers per embedding + Qdrant upsert batch.
125
+ timeout: 300 # Timeout for embedding API and Qdrant requests.
126
+ embedding_model: Qwen3-Embedding-8B # Model name sent to the embeddings server.
127
+ preprocess_limit: null # Optional cap for preprocessing this run; null means no limit.
128
+ index_limit: null # Optional cap for indexing new/changed papers this run; null means no limit.
129
+ # Stage 5: chat service that searches papers and answers with paper-grounded summaries.
130
+ s5_agent:
131
+ enhanced_query: true # true = parse the question into filters + search text; false = plain vector search only.
132
+ top_k: 5 # Default number of papers retrieved for each user question.
133
+ collection: papers # Qdrant collection the agent searches.
134
+ timeout_seconds: 30.0 # HTTP timeout for retrieval and LLM calls inside the agent.
135
+ history_turns: 5 # How many recent chat turns each session keeps in memory. Increase this value will slow down the response time and might cause error if exceeds the max tokens of the model.
136
+ service_port: 7773 # Port for the paper-agent REST API.
install_env.sh ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ENV_NAME="${ENV_NAME:-biopacific}"
5
+ PYTHON_VERSION="${PYTHON_VERSION:-3.12}"
6
+
7
+ if ! command -v conda >/dev/null 2>&1; then
8
+ echo "conda is not available in PATH." >&2
9
+ exit 1
10
+ fi
11
+
12
+ if [[ "$(uname -s)" != "Linux" ]]; then
13
+ echo "This installer currently supports Linux only." >&2
14
+ exit 1
15
+ fi
16
+
17
+ CONDA_BASE="$(conda info --base)"
18
+ source "${CONDA_BASE}/etc/profile.d/conda.sh"
19
+
20
+ if conda env list | awk '{print $1}' | grep -Fxq "${ENV_NAME}"; then
21
+ echo "Conda environment '${ENV_NAME}' already exists. Reusing it."
22
+ else
23
+ echo "Creating conda environment '${ENV_NAME}' with Python ${PYTHON_VERSION} ..."
24
+ conda create -n "${ENV_NAME}" "python=${PYTHON_VERSION}" -y
25
+ fi
26
+
27
+ conda activate "${ENV_NAME}"
28
+
29
+ ARCH="$(uname -m)"
30
+ HOST_TRIPLE=""
31
+ SYSROOT_PACKAGE=""
32
+ case "${ARCH}" in
33
+ x86_64|amd64)
34
+ HOST_TRIPLE="x86_64-conda-linux-gnu"
35
+ SYSROOT_PACKAGE="sysroot_linux-64"
36
+ ;;
37
+ aarch64|arm64)
38
+ HOST_TRIPLE="aarch64-conda-linux-gnu"
39
+ SYSROOT_PACKAGE="sysroot_linux-aarch64"
40
+ ;;
41
+ *)
42
+ echo "Unsupported Linux architecture: ${ARCH}" >&2
43
+ exit 1
44
+ ;;
45
+ esac
46
+
47
+ echo "Installing conda-forge compiler toolchain and sysroot into '${ENV_NAME}' ..."
48
+ conda install -n "${ENV_NAME}" -c conda-forge -y \
49
+ compilers \
50
+ c-compiler \
51
+ cxx-compiler \
52
+ binutils \
53
+ libgcc-ng \
54
+ libstdcxx-ng \
55
+ "${SYSROOT_PACKAGE}"
56
+
57
+ # Reactivate so newly installed compiler activation hooks take effect.
58
+ conda deactivate
59
+ conda activate "${ENV_NAME}"
60
+
61
+ export PATH="${CONDA_PREFIX}/bin:${PATH}"
62
+
63
+ CC_CANDIDATE="${CONDA_PREFIX}/bin/${HOST_TRIPLE}-cc"
64
+ CXX_CANDIDATE="${CONDA_PREFIX}/bin/${HOST_TRIPLE}-c++"
65
+
66
+ if [[ -x "${CC_CANDIDATE}" ]]; then
67
+ export CC="${CC_CANDIDATE}"
68
+ elif command -v "${HOST_TRIPLE}-cc" >/dev/null 2>&1; then
69
+ export CC="$(command -v "${HOST_TRIPLE}-cc")"
70
+ fi
71
+
72
+ if [[ -x "${CXX_CANDIDATE}" ]]; then
73
+ export CXX="${CXX_CANDIDATE}"
74
+ elif command -v "${HOST_TRIPLE}-c++" >/dev/null 2>&1; then
75
+ export CXX="$(command -v "${HOST_TRIPLE}-c++")"
76
+ fi
77
+
78
+ if [[ -z "${CC:-}" || -z "${CXX:-}" ]]; then
79
+ echo "Failed to locate conda compiler toolchain after installation." >&2
80
+ exit 1
81
+ fi
82
+
83
+ if [[ -d "${CONDA_PREFIX}/${HOST_TRIPLE}/sysroot" ]]; then
84
+ export CONDA_BUILD_SYSROOT="${CONDA_PREFIX}/${HOST_TRIPLE}/sysroot"
85
+ fi
86
+
87
+ export CMAKE_C_COMPILER="${CC}"
88
+ export CMAKE_CXX_COMPILER="${CXX}"
89
+ export CUDAHOSTCXX="${CXX}"
90
+ export CMAKE_CUDA_HOST_COMPILER="${CXX}"
91
+ export CCACHE_DISABLE=1
92
+
93
+ echo "Installing uv into '${ENV_NAME}' ..."
94
+ python -m pip install --upgrade pip
95
+ python -m pip install uv
96
+
97
+ echo "Installing core Python packages with uv ..."
98
+ uv pip install -U \
99
+ requests \
100
+ openai \
101
+ beautifulsoup4 \
102
+ selenium \
103
+ webdriver-manager \
104
+ numpy
105
+
106
+ echo "Installing vLLM with uv ..."
107
+ if ! uv pip install -U vllm --torch-backend=auto; then
108
+ echo >&2
109
+ echo "vLLM installation failed." >&2
110
+ echo "Diagnostics:" >&2
111
+ echo " gcc: $(command -v gcc || true)" >&2
112
+ echo " g++: $(command -v g++ || true)" >&2
113
+ echo " CC: ${CC:-"(unset)"}" >&2
114
+ echo " CXX: ${CXX:-"(unset)"}" >&2
115
+ echo " CMAKE_C_COMPILER: ${CMAKE_C_COMPILER:-"(unset)"}" >&2
116
+ echo " CMAKE_CXX_COMPILER: ${CMAKE_CXX_COMPILER:-"(unset)"}" >&2
117
+ echo " CUDAHOSTCXX: ${CUDAHOSTCXX:-"(unset)"}" >&2
118
+ echo " sysroot: ${CONDA_BUILD_SYSROOT:-"(unset)"}" >&2
119
+ echo " gcc version: $(${CC} --version 2>/dev/null | sed -n '1p' || true)" >&2
120
+ echo " g++ version: $(${CXX} --version 2>/dev/null | sed -n '1p' || true)" >&2
121
+ exit 1
122
+ fi
123
+
124
+ echo
125
+ echo "Environment ready."
126
+ echo " active env: ${ENV_NAME}"
127
+ echo " arch: ${ARCH}"
128
+ echo " python: $(python --version 2>&1)"
129
+ echo " uv: $(uv --version 2>&1)"
130
+ echo " gcc: $(command -v gcc)"
131
+ echo " g++: $(command -v g++)"
132
+ if [[ -n "${CC:-}" ]]; then
133
+ echo " CC: ${CC}"
134
+ fi
135
+ if [[ -n "${CXX:-}" ]]; then
136
+ echo " CXX: ${CXX}"
137
+ fi
138
+ if [[ -n "${CONDA_BUILD_SYSROOT:-}" ]]; then
139
+ echo " CONDA_BUILD_SYSROOT: ${CONDA_BUILD_SYSROOT}"
140
+ fi
src.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1e15d9c61600d5ff851b636c9c01fcea7a2b57822578611e9e6ddfa97424c16
3
+ size 1090877934
start_service.sh ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ #
3
+ # BioPacific launcher and orchestrator.
4
+ #
5
+ # This script manages two different concepts:
6
+ #
7
+ # 1. Services (long-running background processes)
8
+ # - embedding : vLLM embedding server
9
+ # - llm : vLLM chat/completions server
10
+ # - qdrant : vector database
11
+ # - agent : paper agent REST service
12
+ #
13
+ # 2. Pipeline stages (one-shot foreground jobs)
14
+ # - s1_index : build journal article indexes
15
+ # - s2_filter : filter indexed papers
16
+ # - s3_fetch : fetch article content / sections
17
+ # - s4_embedding : preprocess and push embeddings into Qdrant
18
+ #
19
+ # Default orchestration:
20
+ # start / restart with no explicit targets performs a full bring-up:
21
+ # 1) start embedding + llm + qdrant
22
+ # 2) wait until those prerequisite services are ready
23
+ # 3) run pipeline.s1_index -> s2_filter -> s3_fetch -> s4_embedding
24
+ # 4) start the agent service
25
+ #
26
+ # Service processes run in the background via nohup; PIDs are recorded under
27
+ # logs/ so subsequent stop/status calls can find them again. Pipeline stages
28
+ # run in the foreground and stream output to both the terminal and log files.
29
+ #
30
+ # Common usage:
31
+ # ./start_service.sh
32
+ # ./start_service.sh start
33
+ # ./start_service.sh start embedding llm qdrant
34
+ # ./start_service.sh stop
35
+ # ./start_service.sh stop agent
36
+ # ./start_service.sh restart
37
+ # ./start_service.sh status
38
+ # ./start_service.sh pipeline
39
+ # ./start_service.sh pipeline s2_filter s3_fetch
40
+ # CONFIG_FILE=/path/to/config.yaml ./start_service.sh start
41
+
42
+ set -euo pipefail
43
+
44
+ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
45
+ CONFIG_FILE="${CONFIG_FILE:-${ROOT_DIR}/config.yaml}"
46
+ LOG_DIR="${LOG_DIR:-${ROOT_DIR}/logs}"
47
+ mkdir -p "${LOG_DIR}"
48
+
49
+ SERVICES=(embedding llm qdrant agent)
50
+ PIPELINE_STAGES=(s1_index s2_filter s3_fetch s4_embedding)
51
+ PREREQ_SERVICES=(embedding llm qdrant)
52
+ STOP_ORDER=(agent qdrant llm embedding)
53
+
54
+ PYTHON_BIN=""
55
+ VLLM_BIN=""
56
+ CONDA_ENV_DIR=""
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Tiny helpers
60
+ # ---------------------------------------------------------------------------
61
+
62
+ die() {
63
+ echo "$*" >&2
64
+ exit 1
65
+ }
66
+
67
+ require_executable() {
68
+ local executable="$1"
69
+ local label="$2"
70
+ if [[ -z "${executable}" || ! -x "${executable}" ]]; then
71
+ die "Missing executable: ${label}"
72
+ fi
73
+ }
74
+
75
+ require_dir() {
76
+ [[ -d "$1" ]] || die "Directory not found: $1"
77
+ }
78
+
79
+ require_file() {
80
+ [[ -f "$1" ]] || die "File not found: $1"
81
+ }
82
+
83
+ append_unique_path() {
84
+ local value="$1"
85
+ local current="$2"
86
+ if [[ -z "${current}" ]]; then
87
+ printf '%s' "${value}"
88
+ elif [[ ":${current}:" == *":${value}:"* ]]; then
89
+ printf '%s' "${current}"
90
+ else
91
+ printf '%s:%s' "${value}" "${current}"
92
+ fi
93
+ }
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Conda env auto-detection (same behavior as before)
97
+ # ---------------------------------------------------------------------------
98
+
99
+ detect_conda_env_dir() {
100
+ local env_name="$1"
101
+ local -a candidates=()
102
+
103
+ if [[ -n "${PREFERRED_ENV_DIR:-}" ]]; then
104
+ candidates+=("${PREFERRED_ENV_DIR}")
105
+ fi
106
+ if [[ -n "${CONDA_PREFIX:-}" && "$(basename "${CONDA_PREFIX}")" == "${env_name}" ]]; then
107
+ candidates+=("${CONDA_PREFIX}")
108
+ fi
109
+ candidates+=("${ROOT_DIR}/../anaconda/envs/${env_name}")
110
+ if command -v conda >/dev/null 2>&1; then
111
+ local conda_base
112
+ conda_base="$(conda info --base 2>/dev/null || true)"
113
+ [[ -n "${conda_base}" ]] && candidates+=("${conda_base}/envs/${env_name}")
114
+ fi
115
+ candidates+=(
116
+ "${HOME}/anaconda/envs/${env_name}"
117
+ "${HOME}/miniconda3/envs/${env_name}"
118
+ "${HOME}/mambaforge/envs/${env_name}"
119
+ )
120
+ for candidate in "${candidates[@]}"; do
121
+ if [[ -n "${candidate}" && -x "${candidate}/bin/python" ]]; then
122
+ printf '%s\n' "${candidate}"
123
+ return 0
124
+ fi
125
+ done
126
+ return 1
127
+ }
128
+
129
+ use_preferred_runtime() {
130
+ local env_name="$1"
131
+ local env_dir
132
+ env_dir="$(detect_conda_env_dir "${env_name}" || true)"
133
+
134
+ if [[ -n "${env_dir}" ]]; then
135
+ CONDA_ENV_DIR="${env_dir}"
136
+ export PATH
137
+ PATH="$(append_unique_path "${CONDA_ENV_DIR}/bin" "${PATH}")"
138
+ export LD_LIBRARY_PATH
139
+ LD_LIBRARY_PATH="$(append_unique_path "${CONDA_ENV_DIR}/lib" "${LD_LIBRARY_PATH:-}")"
140
+ export LIBRARY_PATH
141
+ LIBRARY_PATH="$(append_unique_path "${CONDA_ENV_DIR}/lib" "${LIBRARY_PATH:-}")"
142
+ export CONDA_PREFIX="${CONDA_ENV_DIR}"
143
+ export CONDA_DEFAULT_ENV="${env_name}"
144
+ PYTHON_BIN="${CONDA_ENV_DIR}/bin/python"
145
+ VLLM_BIN="${CONDA_ENV_DIR}/bin/vllm"
146
+ fi
147
+ [[ -z "${PYTHON_BIN}" ]] && PYTHON_BIN="$(command -v python3 || true)"
148
+ [[ -z "${VLLM_BIN}" ]] && VLLM_BIN="$(command -v vllm || true)"
149
+ require_executable "${PYTHON_BIN}" "python3"
150
+ }
151
+
152
+ # ---------------------------------------------------------------------------
153
+ # Config loading via PyYAML. Emits shell assignments for CFG_* variables.
154
+ # ---------------------------------------------------------------------------
155
+
156
+ load_config() {
157
+ require_file "${CONFIG_FILE}"
158
+ local dump
159
+ dump="$(
160
+ ROOT_DIR="${ROOT_DIR}" \
161
+ CONFIG_FILE="${CONFIG_FILE}" \
162
+ "${PYTHON_BIN}" - <<'PY'
163
+ import os, shlex, sys
164
+ try:
165
+ import yaml
166
+ except ImportError:
167
+ sys.stderr.write(
168
+ "PyYAML is required. Install it in the biopacific env, e.g.\n"
169
+ " pip install pyyaml\n"
170
+ )
171
+ sys.exit(1)
172
+
173
+ root = os.environ["ROOT_DIR"]
174
+ with open(os.environ["CONFIG_FILE"], encoding="utf-8") as fh:
175
+ cfg = yaml.safe_load(fh) or {}
176
+
177
+ def resolve_path(value: str) -> str:
178
+ if not value:
179
+ return ""
180
+ return value if os.path.isabs(value) else os.path.normpath(os.path.join(root, value))
181
+
182
+ def emit(name: str, value) -> None:
183
+ print(f"{name}={shlex.quote(str(value))}")
184
+
185
+ emit("CFG_ENV_NAME", cfg.get("env_name", "biopacific"))
186
+ emit("CFG_SERVICE_HOST", cfg.get("service_host", "0.0.0.0"))
187
+
188
+ q = cfg.get("qdrant") or {}
189
+ emit("CFG_QDRANT_BINARY", resolve_path(q.get("binary", "")))
190
+ emit("CFG_QDRANT_STORAGE_PATH", resolve_path(q.get("storage_path", "")))
191
+ emit("CFG_QDRANT_PORT", q.get("port", 6333))
192
+
193
+ pipeline = cfg.get("pipeline")
194
+ if not isinstance(pipeline, dict):
195
+ sys.stderr.write("config.yaml: [pipeline] must be a mapping\n")
196
+ sys.exit(1)
197
+
198
+ a = pipeline.get("s5_agent")
199
+ if not isinstance(a, dict):
200
+ sys.stderr.write("config.yaml: [pipeline.s5_agent] must be a mapping\n")
201
+ sys.exit(1)
202
+ if "service_port" not in a:
203
+ sys.stderr.write("config.yaml: [pipeline.s5_agent].service_port is required\n")
204
+ sys.exit(1)
205
+ emit("CFG_AGENT_PORT", a["service_port"])
206
+
207
+ for yaml_key, prefix in (("embedding", "EMBEDDING"),
208
+ ("llm", "LLM")):
209
+ s = cfg.get(yaml_key)
210
+ if not isinstance(s, dict):
211
+ sys.stderr.write(
212
+ "config.yaml: [%s] must be a mapping (section missing or wrong type)\n"
213
+ % yaml_key
214
+ )
215
+ sys.exit(1)
216
+ if "max_model_len" not in s:
217
+ sys.stderr.write(
218
+ "config.yaml: [%s].max_model_len is required "
219
+ "(per-service vLLM --max-model-len; no default)\n" % yaml_key
220
+ )
221
+ sys.exit(1)
222
+ emit(f"CFG_{prefix}_SERVED_NAME", s.get("served_name", yaml_key))
223
+ emit(f"CFG_{prefix}_MODEL_DIR", resolve_path(s.get("model_dir", "")))
224
+ emit(f"CFG_{prefix}_PORT", s.get("port", 0))
225
+ emit(f"CFG_{prefix}_GPU", s.get("gpu", "0"))
226
+ emit(f"CFG_{prefix}_GPU_MEMORY_UTILIZATION",
227
+ s.get("gpu_memory_utilization", 0.8))
228
+ emit(f"CFG_{prefix}_MAX_MODEL_LEN", s["max_model_len"])
229
+ PY
230
+ )"
231
+ eval "${dump}"
232
+ }
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # Per-service metadata lookup. Given a service name, populate globals:
236
+ # SVC_LABEL, SVC_KIND (vllm|qdrant|python), SVC_PORT, SVC_GPU, SVC_MEM,
237
+ # SVC_MODEL_DIR, SVC_SCRIPT_PATH, SVC_SERVED_NAME, SVC_LOG_FILE,
238
+ # SVC_PID_FILE, SVC_PGREP_PATTERN,
239
+ # SVC_DEFAULT_CHAT_TEMPLATE_KWARGS.
240
+ # ---------------------------------------------------------------------------
241
+
242
+ select_service() {
243
+ local svc="$1"
244
+ SVC_LABEL="${svc}"
245
+ SVC_LOG_FILE="${LOG_DIR}/${svc}.log"
246
+ SVC_PID_FILE="${LOG_DIR}/${svc}.pid"
247
+ case "${svc}" in
248
+ embedding)
249
+ SVC_KIND="vllm"
250
+ SVC_PORT="${CFG_EMBEDDING_PORT}"
251
+ SVC_GPU="${CFG_EMBEDDING_GPU}"
252
+ SVC_MEM="${CFG_EMBEDDING_GPU_MEMORY_UTILIZATION}"
253
+ SVC_MODEL_DIR="${CFG_EMBEDDING_MODEL_DIR}"
254
+ SVC_SERVED_NAME="${CFG_EMBEDDING_SERVED_NAME}"
255
+ SVC_MAX_MODEL_LEN="${CFG_EMBEDDING_MAX_MODEL_LEN}"
256
+ SVC_VLLM_RUNNER="pooling"
257
+ SVC_DEFAULT_CHAT_TEMPLATE_KWARGS=""
258
+ SVC_PGREP_PATTERN="vllm serve ${SVC_MODEL_DIR}"
259
+ ;;
260
+ llm)
261
+ SVC_KIND="vllm"
262
+ SVC_PORT="${CFG_LLM_PORT}"
263
+ SVC_GPU="${CFG_LLM_GPU}"
264
+ SVC_MEM="${CFG_LLM_GPU_MEMORY_UTILIZATION}"
265
+ SVC_MODEL_DIR="${CFG_LLM_MODEL_DIR}"
266
+ SVC_SERVED_NAME="${CFG_LLM_SERVED_NAME}"
267
+ SVC_MAX_MODEL_LEN="${CFG_LLM_MAX_MODEL_LEN}"
268
+ SVC_VLLM_RUNNER=""
269
+ SVC_DEFAULT_CHAT_TEMPLATE_KWARGS='{"enable_thinking": false}'
270
+ SVC_PGREP_PATTERN="vllm serve ${SVC_MODEL_DIR}"
271
+ ;;
272
+ qdrant)
273
+ SVC_KIND="qdrant"
274
+ SVC_PORT="${CFG_QDRANT_PORT}"
275
+ SVC_GPU="-"
276
+ SVC_MEM="-"
277
+ SVC_MODEL_DIR="${CFG_QDRANT_STORAGE_PATH}"
278
+ SVC_SERVED_NAME="qdrant"
279
+ SVC_VLLM_RUNNER=""
280
+ SVC_DEFAULT_CHAT_TEMPLATE_KWARGS=""
281
+ SVC_PGREP_PATTERN="${CFG_QDRANT_BINARY}"
282
+ ;;
283
+ agent)
284
+ SVC_KIND="python"
285
+ SVC_PORT="${CFG_AGENT_PORT}"
286
+ SVC_GPU="-"
287
+ SVC_MEM="-"
288
+ SVC_MODEL_DIR="-"
289
+ SVC_SCRIPT_PATH="${ROOT_DIR}/pipeline/s5-agent/paper_agent.py"
290
+ SVC_SERVED_NAME="paper-agent"
291
+ SVC_VLLM_RUNNER=""
292
+ SVC_DEFAULT_CHAT_TEMPLATE_KWARGS=""
293
+ SVC_PGREP_PATTERN="${SVC_SCRIPT_PATH}"
294
+ ;;
295
+ *)
296
+ die "Unknown service: ${svc}. Valid: ${SERVICES[*]}"
297
+ ;;
298
+ esac
299
+ }
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # Runtime utilities
303
+ # ---------------------------------------------------------------------------
304
+
305
+ port_in_use() {
306
+ "${PYTHON_BIN}" - "$1" <<'PY'
307
+ import socket, sys
308
+ port = int(sys.argv[1])
309
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
310
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
311
+ try:
312
+ s.bind(("0.0.0.0", port))
313
+ except OSError:
314
+ sys.exit(0)
315
+ sys.exit(1)
316
+ PY
317
+ }
318
+
319
+ validate_shared_gpu_budget() {
320
+ "${PYTHON_BIN}" - \
321
+ "${CFG_EMBEDDING_GPU}" "${CFG_LLM_GPU}" \
322
+ "${CFG_EMBEDDING_GPU_MEMORY_UTILIZATION}" \
323
+ "${CFG_LLM_GPU_MEMORY_UTILIZATION}" <<'PY'
324
+ import sys
325
+ labels = ["embedding", "llm"]
326
+ gpus = sys.argv[1:3]
327
+ mems = [float(x) for x in sys.argv[3:5]]
328
+
329
+ per_gpu, per_gpu_who = {}, {}
330
+ for label, gpu, mem in zip(labels, gpus, mems):
331
+ for single in gpu.split(","):
332
+ single = single.strip()
333
+ if not single:
334
+ continue
335
+ per_gpu[single] = per_gpu.get(single, 0.0) + mem
336
+ per_gpu_who.setdefault(single, []).append(label)
337
+
338
+ bad = [(g, t, per_gpu_who[g]) for g, t in per_gpu.items() if t > 1.0]
339
+ if bad:
340
+ for gpu, total, who in bad:
341
+ print(
342
+ f"GPU {gpu} is shared by {', '.join(who)} with a combined "
343
+ f"memory budget of {total:.2f} (> 1.0).",
344
+ file=sys.stderr,
345
+ )
346
+ print(
347
+ "Move one of the services to a different GPU, or lower the "
348
+ "gpu_memory_utilization values in config.yaml.",
349
+ file=sys.stderr,
350
+ )
351
+ sys.exit(1)
352
+ PY
353
+ }
354
+
355
+ gpu_count() {
356
+ local list="$1"
357
+ local IFS=','
358
+ local -a gpus=($list)
359
+ echo "${#gpus[@]}"
360
+ }
361
+
362
+ get_running_pid() {
363
+ local pid_file="$1"
364
+ local expected="$2"
365
+
366
+ if [[ -f "${pid_file}" ]]; then
367
+ local pid
368
+ pid="$(<"${pid_file}")"
369
+ if [[ -n "${pid}" ]] && kill -0 "${pid}" >/dev/null 2>&1; then
370
+ local cmdline
371
+ cmdline="$(ps -p "${pid}" -o args= 2>/dev/null || true)"
372
+ if [[ "${cmdline}" == *"${expected}"* ]]; then
373
+ echo "${pid}"
374
+ return 0
375
+ fi
376
+ fi
377
+ fi
378
+
379
+ if command -v pgrep >/dev/null 2>&1; then
380
+ local pid
381
+ pid="$(pgrep -f "${expected}" | head -n 1 || true)"
382
+ if [[ -n "${pid}" ]]; then
383
+ echo "${pid}" > "${pid_file}"
384
+ echo "${pid}"
385
+ return 0
386
+ fi
387
+ fi
388
+ return 1
389
+ }
390
+
391
+ wait_for_stop() {
392
+ local pid="$1"
393
+ for _ in $(seq 1 20); do
394
+ kill -0 "${pid}" >/dev/null 2>&1 || return 0
395
+ sleep 1
396
+ done
397
+ return 1
398
+ }
399
+
400
+ validate_vllm_targets() {
401
+ local -a targets=("$@")
402
+ local target
403
+ for target in "${targets[@]}"; do
404
+ if [[ "${target}" == "embedding" || "${target}" == "llm" ]]; then
405
+ validate_shared_gpu_budget
406
+ return 0
407
+ fi
408
+ done
409
+ }
410
+
411
+ wait_for_http_ready() {
412
+ local label="$1"
413
+ local method="$2"
414
+ local url="$3"
415
+ require_executable "$(command -v curl || true)" "curl"
416
+
417
+ local attempt
418
+ for attempt in $(seq 1 60); do
419
+ if [[ "${method}" == "POST" ]]; then
420
+ if curl --silent --show-error --fail \
421
+ -X POST \
422
+ -H "Content-Type: application/json" \
423
+ -d '{}' \
424
+ "${url}" >/dev/null 2>&1; then
425
+ echo "${label} is ready: ${url}"
426
+ return 0
427
+ fi
428
+ else
429
+ if curl --silent --show-error --fail "${url}" >/dev/null 2>&1; then
430
+ echo "${label} is ready: ${url}"
431
+ return 0
432
+ fi
433
+ fi
434
+ sleep 2
435
+ done
436
+
437
+ die "Timed out waiting for ${label} to become ready: ${url}"
438
+ }
439
+
440
+ wait_for_service_ready() {
441
+ local svc="$1"
442
+ select_service "${svc}"
443
+ case "${svc}" in
444
+ embedding|llm)
445
+ wait_for_http_ready "${svc}" GET "http://127.0.0.1:${SVC_PORT}/v1/models"
446
+ ;;
447
+ qdrant)
448
+ wait_for_http_ready "${svc}" GET "http://127.0.0.1:${SVC_PORT}/"
449
+ ;;
450
+ agent)
451
+ wait_for_http_ready "${svc}" POST "http://127.0.0.1:${SVC_PORT}/v1/session/start"
452
+ ;;
453
+ *)
454
+ die "Unknown service for readiness check: ${svc}"
455
+ ;;
456
+ esac
457
+ }
458
+
459
+ select_pipeline_stage() {
460
+ local stage="$1"
461
+ PIPELINE_STAGE_LABEL="${stage}"
462
+ PIPELINE_STAGE_LOG_FILE="${LOG_DIR}/${stage}.log"
463
+
464
+ case "${stage}" in
465
+ s1_index)
466
+ PIPELINE_STAGE_SCRIPT="${ROOT_DIR}/pipeline/s1-index/paper-index.sh"
467
+ ;;
468
+ s2_filter)
469
+ PIPELINE_STAGE_SCRIPT="${ROOT_DIR}/pipeline/s2-filter/paper-filter.sh"
470
+ ;;
471
+ s3_fetch)
472
+ PIPELINE_STAGE_SCRIPT="${ROOT_DIR}/pipeline/s3-fetch/paper-fetch.sh"
473
+ ;;
474
+ s4_embedding)
475
+ PIPELINE_STAGE_SCRIPT="${ROOT_DIR}/pipeline/s4-embedding/paper_embedding.sh"
476
+ ;;
477
+ *)
478
+ die "Unknown pipeline stage: ${stage}. Valid: ${PIPELINE_STAGES[*]}"
479
+ ;;
480
+ esac
481
+ }
482
+
483
+ run_pipeline_stage() {
484
+ local stage="$1"
485
+ select_pipeline_stage "${stage}"
486
+ require_file "${PIPELINE_STAGE_SCRIPT}"
487
+
488
+ echo "============================================================"
489
+ echo "Running pipeline stage: ${PIPELINE_STAGE_LABEL}"
490
+ echo " script: ${PIPELINE_STAGE_SCRIPT}"
491
+ echo " log: ${PIPELINE_STAGE_LOG_FILE}"
492
+ echo "============================================================"
493
+
494
+ (
495
+ cd "${ROOT_DIR}"
496
+ env BIOPACIFIC_CONFIG="${CONFIG_FILE}" \
497
+ bash "${PIPELINE_STAGE_SCRIPT}"
498
+ ) 2>&1 | tee "${PIPELINE_STAGE_LOG_FILE}"
499
+ }
500
+
501
+ run_pipeline_sequence() {
502
+ local -a stages=("$@")
503
+ local stage
504
+ for stage in "${stages[@]}"; do
505
+ run_pipeline_stage "${stage}"
506
+ done
507
+ }
508
+
509
+ stop_services_in_order() {
510
+ local -a ordered=("$@")
511
+ local svc
512
+ for svc in "${ordered[@]}"; do
513
+ stop_one "${svc}"
514
+ done
515
+ }
516
+
517
+ run_full_start() {
518
+ local svc
519
+
520
+ validate_vllm_targets "${PREREQ_SERVICES[@]}"
521
+
522
+ echo "Starting prerequisite services: ${PREREQ_SERVICES[*]}"
523
+ for svc in "${PREREQ_SERVICES[@]}"; do
524
+ start_one "${svc}"
525
+ done
526
+
527
+ echo "Waiting for prerequisite services to become ready ..."
528
+ for svc in "${PREREQ_SERVICES[@]}"; do
529
+ wait_for_service_ready "${svc}"
530
+ done
531
+
532
+ echo "Running full pipeline: ${PIPELINE_STAGES[*]}"
533
+ run_pipeline_sequence "${PIPELINE_STAGES[@]}"
534
+
535
+ echo "Starting final service: agent"
536
+ start_one agent
537
+ wait_for_service_ready agent
538
+ }
539
+
540
+ # ---------------------------------------------------------------------------
541
+ # Start / stop / status for a single service
542
+ # ---------------------------------------------------------------------------
543
+
544
+ start_one() {
545
+ local svc="$1"
546
+ select_service "${svc}"
547
+
548
+ local existing_pid
549
+ if existing_pid="$(get_running_pid "${SVC_PID_FILE}" "${SVC_PGREP_PATTERN}")"; then
550
+ echo "${SVC_LABEL} is already running with PID ${existing_pid} (log: ${SVC_LOG_FILE})"
551
+ return 0
552
+ fi
553
+
554
+ if port_in_use "${SVC_PORT}"; then
555
+ die "Port ${SVC_PORT} is already in use (needed by ${SVC_LABEL})."
556
+ fi
557
+
558
+ case "${SVC_KIND}" in
559
+ vllm)
560
+ require_executable "${VLLM_BIN}" "vllm"
561
+ require_dir "${SVC_MODEL_DIR}"
562
+ local tp_size
563
+ tp_size="$(gpu_count "${SVC_GPU}")"
564
+ local -a cmd=(
565
+ env "CUDA_VISIBLE_DEVICES=${SVC_GPU}"
566
+ "${VLLM_BIN}" serve "${SVC_MODEL_DIR}"
567
+ --host "${CFG_SERVICE_HOST}"
568
+ --port "${SVC_PORT}"
569
+ --served-model-name "${SVC_SERVED_NAME}"
570
+ --max-model-len "${SVC_MAX_MODEL_LEN}"
571
+ --gpu-memory-utilization "${SVC_MEM}"
572
+ --tensor-parallel-size "${tp_size}"
573
+ --trust-remote-code
574
+ )
575
+ [[ -n "${SVC_VLLM_RUNNER}" ]] && cmd+=(--runner "${SVC_VLLM_RUNNER}")
576
+ [[ -n "${SVC_DEFAULT_CHAT_TEMPLATE_KWARGS}" ]] && \
577
+ cmd+=(--default-chat-template-kwargs "${SVC_DEFAULT_CHAT_TEMPLATE_KWARGS}")
578
+
579
+ nohup "${cmd[@]}" > "${SVC_LOG_FILE}" 2>&1 &
580
+ local pid=$!
581
+ echo "${pid}" > "${SVC_PID_FILE}"
582
+ echo "${SVC_LABEL} started on port ${SVC_PORT}, GPU(s) ${SVC_GPU} (tp=${tp_size}), PID ${pid}"
583
+ echo " log: ${SVC_LOG_FILE}"
584
+ ;;
585
+ qdrant)
586
+ require_executable "${CFG_QDRANT_BINARY}" "qdrant"
587
+ mkdir -p "${CFG_QDRANT_STORAGE_PATH}"
588
+ local -a cmd=(
589
+ env
590
+ "QDRANT__SERVICE__HOST=${CFG_SERVICE_HOST}"
591
+ "QDRANT__SERVICE__HTTP_PORT=${CFG_QDRANT_PORT}"
592
+ "QDRANT__STORAGE__STORAGE_PATH=${CFG_QDRANT_STORAGE_PATH}"
593
+ "QDRANT__TELEMETRY_DISABLED=true"
594
+ "${CFG_QDRANT_BINARY}"
595
+ )
596
+ ( cd "$(dirname "${CFG_QDRANT_BINARY}")" && \
597
+ nohup "${cmd[@]}" > "${SVC_LOG_FILE}" 2>&1 & echo $! > "${SVC_PID_FILE}" )
598
+ local pid
599
+ pid="$(<"${SVC_PID_FILE}")"
600
+ echo "${SVC_LABEL} started on port ${SVC_PORT}, storage ${CFG_QDRANT_STORAGE_PATH}, PID ${pid}"
601
+ echo " log: ${SVC_LOG_FILE}"
602
+ ;;
603
+ python)
604
+ require_file "${SVC_SCRIPT_PATH}"
605
+ local -a cmd=(
606
+ env
607
+ "BIOPACIFIC_CONFIG=${CONFIG_FILE}"
608
+ "BIOPACIFIC_AGENT_HOST=${CFG_SERVICE_HOST}"
609
+ "${PYTHON_BIN}" "${SVC_SCRIPT_PATH}"
610
+ )
611
+ ( cd "${ROOT_DIR}" && \
612
+ nohup "${cmd[@]}" > "${SVC_LOG_FILE}" 2>&1 & echo $! > "${SVC_PID_FILE}" )
613
+ local pid
614
+ pid="$(<"${SVC_PID_FILE}")"
615
+ echo "${SVC_LABEL} started on port ${SVC_PORT}, script ${SVC_SCRIPT_PATH}, PID ${pid}"
616
+ echo " log: ${SVC_LOG_FILE}"
617
+ ;;
618
+ esac
619
+ }
620
+
621
+ stop_one() {
622
+ local svc="$1"
623
+ select_service "${svc}"
624
+ local pid
625
+ if ! pid="$(get_running_pid "${SVC_PID_FILE}" "${SVC_PGREP_PATTERN}")"; then
626
+ rm -f "${SVC_PID_FILE}"
627
+ echo "${SVC_LABEL} is not running"
628
+ return 0
629
+ fi
630
+
631
+ kill "${pid}" >/dev/null 2>&1 || true
632
+ if wait_for_stop "${pid}"; then
633
+ rm -f "${SVC_PID_FILE}"
634
+ echo "${SVC_LABEL} stopped (PID ${pid})"
635
+ return 0
636
+ fi
637
+ echo "${SVC_LABEL} did not exit after SIGTERM; sending SIGKILL"
638
+ kill -9 "${pid}" >/dev/null 2>&1 || true
639
+ rm -f "${SVC_PID_FILE}"
640
+ echo "${SVC_LABEL} stopped (SIGKILL)"
641
+ }
642
+
643
+ status_one() {
644
+ local svc="$1"
645
+ select_service "${svc}"
646
+ local pid
647
+ if pid="$(get_running_pid "${SVC_PID_FILE}" "${SVC_PGREP_PATTERN}")"; then
648
+ printf "%-10s running pid=%-7s port=%-5s gpu=%s\n" \
649
+ "${SVC_LABEL}" "${pid}" "${SVC_PORT}" "${SVC_GPU}"
650
+ else
651
+ printf "%-10s stopped port=%-5s gpu=%s\n" \
652
+ "${SVC_LABEL}" "${SVC_PORT}" "${SVC_GPU}"
653
+ fi
654
+ echo " log: ${SVC_LOG_FILE}"
655
+ }
656
+
657
+ # ---------------------------------------------------------------------------
658
+ # Dispatch
659
+ # ---------------------------------------------------------------------------
660
+
661
+ usage() {
662
+ cat <<EOF
663
+ Usage:
664
+ $(basename "$0") [start|stop|restart|status] [SERVICE ...]
665
+ $(basename "$0") pipeline [STAGE ...]
666
+
667
+ Services: ${SERVICES[*]}
668
+ Pipeline stages: ${PIPELINE_STAGES[*]}
669
+
670
+ Config file: ${CONFIG_FILE}
671
+ (Override via CONFIG_FILE env var.)
672
+
673
+ Behavior:
674
+ - start / restart with no SERVICE arguments performs the full orchestrated flow:
675
+ start ${PREREQ_SERVICES[*]} -> run ${PIPELINE_STAGES[*]} -> start agent
676
+ - start / stop / restart / status with SERVICE arguments only manages
677
+ background services.
678
+ - pipeline runs one-shot foreground pipeline stages only.
679
+
680
+ Examples:
681
+ $(basename "$0") # full bring-up
682
+ $(basename "$0") start # same as above
683
+ $(basename "$0") start llm qdrant # start only these services
684
+ $(basename "$0") stop # stop all services
685
+ $(basename "$0") stop agent # stop only the agent
686
+ $(basename "$0") restart # full stop + full bring-up
687
+ $(basename "$0") restart embedding # restart one service
688
+ $(basename "$0") status # status of all services
689
+ $(basename "$0") pipeline # run s1 -> s2 -> s3 -> s4
690
+ $(basename "$0") pipeline s3_fetch # run only one pipeline stage
691
+ EOF
692
+ }
693
+
694
+ resolve_service_list() {
695
+ local -a requested=("$@")
696
+ if [[ ${#requested[@]} -eq 0 || "${requested[0]}" == "all" ]]; then
697
+ printf '%s\n' "${SERVICES[@]}"
698
+ return
699
+ fi
700
+ for svc in "${requested[@]}"; do
701
+ local ok=0
702
+ for valid in "${SERVICES[@]}"; do
703
+ if [[ "${svc}" == "${valid}" ]]; then
704
+ ok=1; break
705
+ fi
706
+ done
707
+ [[ ${ok} -eq 1 ]] || die "Unknown service: ${svc}. Valid: ${SERVICES[*]}"
708
+ printf '%s\n' "${svc}"
709
+ done
710
+ }
711
+
712
+ resolve_pipeline_list() {
713
+ local -a requested=("$@")
714
+ if [[ ${#requested[@]} -eq 0 || "${requested[0]}" == "all" ]]; then
715
+ printf '%s\n' "${PIPELINE_STAGES[@]}"
716
+ return
717
+ fi
718
+ local stage valid ok
719
+ for stage in "${requested[@]}"; do
720
+ ok=0
721
+ for valid in "${PIPELINE_STAGES[@]}"; do
722
+ if [[ "${stage}" == "${valid}" ]]; then
723
+ ok=1
724
+ break
725
+ fi
726
+ done
727
+ [[ ${ok} -eq 1 ]] || die "Unknown pipeline stage: ${stage}. Valid: ${PIPELINE_STAGES[*]}"
728
+ printf '%s\n' "${stage}"
729
+ done
730
+ }
731
+
732
+ is_full_orchestration_request() {
733
+ [[ $# -eq 0 ]] && return 0
734
+ [[ $# -eq 1 && "$1" == "all" ]] && return 0
735
+ return 1
736
+ }
737
+
738
+ main() {
739
+ local action="start"
740
+ if [[ $# -gt 0 ]]; then
741
+ case "$1" in
742
+ start|stop|restart|status|pipeline) action="$1"; shift ;;
743
+ -h|--help) usage; exit 0 ;;
744
+ *) # first token is already a service name -> implicit "start"
745
+ ;;
746
+ esac
747
+ fi
748
+
749
+ # Need python to load config.
750
+ use_preferred_runtime "biopacific" # env_name gets overridden once config loads
751
+ load_config
752
+ use_preferred_runtime "${CFG_ENV_NAME}"
753
+
754
+ case "${action}" in
755
+ start)
756
+ if is_full_orchestration_request "$@"; then
757
+ run_full_start
758
+ else
759
+ local -a targets=()
760
+ local t
761
+ mapfile -t targets < <(resolve_service_list "$@")
762
+ validate_vllm_targets "${targets[@]}"
763
+ for t in "${targets[@]}"; do start_one "${t}"; done
764
+ fi
765
+ ;;
766
+ stop)
767
+ local -a stop_targets=()
768
+ local t
769
+ if is_full_orchestration_request "$@"; then
770
+ stop_services_in_order "${STOP_ORDER[@]}"
771
+ else
772
+ mapfile -t stop_targets < <(resolve_service_list "$@")
773
+ for t in "${stop_targets[@]}"; do stop_one "${t}"; done
774
+ fi
775
+ ;;
776
+ restart)
777
+ if is_full_orchestration_request "$@"; then
778
+ stop_services_in_order "${STOP_ORDER[@]}"
779
+ run_full_start
780
+ else
781
+ local -a restart_targets=()
782
+ local t
783
+ mapfile -t restart_targets < <(resolve_service_list "$@")
784
+ for t in "${restart_targets[@]}"; do stop_one "${t}"; done
785
+ validate_vllm_targets "${restart_targets[@]}"
786
+ for t in "${restart_targets[@]}"; do start_one "${t}"; done
787
+ fi
788
+ ;;
789
+ status)
790
+ local -a status_targets=()
791
+ local t
792
+ mapfile -t status_targets < <(resolve_service_list "$@")
793
+ for t in "${status_targets[@]}"; do status_one "${t}"; done
794
+ ;;
795
+ pipeline)
796
+ local -a stages=()
797
+ local stage
798
+ mapfile -t stages < <(resolve_pipeline_list "$@")
799
+ run_pipeline_sequence "${stages[@]}"
800
+ ;;
801
+ *)
802
+ usage; exit 1 ;;
803
+ esac
804
+ }
805
+
806
+ main "$@"