ancor 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.
Files changed (47) hide show
  1. ancor-0.1.0/LICENSE +21 -0
  2. ancor-0.1.0/PKG-INFO +424 -0
  3. ancor-0.1.0/README.md +387 -0
  4. ancor-0.1.0/ancor.egg-info/PKG-INFO +424 -0
  5. ancor-0.1.0/ancor.egg-info/SOURCES.txt +45 -0
  6. ancor-0.1.0/ancor.egg-info/dependency_links.txt +1 -0
  7. ancor-0.1.0/ancor.egg-info/entry_points.txt +2 -0
  8. ancor-0.1.0/ancor.egg-info/requires.txt +19 -0
  9. ancor-0.1.0/ancor.egg-info/top_level.txt +1 -0
  10. ancor-0.1.0/pyproject.toml +63 -0
  11. ancor-0.1.0/setup.cfg +4 -0
  12. ancor-0.1.0/src/agent/api.py +28 -0
  13. ancor-0.1.0/src/agent/file.py +6 -0
  14. ancor-0.1.0/src/agent/local.py +27 -0
  15. ancor-0.1.0/src/agent/manage.py +44 -0
  16. ancor-0.1.0/src/agent/prompt.md +54 -0
  17. ancor-0.1.0/src/cli.py +134 -0
  18. ancor-0.1.0/src/client/_base.py +114 -0
  19. ancor-0.1.0/src/client/documents.py +33 -0
  20. ancor-0.1.0/src/client/files.py +31 -0
  21. ancor-0.1.0/src/client/manage.py +10 -0
  22. ancor-0.1.0/src/config/envs.py +43 -0
  23. ancor-0.1.0/src/config/settings.py +55 -0
  24. ancor-0.1.0/src/database/connect.py +71 -0
  25. ancor-0.1.0/src/database/manage.py +138 -0
  26. ancor-0.1.0/src/exceptions.py +14 -0
  27. ancor-0.1.0/src/handles/documents.py +132 -0
  28. ancor-0.1.0/src/handles/files.py +114 -0
  29. ancor-0.1.0/src/handles/health.py +8 -0
  30. ancor-0.1.0/src/handles/route.py +20 -0
  31. ancor-0.1.0/src/logs.py +3 -0
  32. ancor-0.1.0/src/midlleware/count.py +69 -0
  33. ancor-0.1.0/src/midlleware/midlle.py +61 -0
  34. ancor-0.1.0/src/schema.py +97 -0
  35. ancor-0.1.0/src/server.py +94 -0
  36. ancor-0.1.0/src/utils/chunk.py +69 -0
  37. ancor-0.1.0/src/utils/encode.py +21 -0
  38. ancor-0.1.0/src/utils/manage.py +47 -0
  39. ancor-0.1.0/tests/test_documents_add.py +26 -0
  40. ancor-0.1.0/tests/test_documents_add_from_storage.py +29 -0
  41. ancor-0.1.0/tests/test_documents_delete.py +44 -0
  42. ancor-0.1.0/tests/test_documents_query.py +65 -0
  43. ancor-0.1.0/tests/test_files_delete.py +27 -0
  44. ancor-0.1.0/tests/test_files_download.py +43 -0
  45. ancor-0.1.0/tests/test_files_names.py +20 -0
  46. ancor-0.1.0/tests/test_files_upload.py +42 -0
  47. ancor-0.1.0/tests/test_health.py +16 -0
