Skip to content

Commit c5ff473

Browse files
committed
v2.5.0a12
1 parent d150e42 commit c5ff473

File tree

11 files changed

+138
-78
lines changed

11 files changed

+138
-78
lines changed

.dockerignore

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22

33
docs
44
.git
5-
config.json
6-
Pipfile
7-
Pipfile.lock
85

96
# Cache
107
.mypy_cache
@@ -26,8 +23,5 @@ Pipfile.lock
2623
.venv
2724
venv*
2825
aienv*
29-
apienv*
30-
appenv*
31-
llmenv*
3226

3327
.ipynb_checkpoints

Dockerfile

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,21 @@ RUN groupadd -g 61000 ${USER} \
1010

1111
WORKDIR ${APP_DIR}
1212

13-
# Copy requirements and install
14-
COPY requirements.txt pyproject.toml ./
13+
# Copy requirements.txt
14+
COPY requirements.txt ./
15+
16+
# Install requirements
1517
RUN --mount=type=cache,target=/root/.cache/uv \
1618
uv pip sync requirements.txt --system
1719

1820
# Copy project files
1921
COPY . .
2022

21-
COPY scripts /scripts
23+
# Set permissions for the /app directory
24+
RUN chown -R ${USER}:${USER} ${APP_DIR}
25+
26+
# Switch to non-root user
2227
USER ${USER}
23-
ENTRYPOINT ["/scripts/entrypoint.sh"]
28+
29+
ENTRYPOINT ["/app/scripts/entrypoint.sh"]
2430
CMD ["chill"]

README.md

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,41 @@
22

33
This repo contains the code for running phidata demo-agents in 2 environments:
44

5-
1. `dev`: A development environment running locally on docker
6-
2. `prd`: A production environment running on AWS ECS
5+
1. **dev**: A development environment running locally on docker
6+
2. **prd**: A production environment running on AWS ECS
77

88
## Setup Workspace
99

1010
1. Clone the git repo
1111

1212
> from the `demo-agents` dir:
1313
14-
2. Create + activate a virtual env:
14+
2. Install workspace and activate the virtual env:
1515

1616
```sh
17-
python3 -m venv aienv
18-
source aienv/bin/activate
17+
./scripts/install.sh
18+
source .venv/bin/activate
1919
```
2020

21-
3. Install `phidata`:
22-
23-
```sh
24-
pip install phidata
25-
```
26-
27-
4. Setup workspace:
21+
3. Setup workspace:
2822

2923
```sh
3024
phi ws setup
3125
```
3226

33-
5. Copy `workspace/example_secrets` to `workspace/secrets`:
27+
4. Copy `workspace/example_secrets` to `workspace/secrets`:
3428

3529
```sh
3630
cp -r workspace/example_secrets workspace/secrets
3731
```
3832

39-
6. Optional: Create `.env` file:
33+
5. Optional: Create `.env` file:
4034

4135
```sh
4236
cp example.env .env
4337
```
4438

45-
## Run Api locally
39+
## Run Demo Agents locally
4640

