Skip to content

Commit 3e42e82

Browse files
committed
Move to ruff format
1 parent ed4fcc6 commit 3e42e82

16 files changed

+21
-49
lines changed

.devcontainer/devcontainer.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
"ms-python.python",
3030
"ms-python.vscode-pylance",
3131
"charliermarsh.ruff",
32-
"ms-python.black-formatter",
3332
"mtxr.sqltools",
3433
"mtxr.sqltools-driver-pg",
3534
"ms-vscode.vscode-node-azure-pack",
@@ -45,7 +44,7 @@
4544
"editor.codeActionsOnSave": {
4645
"source.fixAll": "explicit"
4746
},
48-
"editor.defaultFormatter": "ms-python.black-formatter"
47+
"editor.defaultFormatter": "charliermarsh.ruff"
4948
},
5049
"files.exclude": {
5150
".ruff_cache": true,

.github/PULL_REQUEST_TEMPLATE.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,4 @@ See [CONTRIBUTING.md](https://github.com/Azure-Samples/rag-postgres-openai-pytho
3232
- [ ] I added tests that prove my fix is effective or that my feature works
3333
- [ ] I ran `python -m pytest --cov` to verify 100% coverage of added lines
3434
- [ ] I ran `python -m mypy` to check for type errors
35-
- [ ] I either used the pre-commit hooks or ran `ruff` and `black` manually on my code.
36-
35+
- [ ] I either used the pre-commit hooks or ran `ruff` manually on my code.

.github/workflows/python-code-quality.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@ jobs:
2121
pip install -r requirements-dev.txt
2222
- name: Lint with ruff
2323
run: ruff check .
24-
- name: Check formatting with black
25-
run: black . --check --verbose
24+
- name: Check formatting with ruff
25+
run: ruff format --check .

.pre-commit-config.yaml

+5-5
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ repos:
88
- repo: https://github.com/astral-sh/ruff-pre-commit
99
rev: v0.1.0
1010
hooks:
11-
- id: ruff
12-
- repo: https://github.com/psf/black
13-
rev: 23.9.1
14-
hooks:
15-
- id: black
11+
# Run the linter.
12+
- id: ruff
13+
args: [ --fix ]
14+
# Run the formatter.
15+
- id: ruff-format

CONTRIBUTING.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ Compile the JavaScript:
9393
This codebase includes several languages: TypeScript, Python, Bicep, Powershell, and Bash.
9494
Code should follow the standard conventions of each language.
9595

96-
For Python, you can enforce the conventions using `ruff` and `black`.
96+
For Python, you can enforce the conventions using `ruff`.
9797

9898
Install the development dependencies:
9999

@@ -104,13 +104,13 @@ python3 -m pip install -r requirements-dev.txt
104104
Run `ruff` to lint a file:
105105

106106
```
107-
python3 -m ruff <path-to-file>
107+
python3 -m ruff check <path-to-file>
108108
```
109109

110-
Run `black` to format a file:
110+
Run `ruff` to format a file:
111111

112112
```
113-
python3 -m black <path-to-file>
113+
python3 -m ruff format <path-to-file>
114114
```
115115

116-
If you followed the steps above to install the pre-commit hooks, then you can just wait for those hooks to run `ruff` and `black` for you.
116+
If you followed the steps above to install the pre-commit hooks, then you can just wait for those hooks to run `ruff` for you.

pyproject.toml

-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,3 @@ ignore = ["D203"]
88

99
[tool.ruff.lint.isort]
1010
known-first-party = ["fastapi_app"]
11-
12-
[tool.black]
13-
line-length = 120
14-
target-version = ["py311"]

requirements-dev.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
-r src/requirements.txt
22
ruff
3-
black
43
pre-commit
5-
pip-tools
4+
pip-tools

src/fastapi_app/api_routes.py

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
@router.post("/chat")
1313
async def chat_handler(chat_request: ChatRequest):
14-
1514
messages = [message.model_dump() for message in chat_request.messages]
1615
overrides = chat_request.context.get("overrides", {})
1716

src/fastapi_app/openai_clients.py

-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ async def create_openai_chat_client(azure_credential):
3838

3939

4040
async def create_openai_embed_client(azure_credential):
41-
4241
OPENAI_EMBED_HOST = os.getenv("OPENAI_EMBED_HOST")
4342
if OPENAI_EMBED_HOST == "azure":
4443
token_provider = azure.identity.aio.get_bearer_token_provider(

src/fastapi_app/postgres_engine.py

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99

1010
async def create_postgres_engine(*, host, username, database, password, sslmode, azure_credential) -> AsyncEngine:
11-
1211
if host.endswith(".database.azure.com"):
1312
logger.info("Authenticating to Azure Database for PostgreSQL using Azure Identity...")
1413
if azure_credential is None:

src/fastapi_app/postgres_searcher.py

-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77

88
class PostgresSearcher:
9-
109
def __init__(self, engine):
1110
self.async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
1211

@@ -30,7 +29,6 @@ async def search(
3029
query_top: int = 5,
3130
filters: list[dict] | None = None,
3231
):
33-
3432
filter_clause_where, filter_clause_and = self.build_filter_clause(filters)
3533

3634
vector_query = f"""

src/fastapi_app/rag_advanced.py

+4-9
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ def __init__(
2525
chat_model: str,
2626
chat_deployment: str | None, # Not needed for non-Azure OpenAI
2727
openai_embed_client: AsyncOpenAI,
28-
embed_deployment: str
29-
| None, # Not needed for non-Azure OpenAI or for retrieval_mode="text"
28+
embed_deployment: str | None, # Not needed for non-Azure OpenAI or for retrieval_mode="text"
3029
embed_model: str,
3130
embed_dimensions: int,
3231
):
@@ -60,8 +59,7 @@ async def run(
6059
system_prompt=self.query_prompt_template,
6160
new_user_content=original_user_query,
6261
past_messages=past_messages,
63-
max_tokens=self.chat_token_limit
64-
- query_response_token_limit, # TODO: count functions
62+
max_tokens=self.chat_token_limit - query_response_token_limit, # TODO: count functions
6563
fallback_to_default=True,
6664
)
6765

@@ -93,17 +91,14 @@ async def run(
9391

9492
results = await self.searcher.search(query_text, vector, top, filters)
9593

96-
sources_content = [
97-
f"[{(item.id)}]:{item.to_str_for_rag()}\n\n" for item in results
98-
]
94+
sources_content = [f"[{(item.id)}]:{item.to_str_for_rag()}\n\n" for item in results]
9995
content = "\n".join(sources_content)
10096

10197
# Generate a contextual and content specific answer using the search results and chat history
10298
response_token_limit = 1024
10399
messages = build_messages(
104100
model=self.chat_model,
105-
system_prompt=overrides.get("prompt_template")
106-
or self.answer_prompt_template,
101+
system_prompt=overrides.get("prompt_template") or self.answer_prompt_template,
107102
new_user_content=original_user_query + "\n\nSources:\n" + content,
108103
past_messages=past_messages,
109104
max_tokens=self.chat_token_limit - response_token_limit,

src/fastapi_app/rag_simple.py

-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414

1515
class SimpleRAGChat:
16-
1716
def __init__(
1817
self,
1918
*,
@@ -41,7 +40,6 @@ def __init__(
4140
async def run(
4241
self, messages: list[dict], overrides: dict[str, Any] = {}
4342
) -> dict[str, Any] | AsyncGenerator[dict[str, Any], None]:
44-
4543
text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
4644
vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
4745
top = overrides.get("top", 3)

src/fastapi_app/setup_postgres_azurerole.py

-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212

1313
async def assign_role_for_webapp(engine, app_identity_name):
14-
1514
async with engine.begin() as conn:
1615
identities = await conn.execute(
1716
text(f"select * from pgaadauth_list_principals(false) WHERE rolname = '{app_identity_name}'")
@@ -39,7 +38,6 @@ async def assign_role_for_webapp(engine, app_identity_name):
3938

4039

4140
async def main():
42-
4341
parser = argparse.ArgumentParser(description="Create database schema")
4442
parser.add_argument("--host", type=str, help="Postgres host")
4543
parser.add_argument("--username", type=str, help="Postgres username")
@@ -64,7 +62,6 @@ async def main():
6462

6563

6664
if __name__ == "__main__":
67-
6865
logging.basicConfig(level=logging.WARNING)
6966
logger.setLevel(logging.INFO)
7067
load_dotenv(override=True)

src/fastapi_app/setup_postgres_database.py

-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ async def create_db_schema(engine):
2222

2323

2424
async def main():
25-
2625
parser = argparse.ArgumentParser(description="Create database schema")
2726
parser.add_argument("--host", type=str, help="Postgres host")
2827
parser.add_argument("--username", type=str, help="Postgres username")
@@ -45,7 +44,6 @@ async def main():
4544

4645

4746
if __name__ == "__main__":
48-
4947
logging.basicConfig(level=logging.WARNING)
5048
logger.setLevel(logging.INFO)
5149
load_dotenv(override=True)

src/fastapi_app/setup_postgres_seeddata.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@ async def seed_data(engine):
2727
)
2828
)
2929
if not result.scalar():
30-
logger.error(
31-
"Items table does not exist. Please run the database setup script first."
32-
)
30+
logger.error("Items table does not exist. Please run the database setup script first.")
3331
return
3432

3533
async with async_sessionmaker(engine, expire_on_commit=False)() as session:
@@ -38,9 +36,7 @@ async def seed_data(engine):
3836
with open(os.path.join(current_dir, "seed_data.json")) as f:
3937
catalog_items = json.load(f)
4038
for catalog_item in catalog_items:
41-
item = await session.execute(
42-
select(Item).filter(Item.id == catalog_item["Id"])
43-
)
39+
item = await session.execute(select(Item).filter(Item.id == catalog_item["Id"]))
4440
if item.scalars().first():
4541
continue
4642
item = Item(

0 commit comments

Comments
 (0)