ancor-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brayan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ancor-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,424 @@
1
+ Metadata-Version: 2.4
2
+ Name: ancor
3
+ Version: 0.1.0
4
+ Summary: API de RAG para PDFs: Qdrant, embeddings e um agente local ou compatível com a API da OpenAI
5
+ Author: Brayan
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/BrayanDevZN/AncorRag
8
+ Project-URL: Repository, https://github.com/BrayanDevZN/AncorRag
9
+ Project-URL: Issues, https://github.com/BrayanDevZN/AncorRag/issues
10
+ Keywords: rag,pdf,qdrant,fastapi,embeddings,llm
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: requests
19
+ Requires-Dist: WatchGuardian
20
+ Requires-Dist: fastapi
21
+ Requires-Dist: uvicorn
22
+ Requires-Dist: typer
23
+ Requires-Dist: pydantic
24
+ Requires-Dist: pyyaml
25
+ Requires-Dist: python-dotenv
26
+ Requires-Dist: qdrant-client
27
+ Requires-Dist: sentence-transformers
28
+ Requires-Dist: langchain-core
29
+ Requires-Dist: langchain-openai
30
+ Requires-Dist: langchain-text-splitters
31
+ Requires-Dist: pypdf
32
+ Requires-Dist: python-multipart
33
+ Provides-Extra: local
34
+ Requires-Dist: transformers; extra == "local"
35
+ Requires-Dist: torch; extra == "local"
36
+ Dynamic: license-file
37
+
38
+ <h1 align="center">ancor</h1>
39
+
40
+ <p align="center">
41
+ <img src="assets/logo.svg" alt="Logo do ancor: uma âncora sobre um documento ligada a pontos de busca vetorial" width="160" height="160">
42
+ </p>
43
+
44
+ <p align="center">
45
+ API de RAG para PDFs: envie documentos, o ancor divide em trechos, gera embeddings e guarda no Qdrant.<br>
46
+ Depois é só perguntar: ele busca os trechos mais parecidos e um modelo de linguagem responde com base neles.<br>
47
+ Roda 100% local, sem serviço externo.
48
+ </p>
49
+
50
+ <p align="center">
51
+ <a href="https://github.com/BrayanDevZN/AncorRag/actions/workflows/build.yaml"><img alt="CI" src="https://github.com/BrayanDevZN/AncorRag/actions/workflows/build.yaml/badge.svg"></a>
52
+ <img alt="100% local" src="https://img.shields.io/badge/100%25-local-2ECC71?style=for-the-badge">
53
+ <img alt="RAG" src="https://img.shields.io/badge/RAG-PDF-FF6F00?style=for-the-badge">
54
+ </p>
55
+
56
+ <p align="center">
57
+ <b>API</b><br>
58
+ <img alt="Python" src="https://img.shields.io/badge/Python-3.12+-3776AB?style=for-the-badge&logo=python&logoColor=FFD43B">
59
+ <img alt="FastAPI" src="https://img.shields.io/badge/FastAPI-0.143-009688?style=for-the-badge&logo=fastapi&logoColor=white">
60
+ <img alt="Uvicorn" src="https://img.shields.io/badge/Uvicorn-0.54-2094F3?style=for-the-badge&logo=gunicorn&logoColor=white">
61
+ <img alt="Pydantic" src="https://img.shields.io/badge/Pydantic-2.14-E92063?style=for-the-badge&logo=pydantic&logoColor=white">
62
+ <img alt="Typer" src="https://img.shields.io/badge/Typer-0.29-2F9C95?style=for-the-badge&logo=typer&logoColor=white">
63
+ </p>
64
+
65
+ <p align="center">
66
+ <b>Busca vetorial e embeddings</b><br>
67
+ <img alt="Qdrant" src="https://img.shields.io/badge/Qdrant-1.20-DC244C?style=for-the-badge&logo=qdrant&logoColor=white">
68
+ <img alt="Sentence Transformers" src="https://img.shields.io/badge/Sentence_Transformers-6.3-FFD21E?style=for-the-badge&logo=huggingface&logoColor=black">
69
+ <img alt="LangChain Text Splitters" src="https://img.shields.io/badge/LangChain_Splitters-1.2-1C3C3C?style=for-the-badge&logo=langchain&logoColor=white">
70
+ <img alt="pypdf" src="https://img.shields.io/badge/pypdf-7.2-B71C1C?style=for-the-badge&logo=adobeacrobatreader&logoColor=white">
71
+ </p>
72
+
73
+ <p align="center">
74
+ <b>Agente (LLM)</b><br>
75
+ <img alt="Transformers" src="https://img.shields.io/badge/Transformers-5.24-FFD21E?style=for-the-badge&logo=huggingface&logoColor=black">
76
+ <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-2.15-EE4C2C?style=for-the-badge&logo=pytorch&logoColor=white">
77
+ <img alt="LangChain" src="https://img.shields.io/badge/LangChain-1.5-1C3C3C?style=for-the-badge&logo=langchain&logoColor=white">
78
+ <img alt="OpenAI API" src="https://img.shields.io/badge/API_OpenAI--compatível-412991?style=for-the-badge&logo=openai&logoColor=white">
79
+ <img alt="Qwen" src="https://img.shields.io/badge/Qwen2.5-3B-615CED?style=for-the-badge&logo=alibabacloud&logoColor=white">
80
+ <img alt="Ollama" src="https://img.shields.io/badge/Ollama-suportado-000000?style=for-the-badge&logo=ollama&logoColor=white">
81
+ </p>
82
+
83
+ <p align="center">
84
+ <b>Utilitários e CI</b><br>
85
+ <img alt="Requests" src="https://img.shields.io/badge/Requests-2.34-2B7BB9?style=for-the-badge&logo=python&logoColor=white">
86
+ <img alt="PyYAML" src="https://img.shields.io/badge/PyYAML-6.0-CB171E?style=for-the-badge&logo=yaml&logoColor=white">
87
+ <img alt="python-dotenv" src="https://img.shields.io/badge/python--dotenv-1.2-ECD53F?style=for-the-badge&logo=dotenv&logoColor=black">
88
+ <img alt="WatchGuardian" src="https://img.shields.io/badge/WatchGuardian-0.2-6E56CF?style=for-the-badge">
89
+ <img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-2088FF?style=for-the-badge&logo=githubactions&logoColor=white">
90
+ </p>
91
+
92
+ ---
93
+
94
+ ## Como funciona
95
+
96
+ ```
97
+ PDF ──► pypdf ──► chunks ──► embeddings ──► Qdrant
98
+ (texto (400 chars, (MiniLM (cosseno)
99
+ por página) overlap 60) multilíngue) │
100
+ ▼
101
+ pergunta ──► embedding ──► busca por similaridade ──► trechos + arquivo + página
102
+ │
103
+ ▼
104
+ agente (Qwen 3B local) ──► resposta + score médio
105
+ ```
106
+
107
+ 1. **Upload:** o PDF chega por `POST /documents/` (ou já está guardado em `/files`).
108
+ 2. **Leitura e divisão:** o `pypdf` extrai o texto de cada página e o `RecursiveCharacterTextSplitter` do LangChain corta em trechos, guardando `file_name`, `page` e `created_at`.
109
+ 3. **Embedding:** o `sentence-transformers` (`paraphrase-multilingual-MiniLM-L12-v2`, 384 dimensões) transforma cada trecho em um vetor.
110
+ 4. **Armazenamento:** os vetores vão para uma collection do Qdrant. Sem `url` no yaml, o Qdrant roda em disco (`src/data/db`); com `url`, usa um servidor.
111
+ 5. **Busca:** a pergunta vira vetor e o Qdrant devolve os trechos mais próximos (`limit` e `score` configuráveis), com filtro opcional por arquivo e página.
112
+ 6. **Resposta:** o agente recebe os textos dos trechos e a pergunta e responde só com base neles. O comportamento dele está em [`src/agent/prompt.md`](src/agent/prompt.md). Sem `agent.base_url`, o modelo roda local com `transformers`; com `base_url`, usa qualquer servidor compatível com a API da OpenAI.
113
+
114
+ Toda requisição passa por um middleware que exige `Authorization: Bearer <api_key>` e aplica limite de requisições por IP e global (por minuto).
115
+
116
+ ## Instalação
117
+
118
+ Requer Python 3.12 ou superior.
119
+
120
+ ```bash
121
+ git clone https://github.com/BrayanDevZN/AncorRag.git
122
+ cd AncorRag
123
+ python -m venv .venv && source .venv/bin/activate
124
+ pip install -e .
125
+ ```
126
+
127
+ A instalação traz o servidor, o comando `ancor` e o cliente Python. Na primeira execução, o modelo de embeddings é baixado do Hugging Face.
128
+
129
+ ## Configuração
130
+
131
+ O servidor lê um yaml (por padrão `rag.yaml` na raiz, ou o caminho passado em `-f`). Só duas seções são obrigatórias: **`database`** e **`config`**, e dentro de `config` só o `api_key`. Todo o resto tem valor padrão.
132
+
133
+ ### Yaml completo (com os padrões)
134
+
135
+ ```yaml
136
+ env_file: # um ou mais .env (o primeiro tem prioridade)
137
+ - .env
138
+
139
+ database:
140
+ url: # vazio = Qdrant local em disco
141
+ db_key: # api key do Qdrant (se usar servidor)
142
+ collection_name: rag_data
143
+ size: 384 # dimensão do vetor (deve bater com o modelo)
144
+
145
+ chunking:
146
+ size: 400
147
+ overlap: 60
148
+
149
+ search:
150
+ limit: 3 # quantos trechos devolver
151
+ score: 0.4 # similaridade mínima
152
+ field: and # filtros file/page combinados com "and" ou "or"
153
+
154
+ model: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 # embeddings
155
+
156
+ agent:
157
+ model_name: Qwen/Qwen2.5-3B-Instruct
158
+ max_tokens: 400
159
+ base_url: # vazio = modelo local
160
+ agent_api_key: # chave do servidor do modelo, se precisar
161
+
162
+ config:
163
+ api_key: "{API_KEY}" # "{NOME}" é lido da variável de ambiente NOME
164
+ host: 0.0.0.0
165
+ port: 8000
166
+ rate_limit: 100 # requisições por minuto, por IP
167
+ global_rate_limit: 10000 # requisições por minuto, no total
168
+ ```
169
+
170
+ ### Yaml mínimo
171
+
172
+ Este já funciona: Qdrant em disco, embeddings e agente locais, tudo no padrão.
173
+
174
+ ```yaml
175
+ database: {}
176
+ config:
177
+ api_key: dev-local-key
178
+ ```
179
+
180
+ ### Campo a campo
181
+
182
+ #### `env_file` (opcional)
183
+
184
+ Lista de arquivos `.env` a carregar. Aceita uma lista ou um único caminho (`env_file: .env`). Se um caminho não existir, o ancor para com erro. Sem `env_file`, ele procura um `.env` na pasta atual. A flag `--env_file` da CLI substitui esta lista.
185
+
186
+ Os `.env` são carregados **antes** de o yaml ser validado, então os `"{NOME}"` do yaml já enxergam as variáveis deles.
187
+
188
+ #### `database` (obrigatório)
189
+
190
+ Onde os vetores ficam guardados (Qdrant).
191
+
192
+ | Campo | Padrão | O que faz |
193
+ |---|---|---|
194
+ | `url` | vazio | Endereço de um servidor Qdrant (ex.: `http://localhost:6333`). **Vazio = Qdrant embutido, gravando em `src/data/db`**, sem precisar subir nada. Se vazio, lê a variável `url_db`. Aceita `"{NOME}"`. |
195
+ | `db_key` | vazio | API key do servidor Qdrant. Se vazio, lê a variável `db_key`. Não precisa no modo em disco. |
196
+ | `collection_name` | `rag_data` | Nome da collection. Use nomes diferentes para separar bases de documentos. |
197
+ | `size` | `384` | Dimensão dos vetores. **Tem que ser igual à dimensão do modelo de `model`.** |
198
+
199
+ #### `chunking`
200
+
201
+ Como o texto de cada página é cortado em trechos.
202
+
203
+ | Campo | Padrão | O que faz |
204
+ |---|---|---|
205
+ | `size` | `400` | Tamanho máximo de cada trecho, em caracteres. Trechos maiores dão mais contexto ao agente, mas deixam a busca menos precisa. |
206
+ | `overlap` | `60` | Quantos caracteres se repetem entre trechos vizinhos, para não cortar uma ideia ao meio. Deve ser menor que `size`. |
207
+
208
+ #### `search`
209
+
210
+ Como a busca responde a uma pergunta.
211
+
212
+ | Campo | Padrão | O que faz |
213
+ |---|---|---|
214
+ | `limit` | `3` | Máximo de trechos devolvidos (e entregues ao agente). |
215
+ | `score` | `0.4` | Similaridade mínima (cosseno, de 0 a 1). Trechos abaixo disso são descartados. Suba para respostas mais seguras, desça se a busca vier vazia. |
216
+ | `field` | `and` | Como combinar os filtros `?file=` e `?page=`: `and` exige os dois; `or` aceita qualquer um. Só aceita `and` ou `or`. |
217
+
218
+ #### `model`
219
+
220
+ Id do modelo de **embeddings** no Hugging Face. Padrão: `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` (384 dimensões, multilíngue). É baixado na primeira execução. Lembre de casar com `database.size`.
221
+
222
+ #### `agent`
223
+
224
+ O modelo de linguagem que lê os trechos e responde. Há dois modos, escolhidos por `base_url`:
225
+
226
+ **Modo local** (`base_url` vazio): o modelo de `model_name` é baixado do Hugging Face e roda na sua máquina com `transformers`. Não precisa de chave. O padrão é o `Qwen/Qwen2.5-3B-Instruct`.
227
+
228
+ ```yaml
229
+ agent:
230
+ model_name: Qwen/Qwen2.5-3B-Instruct
231
+ max_tokens: 400
232
+ ```
233
+
234
+ **Modo API** (`base_url` preenchido): usa qualquer servidor compatível com a API da OpenAI, como Ollama, vLLM, LM Studio ou a própria OpenAI. Nada é baixado.
235
+
236
+ ```yaml
237
+ agent:
238
+ base_url: http://localhost:11434/v1 # Ollama
239
+ model_name: qwen2.5:3b # nome do modelo NESSE servidor
240
+ max_tokens: 400
241
+ ```
242
+
243
+ ```yaml
244
+ agent:
245
+ base_url: https://api.openai.com/v1
246
+ model_name: gpt-4o-mini
247
+ agent_api_key: "{OPENAI_KEY}"
248
+ ```
249
+
250
+ | Campo | Padrão | O que faz |
251
+ |---|---|---|
252
+ | `model_name` | `Qwen/Qwen2.5-3B-Instruct` | No modo local, id do Hugging Face. No modo API, nome do modelo como o servidor o conhece. |
253
+ | `max_tokens` | `400` | Tamanho máximo da resposta gerada. |
254
+ | `base_url` | vazio | Vazio = local. Se vazio, lê a variável `agent_base_url`. Aceita `"{NOME}"`. |
255
+ | `agent_api_key` | vazio | Chave do servidor, se ele exigir (servidores locais como o Ollama não exigem). Se vazio, lê a variável `agent_api_key`. Aceita `"{NOME}"`. |
256
+
257
+ O comportamento do agente (só responder com base nos trechos) está em [`src/agent/prompt.md`](src/agent/prompt.md).
258
+
259
+ #### `config` (obrigatório)
260
+
261
+ O servidor HTTP.
262
+
263
+ | Campo | Padrão | O que faz |
264
+ |---|---|---|
265
+ | `api_key` | **obrigatório** | Chave que os clientes mandam em `Authorization: Bearer <api_key>`. Aceita `"{NOME}"`. |
266
+ | `host` | `0.0.0.0` | Interface de escuta. Use `127.0.0.1` para aceitar só conexões da própria máquina. |
267
+ | `port` | `8000` | Porta. |
268
+ | `rate_limit` | `100` | Requisições por minuto por IP. |
269
+ | `global_rate_limit` | `10000` | Requisições por minuto somando todos os IPs. |
270
+
271
+ ### Variáveis de ambiente (`"{NOME}"`)
272
+
273
+ Um valor escrito como `"{NOME}"` (entre aspas, com chaves) é trocado pela variável de ambiente `NOME`. Se ela não existir, o ancor não sobe e avisa qual faltou. Isso mantém segredos fora do yaml:
274
+
275
+ ```yaml
276
+ config:
277
+ api_key: "{API_KEY}"
278
+ ```
279
+
280
+ ```bash
281
+ # .env
282
+ API_KEY=troque-por-uma-chave-forte
283
+ ```
284
+
285
+ O `"{NOME}"` funciona em `database.url`, `config.api_key`, `agent.base_url` e `agent.agent_api_key`.
286
+
287
+ Além disso, quando estes campos estão vazios, o ancor procura estas variáveis (no ambiente ou nos `.env`):
288
+
289
+ | Campo vazio | Variável lida |
290
+ |---|---|
291
+ | `database.url` | `url_db` |
292
+ | `database.db_key` | `db_key` |
293
+ | `agent.base_url` | `agent_base_url` |
294
+ | `agent.agent_api_key` | `agent_api_key` |
295
+
296
+ ### Exemplos prontos
297
+
298
+ **Tudo local** (nenhum serviço externo):
299
+
300
+ ```yaml
301
+ database: {}
302
+ config:
303
+ api_key: dev-local-key
304
+ host: 127.0.0.1
305
+ ```
306
+
307
+ **Qdrant em servidor + agente no Ollama**, com segredos no `.env`:
308
+
309
+ ```yaml
310
+ env_file: .env
311
+
312
+ database:
313
+ url: "{QDRANT_URL}"
314
+ db_key: "{QDRANT_KEY}" # ou deixe vazio e defina db_key no ambiente
315
+ collection_name: manuais
316
+
317
+ agent:
318
+ base_url: http://localhost:11434/v1
319
+ model_name: qwen2.5:3b
320
+
321
+ config:
322
+ api_key: "{API_KEY}"
323
+ port: 9000
324
+ ```
325
+
326
+ ## Uso
327
+
328
+ ### Linha de comando
329
+
330
+ ```bash
331
+ ancor run # usa ./rag.yaml
332
+ ancor -f outro.yaml run # yaml específico
333
+ ancor --env_file .env run # carrega variáveis de um .env
334
+ ancor -d run # em segundo plano (logs em ancor.log)
335
+ ```
336
+
337
+ | Flag | O que faz |
338
+ |---|---|
339
+ | `-f`, `--file` | Caminho do yaml. Sem ela, usa `rag.yaml` na raiz. |
340
+ | `--env_file` | Caminho do `.env`. Quando usada, substitui a lista `env_file` do yaml. |
341
+ | `-d`, `--detach` | Sobe em segundo plano, espera o servidor responder e mostra a URL e o PID. Para parar: `kill <pid>`. |
342
+
343
+ O `run` é obrigatório e vai por último. Ao iniciar, o servidor loga a URL, por exemplo `Server running at http://localhost:8000`.
344
+
345
+ ### API
346
+
347
+ Todas as rotas pedem o header `Authorization: Bearer <api_key>`.
348
+
349
+ | Método | Rota | Descrição |
350
+ |---|---|---|
351
+ | `GET` | `/health/` | Verifica se a API está no ar |
352
+ | `POST` | `/files/` | Guarda um arquivo bruto no servidor |
353
+ | `GET` | `/files/names` | Lista os arquivos guardados |
354
+ | `GET` | `/files/{file}` | Baixa um arquivo (`?with_content=true` devolve os bytes) |
355
+ | `DELETE` | `/files/{file}` | Apaga um arquivo |
356
+ | `POST` | `/documents/` | Envia um PDF, divide e salva no banco |
357
+ | `POST` | `/documents/file/{filename}` | Salva no banco um arquivo que já está em `/files` |
358
+ | `GET` | `/documents/?file=&page=` | Pergunta aos documentos. O corpo é a pergunta, como texto JSON, e a resposta é `{"response": texto do agente, "score": média dos scores dos trechos}` |
359
+
360
+ ```bash
361
+ curl -H "Authorization: Bearer $API_KEY" -F "file=@manual.pdf" http://localhost:8000/documents/
362
+
363
+ curl -X GET -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
364
+ -d '"quanto custa o café expresso?"' "http://localhost:8000/documents/?file=manual.pdf&page=2"
365
+ ```
366
+
367
+ ### Cliente Python
368
+
369
+ O pacote traz um cliente que já envia a api key em todas as chamadas.
370
+
371
+ ```python
372
+ from src.client.manage import Manage
373
+
374
+ client = Manage(url="http://localhost:8000", api_key="minha-chave")
375
+
376
+ client.health() # testa a conexão (tenta 3 vezes)
377
+
378
+ client.add(path="manual.pdf") # lê o arquivo e envia
379
+ client.add(name="manual.pdf", content=pdf_bytes) # ou envia bytes brutos
380
+
381
+ resposta = client.query("quanto custa o café expresso?", file="manual.pdf", page=2)
382
+ print(resposta.json()) # {"response": texto do agente, "score": média dos scores}
383
+
384
+ client.upload(path="manual.pdf") # guarda o arquivo bruto
385
+ client.names().json() # ["manual.pdf"]
386
+ client.download("manual.pdf").content
387
+ client.delete("manual.pdf")
388
+ client.add_from_storage("manual.pdf") # salva no banco um arquivo já guardado
389
+ ```
390
+
391
+ Os métodos devolvem a `requests.Response`. O `query` espera até 300 s por padrão (`timeout=`). Erros de rede ou de uso viram `ClientAncorError`.
392
+
393
+ ## Estrutura
394
+
395
+ ```
396
+ src/
397
+ ├── cli.py # comando ancor
398
+ ├── server.py # monta o FastAPI (objetos, rotas, middleware, uvicorn)
399
+ ├── schema.py # modelo do yaml, com os valores padrão
400
+ ├── config/ # leitura do yaml e do .env
401
+ ├── database/ # Qdrant: conexão, inserção e busca
402
+ ├── agent/ # agente que responde (local ou API) e prompt.md
403
+ ├── utils/ # leitura do PDF, chunks e embeddings
404
+ ├── midlleware/ # api key e rate limit
405
+ ├── handles/ # rotas: /documents, /files, /health
406
+ └── client/ # cliente Python (um arquivo por rota)
407
+ tests/ # um arquivo por caso de uso + main.py
408
+ ```
409
+
410
+ ## Testes
411
+
412
+ Os testes chamam a API de verdade pelo cliente, então o servidor precisa estar rodando em `http://127.0.0.1:8000` com a chave `dev-local-key` (a do `rag.yaml` de exemplo).
413
+
414
+ ```bash
415
+ ancor -d run # sobe o servidor em segundo plano
416
+ python -m tests.main # roda todos os arquivos de teste
417
+ python -m tests.main health files # só os arquivos cujo nome contém essas palavras
418
+ ```
419
+
420
+ Cada teste imprime a resposta retornada. Se algum falhar, o erro é levantado e a execução para. O `tests/sample.pdf` é um PDF fictício de 3 páginas usado nos testes.
421
+
422
+ ## CI
423
+
424
+ O workflow [`build.yaml`](.github/workflows/build.yaml) roda a cada push e pull request na `main`: instala as dependências e o pacote, sobe o servidor com `ancor -d run` e executa `python -m tests.main`.