4741
1. Install [docker desktop](https://www.docker.com/products/docker-desktop)
4842

@@ -62,7 +56,7 @@ export OPENAI_API_KEY=sk-***
6256
phi ws up
6357
```
6458

65-
Open [localhost:8000/docs](http://localhost:8000/docs) to view the FastApi docs.
59+
Open [localhost:8000/docs](http://localhost:8000/docs) to view the demo agents api.
6660

6761
4. Stop the workspace using:
6862

db/README.md

Lines changed: 83 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,77 @@
1-
## Running database migrations
1+
## Managing database migrations
22

3-
Steps to migrate the database using alembic:
3+
This guide outlines the steps to manage database migrations for your workspace.
44

5-
1. Add/update SqlAlchemy tables in the `db/tables` directory.
6-
2. Import the SqlAlchemy class in the `db/tables/__init__.py` file.
7-
3. Create a database revision using: `alembic -c db/alembic.ini revision --autogenerate -m "Revision Name"`
8-
4. Migrate database using: `alembic -c db/alembic.ini upgrade head`
5+
## Table of Contents
96

10-
> Note: Set Env Var `MIGRATE_DB = True` to run the database migration in the entrypoint script at container startup.
7+
- [Prerequisites](#prerequisites)
8+
- [Running Migrations](#running-migrations)
9+
- [Create a Database Revision](#create-a-database-revision)
10+
- [Migrate the Database](#migrate-the-database)
11+
- [Environment-specific Instructions](#environment-specific-instructions)
12+
- [Development Environment](#development-environment)
13+
- [Production Environment](#production-environment)
14+
- [Creating the Migrations Directory](#creating-the-migrations-directory)
15+
- [Additional Resources](#additional-resources)
1116

12-
Checkout the docs on [adding database tables](https://docs.phidata.com/day-2/database-tables).
17+
---
18+
19+
## Prerequisites
20+
21+
1. **Update Tables**: To run a migration, first we need to add or update SQLAlchemy tables in the `db/tables` directory.
22+
2. **Import Classes**: Ensure that the SQLAlchemy table classes are imported in `db/tables/__init__.py`.
23+
24+
## Running Migrations
25+
26+
### Create a Database Revision
27+
28+
After you have added or updated your table, create a new database revision using:
29+
30+
```bash
31+
alembic -c db/alembic.ini revision --autogenerate -m "Your Revision Message"
32+
```
33+
34+
> **Note:** Replace `"Your Revision Message"` with a meaningful description of the changes.
35+
36+
### Migrate the Database by applying the revision
37+
38+
Run the migration to update the database schema:
39+
40+
```bash
41+
alembic -c db/alembic.ini upgrade head
42+
```
43+
44+
## Environment-specific Instructions
1345

14-
## Creat a database revision using alembic
46+
Let's explore the migration process for both development and production environments.
1547

16-
Run the alembic command to create a database migration in the dev container:
48+
### Development Environment
49+
50+
**Create Revision and Migrate:**
1751

1852
```bash
19-
docker exec -it ai-api-dev alembic -c db/alembic.ini revision --autogenerate -m "Initialize DB"
53+
docker exec -it demo-agents-api alembic -c db/alembic.ini revision --autogenerate -m "Your Revision Message"
54+
docker exec -it demo-agents-api alembic -c db/alembic.ini upgrade head
2055
```
2156

22-
## Migrate development database
57+
### Production Environment
58+
59+
#### Option 1: Automatic Migration at Startup
2360

24-
Run the alembic command to migrate the dev database:
61+
Set the environment variable `MIGRATE_DB=True` to run migrations automatically when the container starts. This executes:
2562

2663
```bash
27-
docker exec -it ai-api-dev alembic -c db/alembic.ini upgrade head
64+
alembic -c db/alembic.ini upgrade head
2865
```
2966

30-
## Migrate production database
67+
#### Option 2: Manual Migration via SSH
3168

32-
1. Recommended: Set Env Var `MIGRATE_DB = True` which runs `alembic -c db/alembic.ini upgrade head` from the entrypoint script at container startup.
33-
2. **OR** you can SSH into the production container to run the migration manually
69+
SSH into the production container and run the migration manually:
3470

3571
```bash
36-
ECS_CLUSTER=ai-api-prd-cluster
37-
TASK_ARN=$(aws ecs list-tasks --cluster ai-api-prd-cluster --query "taskArns[0]" --output text)
38-
CONTAINER_NAME=ai-api-prd
72+
ECS_CLUSTER=demo-agents-cluster
73+
TASK_ARN=$(aws ecs list-tasks --cluster $ECS_CLUSTER --query "taskArns[0]" --output text)
74+
CONTAINER_NAME=demo-agents-api
3975

4076
aws ecs execute-command --cluster $ECS_CLUSTER \
4177
--task $TASK_ARN \
@@ -44,21 +80,35 @@ aws ecs execute-command --cluster $ECS_CLUSTER \
4480
--command "alembic -c db/alembic.ini upgrade head"
4581
```
4682

47-
---
83+
## Creating the Migrations Directory
4884

49-
## How to create the migrations directory
85+
> **Note:** These steps have already been completed and are included here for reference.
5086
51-
> This has already been run and is described here for completeness
87+
1. **Access the Development Container:**
5288

53-
```bash
54-
docker exec -it ai-api-dev zsh
89+
```bash
90+
docker exec -it demo-agents-api zsh
91+
```
5592

56-
cd db
57-
alembic init migrations
58-
```
93+
2. **Initialize Alembic Migrations:**
94+
95+
```bash
96+
cd db
97+
alembic init migrations
98+
```
99+
100+
3. **Post-Initialization Steps:**
101+
102+
- **Update `alembic.ini`:**
103+
- Set `script_location = db/migrations`.
104+
- **Update `migrations/env.py`:**
105+
- Modify according to the [Alembic Autogenerate Documentation](https://alembic.sqlalchemy.org/en/latest/autogenerate.html).
106+
107+
## Additional Resources
108+
109+
- **Adding Database Tables:** Refer to the [Phidata documentation](https://docs.phidata.com/day-2/database-tables) for detailed instructions on adding database tables.
110+
- **Environment Variable Note:** Setting `MIGRATE_DB=True` ensures that the migration command runs from the entrypoint script when the container starts.
111+
112+
---
59113

60-
- After running the above commands, the `db/migrations` directory should be created.
61-
- Update `alembic.ini`
62-
- set `script_location = db/migrations`
63-
- uncomment `black` hook in `[post_write_hooks]`
64-
- Update `migrations/env.py` file following [this link](https://alembic.sqlalchemy.org/en/latest/autogenerate.html)
114+
Feel free to customize this README further to suit your project's needs.

db/session.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
1+
from typing import Generator
2+
13
from sqlalchemy.engine import Engine, create_engine
24
from sqlalchemy.orm import Session, sessionmaker
35

46
from db.settings import db_settings
57

68
# Create SQLAlchemy Engine using a database URL
7-
db_url = db_settings.get_db_url()
9+
db_url: str = db_settings.get_db_url()
810
db_engine: Engine = create_engine(db_url, pool_pre_ping=True)
911

1012
# Create a SessionLocal class
1113
# https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-sessionlocal-class
1214
SessionLocal: sessionmaker[Session] = sessionmaker(autocommit=False, autoflush=False, bind=db_engine)
1315

1416

15-
def get_db():
17+
def get_db() -> Generator[Session, None, None]:
1618
"""
1719
Dependency to get a database session.
1820
19-
https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-dependency
21+
Yields:
22+
Session: An SQLAlchemy database session.
2023
"""
21-
22-
db = SessionLocal()
24+
db: Session = SessionLocal()
2325
try:
2426
yield db
2527
finally:

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ dependencies = [
1414
"mypy",
1515
"openai",
1616
"pgvector",
17-
"phidata[aws]==2.5.0a11",
17+
"phidata[aws]==2.5.0a12",
1818
"psycopg[binary]",
1919
"pypdf",
2020
"pytest",

requirements.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
# This file was autogenerated by uv via the following command:
2-
# ./scripts/generate_requirements.sh
2+
# ./scripts/generate_requirements.sh upgrade
33
alembic==1.13.3
44
annotated-types==0.7.0
55
anyio==4.6.0
66
beautifulsoup4==4.12.3
7-
boto3==1.35.37
8-
botocore==1.35.37
7+
boto3==1.35.38
8+
botocore==1.35.38
99
certifi==2024.8.30
1010
charset-normalizer==3.4.0
1111
click==8.1.7
@@ -44,7 +44,7 @@ packaging==24.1
4444
pandas==2.2.3
4545
peewee==3.17.6
4646
pgvector==0.3.5
47-
phidata==2.5.0a11
47+
phidata==2.5.0a12
4848
platformdirs==4.3.6
4949
pluggy==1.5.0
5050
psycopg==3.1.19

scripts/entrypoint.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ if [[ "$WAIT_FOR_REDIS" = true || "$WAIT_FOR_REDIS" = True ]]; then
2727
fi
2828

2929
############################################################################
30-
# Install dependencies
30+
# Install requirements
3131
############################################################################
3232

3333
if [[ "$INSTALL_REQUIREMENTS" = true || "$INSTALL_REQUIREMENTS" = True ]]; then

utils/dttm.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ def current_utc() -> datetime:
55
return datetime.now(timezone.utc)
66

77

8-
def current_utc_str() -> str:
9-
return current_utc().strftime("%Y-%m-%dT%H:%M:%S")
8+
def current_utc_str(format: str = "%Y-%m-%dT%H:%M:%S.%fZ") -> str:
9+
return current_utc().strftime(format)

utils/log.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
import logging
2+
from typing import Optional
23

34

4-
def build_logger(logger_name: str) -> logging.Logger:
5+
def build_logger(
6+
logger_name: str,
7+
log_level: int = logging.INFO,
8+
show_time: bool = False,
9+
rich_tracebacks: bool = False,
10+
tracebacks_show_locals: bool = False
11+
) -> logging.Logger:
512
from rich.logging import RichHandler
613

7-
rich_handler = RichHandler(show_time=False, rich_tracebacks=False, tracebacks_show_locals=False)
14+
rich_handler = RichHandler(
15+
show_time=show_time,
16+
rich_tracebacks=rich_tracebacks,
17+
tracebacks_show_locals=tracebacks_show_locals
18+
)
819
rich_handler.setFormatter(
920
logging.Formatter(
1021
fmt="%(message)s",
@@ -14,9 +25,14 @@ def build_logger(logger_name: str) -> logging.Logger:
1425

1526
_logger = logging.getLogger(logger_name)
1627
_logger.addHandler(rich_handler)
17-
_logger.setLevel(logging.INFO)
28+
_logger.setLevel(log_level)
1829
_logger.propagate = False
1930
return _logger
2031

2132

22-
logger: logging.Logger = build_logger("ai-api")
33+
# Default logger instance
34+
logger: logging.Logger = build_logger("demo-agents")
35+
36+
# Function to get or create a logger
37+
def get_logger(name: Optional[str] = None) -> logging.Logger:
38+
return logger if name is None else build_logger(name)

0 commit comments

Comments
 (0)