Skip to main content

Brevia

Il repository contiene un progetto di LLM API minimale in Python basato su LangChain per l'interazione con LLM e FastAPI per l'interfaccia API.

Requirements

E' necessaria una versione di Python 3.10 o superiore e Poetry

Si consiglia di utilizzare il virtualenv nel progetto. Verifica le impostazioni con

poetry config --list

Verifica che la configurazione virtualenvs.in-project sia true altrimenti lancia:

poetry config virtualenvs.in-project true

Setup

  • installa le dipendenze lanciando poetry install, verrà automaticamente creato un virtualenv nel folder .venv
  • attiva quindi il virtualenv lanciando il comando poetry shell
  • copia il file .env.sample in .env e valorizza le variabili di ambiente, soprattutto OPENAI_API_KEY con la secret key di OpenAI e PGVECTOR_* vedi la sezione Database

Aggiornamento pacchetti

Si usa poetry update che aggiornerà il file di lock poetry.lock Per cambiare versioni delle dipendenze si può anche modificare direttamente pyproject.toml nella seziona [tool.poetry.dependencies]

Database

Lancia docker compose --profile admin up per fare partire le immagini docker di postgres+pgvector e pgadmin.

Col browser apri pgadmin all'indirizzo http://localhost:4000

La porta 4000 è configurabile con la var di ambiente PGADMIN_PORT nel file .env.

  • fai login su pgadmin con credenziali PGADMIN_DEFAULT_* del file .env
  • crea una connessione con Add New Server impostando
    • in General brevia o altro nome a scelta (PGVECTOR_DATABASE)
    • in Connection come host name pgdatabase e scegli uno Username a Password (PGVECTOR_USER, PGVECTOR_PASSWORD)

Lancia le migrations per creare lo schema iniziale con Alembic

alembic upgrade head

Test setup

Per verificare che il setup sia corretto lanciare

python brevia/scripts/csv_import.py data/test_min_dataset.csv test

Per creare indicizzazione da un CSV di test con una sola riga. Se alla fine in output trovate Index collection {name} updated with {n} documents and {n} texts allora è tutto ok.

Import/export di collections

Per esportare usare lo script export_collection.pydal virtual env

python export_collection.py /path/to/folder collection

Dove

  • /path/to/folder è il path dove verranno creati i 2 file CSV, uno per record di collection e altro con embeddings
  • collection è il nome della collection

Per esportare usare lo script import_collection.pydal virtual env

python import_collection.py /path/to/folder biologia

Dove

  • /path/to/folder è il path dove sono cercati i 2 file CSV da caricare, uno per record di collection e altro con embeddings
  • collection è il nome della collection

NB: per questi script è necessario il client postgres psql, i parametri di connessione saranno letti da var di ambiente (file .env)

API server

Per far partire il server, digita il seguente comando da virtualenv:

uvicorn main:app --reload

Il server inizierà ad eseguire sulla porta 8000.

Docker

Per lanciare l'immagine docker delle API insieme al servizio Postgres usa

docker compose --profile api up

Per lanciare l'immagine docker di PgAdmin insieme a Postgres usa

docker compose --profile admin up

Per lanciare l'immagine docker dell'APP e delle API insieme a Postgres

docker compose --profile app up

La versione dell'immagine docker utilizzata è definita nel file .env nelle variabili d'ambiente API_VERSION per le API e APP_VERSION per l'app

Tracing log

Per abilitare la funzionalità di trace delle chiamate, integrata in langchain aggiungere/scommentare la variabile di sistema su app.py:

environ["LANGCHAIN_HANDLER"] = langchain

assicurandosi che venga eseguita prima di qualsiasi operazione sulle librerie di langchain.

Far partire il server tramite immagini docker dalla console:

langchain-server

Navigare su http://localhost:4173/ per visualizzare il pannello di controllo dei trace e utilizzare la sessione di default.

Per cambiare il nome della sessione impostare:

.environ ["LANGCHAIN_SESSION"] = "my_session" # Assicurandoti che questa sessione esista effettivamente. È possibile creare una nuova sessione nell'interfaccia utente.

Mentre per cambiare dinamicamente sessione nel codice NON impostare la variabile d'ambiente LANGCHAIN_SESSION, usa invece:

langchain.set_tracing_callback_manager(session_name = "my_session")

Access Tokens

There is a built-in basic support for access tokens for API security

Access tokens are actively checked via Authoritazion: Bearer <token> header if a TOKENS_SECRET env variable has been set. You may then generate a new access token using:

poetry run create_token --user {user} --duration {minutes}

If the env TOKENS_SECRET variable is set token verification is automatically performed on every endpoint using brevia.dependencies.get_dependencies in its dependencies.

The recommended way yo generate TOKENS_SECRET is by using openssl via cli like

openssl rand -hex 32

You can also define a list of valid users as a comma separated string in the TOKENS_USERS env variable.

Setting it like TOKENS_USERS="brevia,gustavo" means that only brevia and gustavo are considered valid users names. Remember to use double quotes in a .env file.

Metadata

Release files for brevia 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brevia 0.0.1
File Size Uploaded Provenance Actions
brevia-0.0.1.tar.gz 33.7 kB Without provenance Details for brevia-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brevia 0.0.1
File Interpreter ABI Platform Actions
brevia-0.0.1-py3-none-any.whl Python 3 none any Details for brevia-0.0.1-py3-none-any.whl

Total release size: 81.0 kB

Release files / brevia-0.0.1.tar.gz

Download URL brevia-0.0.1.tar.gz
Size 33.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c3174c52ceb8c3a2fbadb79f18c6b5e66d59939dc4c550d316d90e4df58bd84c
BLAKE2b-256 checksum
How to use checksums
bf00f1f7a04b8244801a923a272a3f8cf8ce720b0772b3901afc28bd1735f140
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.10.6 Linux/5.15.0-84-generic

Release files / brevia-0.0.1-py3-none-any.whl

Download URL brevia-0.0.1-py3-none-any.whl
Size 47.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6e9b08154b962d034dc3237ab4f2c0a857f198e28d084f975123fa0a903228f0
BLAKE2b-256 checksum
How to use checksums
90fff0d9e3c628fa6e097798d109f2e2287e4667c4c02f4ccef9b1c45171a557
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.10.6 Linux/5.15.0-84-generic

Security for brevia 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page