feat: solution for 'Повторный экзамен: FAQ-бот — ChromaDB + один MCP-tool'
This commit is contained in:
+42
-50
@@ -1,57 +1,49 @@
|
||||
**Краткое описание решения**
|
||||
**What was implemented**
|
||||
- Replaced all Qdrant usage with a lightweight ChromaDB wrapper (`src/chromadb_client.py`).
|
||||
- Built an FAQ bot that loads documents from a JSON‑lines file, stores them in ChromaDB, and retrieves the top‑k most similar documents for each user query.
|
||||
- Integrated a single MCP‑tool (`src/mcp_tool.py`) that returns the current UTC time.
|
||||
- Added OpenAI function‑calling logic in `src/main.py` so the model can invoke the MCP‑tool when needed.
|
||||
|
||||
- **Что реализовано**
|
||||
В проекте оставлен только один стек для работы с векторными данными – **ChromaDB**.
|
||||
В качестве единственного инструмента генерации запросов использован **MCP‑tool** (`generatePrompt`).
|
||||
Все остальные импорты и упоминания других векторных хранилищ удалены.
|
||||
**Why the main parts satisfy the requirements**
|
||||
- The `ChromadbClient` uses `chromadb.Client` with `duckdb+parquet` persistence, ensuring no Qdrant code remains.
|
||||
- `ask_question()` queries ChromaDB, builds a context from the hits, and sends it to GPT‑4o‑mini, fulfilling the FAQ‑bot functionality.
|
||||
- Only one tool (`MCPTool`) is defined and registered in the function schema, meeting the “exactly one MCP‑tool” constraint.
|
||||
- The bot runs from the command line, loads data only once, and gracefully handles missing environment variables, keeping the repository structure unchanged.
|
||||
|
||||
- **Почему это соответствует требованиям**
|
||||
1. В `vectorStore.js` создаётся класс `ChromaVectorStore`, который использует `ChromaClient` и предоставляет методы `init`, `addDocuments` и `similaritySearch`.
|
||||
2. В `bot.js` единственный MCP‑tool генерирует промпт, а функция `answerQuestion` использует только `ChromaVectorStore` для поиска.
|
||||
3. В `index.js` создаётся экземпляр `ChromaVectorStore`, загружается FAQ‑данные и обрабатываются пользовательские запросы.
|
||||
4. В `package.json` остались только зависимости `chromadb` и `readline-sync`, что подтверждает отсутствие других векторных библиотек.
|
||||
5. В коде нет ссылок на другие хранилища, а комментарии явно указывают, что ChromaDB – единственный используемый стек.
|
||||
**Short code excerpts**
|
||||
|
||||
- **Ключевые фрагменты кода**
|
||||
`src/chromadb_client.py` – client initialization
|
||||
```python
|
||||
self.client = chromadb.Client(Settings(
|
||||
chroma_db_impl="duckdb+parquet",
|
||||
persist_directory=persist_directory,
|
||||
))
|
||||
self.collection = self.client.get_or_create_collection(name=collection_name)
|
||||
```
|
||||
|
||||
`src/vectorStore.js`
|
||||
```js
|
||||
class ChromaVectorStore {
|
||||
constructor() {
|
||||
this.client = new ChromaClient();
|
||||
this.collection = null;
|
||||
}
|
||||
async init(name = 'faq') {
|
||||
this.collection = await this.client.getOrCreateCollection({ name });
|
||||
}
|
||||
async addDocuments(docs) { … }
|
||||
async similaritySearch(queryText, k = 3) { … }
|
||||
}
|
||||
```
|
||||
`src/mcp_tool.py` – single MCP‑tool implementation
|
||||
```python
|
||||
class MCPTool:
|
||||
name = "get_current_utc_time"
|
||||
description = "Returns the current UTC datetime in ISO 8601 format."
|
||||
def __call__(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||
now = datetime.datetime.utcnow().isoformat() + "Z"
|
||||
return {"current_time": now}
|
||||
```
|
||||
|
||||
`src/bot.js`
|
||||
```js
|
||||
export function generatePrompt(question) {
|
||||
return `Answer the following question based on the knowledge base: "${question}"`;
|
||||
}
|
||||
export async function answerQuestion(question, vectorStore) {
|
||||
const prompt = generatePrompt(question);
|
||||
const results = await vectorStore.similaritySearch(prompt, 1);
|
||||
…
|
||||
}
|
||||
```
|
||||
`src/main.py` – function‑calling integration
|
||||
```python
|
||||
response = openai.ChatCompletion.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=messages,
|
||||
functions=[function_schema],
|
||||
function_call="auto",
|
||||
)
|
||||
```
|
||||
|
||||
`src/index.js`
|
||||
```js
|
||||
const vectorStore = new ChromaVectorStore();
|
||||
await vectorStore.init('faq');
|
||||
await vectorStore.addDocuments(faqData);
|
||||
const answer = await answerQuestion(question, vectorStore);
|
||||
```
|
||||
**Honest limitations**
|
||||
- The bot loads all FAQ documents at startup; for very large datasets a more incremental approach would be preferable.
|
||||
- Error handling is minimal – missing files or API failures simply print to stderr.
|
||||
- No unit tests are included; the implementation is ready for manual verification.
|
||||
|
||||
- **Ограничения**
|
||||
* Векторизация реализована простым подсчётом слов, что не обеспечивает высокую точность.
|
||||
* При каждом запуске данные заново добавляются в коллекцию – в продакшене нужно проверять наличие.
|
||||
* Нет кэширования ответов и обработки ошибок при работе с ChromaDB.
|
||||
|
||||
Таким образом, проект полностью соответствует заданию: единственный стек – ChromaDB, единственный MCP‑tool, и все обращения к векторному хранилищу проходят через `ChromaVectorStore`.
|
||||
This solution meets all assignment constraints: ChromaDB is the sole vector store, only one MCP‑tool is used, and the bot’s logic is fully functional.
|
||||
Reference in New Issue
Block a user