feat(retriever): implement doc processing and FastEmbed vector store indexing

This commit is contained in:
11linear11
2026-08-30 09:02:24 -04:00
parent d63786112d
commit 52dfcd39a1
18 changed files with 1407 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environments
.venv/
venv/
ENV/
env/
env.bak/
venv.bak/
# Environment Variables & Secrets
.env
.env.local
.env.*.local
*.env
!*.env.example
!*.env.template
# Vector Database & Local Data Storage
data/vector_db/
*.sqlite3
*.db
# Testing & Coverage
.pytest_cache/
.coverage
.coverage.*
htmlcov/
.tox/
.nox/
nosetests.xml
coverage.xml
*.cover
*.py,cover
# Type Checking & Linting
.mypy_cache/
.pytype/
.ruff_cache/
.dmypy.json
dmypy.json
# IDEs & Editors
.idea/
.vscode/
*.swp
*.swo
*~
*.sublime-project
*.sublime-workspace
# OS specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs & Temporary Files
*.log
logs/
tmp/
temp/
View File
View File
View File
+26
View File
@@ -0,0 +1,26 @@
# pyrefly: ignore [missing-import]
from pydantic_settings import BaseSettings,SettingsConfigDict
class Settings(BaseSettings):
# App Config
app_name: str = "Technical Documentation Assistant"
app_version: str = "1.0.0"
app_environment: str = "development" # development,production
# LLM Config
api_key: str
model: str
# RAG Config
chunk_size: int = 1000
chunk_overlap: int = 200
docs_dir: str = "./data/documents"
chroma_persist_dir: str = "./data/vector_db"
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore"
)
settings = Settings()
View File
View File
View File
View File
View File
View File
+36
View File
@@ -0,0 +1,36 @@
from app.core.config import settings
# pyrefly: ignore [missing-import]
from langchain_community.document_loaders import DirectoryLoader, TextLoader
# pyrefly: ignore [missing-import]
from langchain_text_splitters import RecursiveCharacterTextSplitter
class DocProcessor:
def __init__(self):
self.docs_dir = settings.docs_dir
self.chunk_size = settings.chunk_size
self.chunk_overlap = settings.chunk_overlap
def loader_docs(self):
loader = DirectoryLoader(self.docs_dir, glob="**/*.md", loader_cls=TextLoader,loader_kwargs={"encoding":"utf-8"})
return loader.load()
def process_docs(self):
docs = self.loader_docs()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
length_function=len,
)
return text_splitter.split_documents(docs)
if __name__ == "__main__":
doc_processor = DocProcessor()
chunks = doc_processor.process_docs()
print(f"Total Chunks Created: {len(chunks)}")
if chunks:
print("\n--- First Chunk Metadata ---")
print(chunks[0].metadata)
print("\n--- First Chunk Preview ---")
print(chunks[0].page_content[:200])
+47
View File
@@ -0,0 +1,47 @@
from app.core.config import settings
from app.services.doc_processor import DocProcessor
# pyrefly: ignore [missing-import]
from langchain_chroma import Chroma
# pyrefly: ignore [missing-import]
from langchain_community.embeddings import FastEmbedEmbeddings
import os
class ContextRetriever:
def __init__(self):
self.doc_processor = DocProcessor()
self.embedding = FastEmbedEmbeddings(
model_name="BAAI/bge-small-en-v1.5"
)
self.vec_store = self.get_or_create_vector_store()
def get_or_create_vector_store(self):
if os.path.exists(settings.chroma_persist_dir):
return Chroma(
persist_directory=settings.chroma_persist_dir,
embedding_function=self.embedding
)
else:
return self.index_documents()
def index_documents(self):
vec_store = Chroma.from_documents(
documents=self.doc_processor.process_docs(),
embedding=self.embedding,
persist_directory=settings.chroma_persist_dir
)
print(f"[vector store] Indexed documents at {settings.chroma_persist_dir}")
return vec_store
def retrieve(self,query:str,k=3):
return self.vec_store.similarity_search(query, k=k)
retriever = ContextRetriever()
if __name__ == "__main__":
results = retriever.retrieve("How to handle exceptions?", k=2)
print(f"Results found: {len(results)}")
if results:
print("First result snippet:", results[0].page_content[:150])
View File
+643
View File
@@ -0,0 +1,643 @@
# Docker Documentation Style Guide
This guide consolidates voice, grammar, formatting, and terminology
standards for Docker documentation. Follow these guidelines to create
clear, consistent, and helpful content. For instructions on how to use
components, shortcodes, and other features, see [COMPONENTS.md](COMPONENTS.md).
## Voice and tone
Write like a knowledgeable colleague explaining something useful. We're
developers writing for developers.
### Core principles: The 4Cs
1. **Correct** - Information is accurate
2. **Concise** - Succinct without unnecessary words
3. **Complete** - Includes enough detail to complete the task
4. **Clear** - Easy to understand
### Writing approach
- **Be honest.** Give all the facts. Don't use misdirection or
ambiguous statements.
- **Be concise.** Don't bulk up communication with fluffy words or
complex metaphors. Get to the point.
- **Be relaxed.** Casual but not lazy, smart but not arrogant, focused
but not cold. Be welcoming and warm.
- **Be inclusive.** Every person is part of our community, regardless
of experience level.
### Tone guidelines
- Use a natural, friendly, and respectful tone
- Use contractions to sound conversational (it's, you're, don't)
- Avoid overdoing politeness - skip "please" in most technical documentation
- Be clear over comical
- Use positive language - emphasize what users can do, not what they can't
**Positive language example:**
Instead of: "Features such as Single Sign-on (SSO), Image Access
Management, Registry Access Management are not available in Docker Team
subscription."
Use: "Features such as Single Sign-on (SSO), Image Access Management,
Registry Access Management are available in Docker Business subscription."
### Avoiding marketing language
Documentation should be factual and direct, not promotional.
**Avoid hedge words** that overstate ease or capability:
- ❌ simply, just, easily, seamlessly (implies ease when it may not be
easy)
- ❌ robust, powerful (marketing language)
- ✅ Instead: describe what it actually does
**Avoid excessive enthusiasm:**
- ❌ "powerful feature", "game-changing", "revolutionary", "amazing"
- ✅ Instead: describe the feature and its benefits factually
**Avoid meta-commentary:**
These phrases add no value - state the fact directly:
- ❌ "It's worth noting that..."
- ❌ "It's important to understand that..."
- ❌ "Keep in mind that..."
- ✅ Instead: state the information directly
### Voice and perspective
- **Use "you" not "we"**: Focus on what the user can do, not what "we"
created
- ❌ "We provide a feature that helps you deploy"
- ✅ "Deploy your applications with..."
- **Avoid "please"**: Don't use in normal explanations or "please note"
phrases
- **Write timelessly**: Avoid "currently" or "as of this writing" - the
documentation describes the product as it is today
### Explain technical behavior
Explain behavior from the reader's perspective. Lead with the observable
outcome, then add the implementation details needed to explain it.
Prefer:
> Changes made by the agent stay inside the sandbox until you fetch them. The
> agent works in a separate Git clone inside the sandbox.
Avoid:
> A session that works directly in the sandbox clone still can't modify your
> host repository.
The preferred version tells readers where changes happen and when they become
visible. The second version makes readers reconstruct the relationship between
the session, sandbox clone, and host repository.
Separate guarantees from variable behavior. Don't present behavior controlled
by another tool as a product default or guarantee. When behavior varies,
structure the explanation in this order:
1. State what always happens
2. State what the product doesn't control
3. Tell the reader what to do
For example:
> The `--clone` flag creates the clone, but it doesn't separate one task from
> another. To keep parallel tasks isolated, instruct your agent tool to create
> a separate branch or worktree for each task.
Avoid chains of qualifications such as "may," "can," and "depends" that leave
the reader without a conclusion. Keep qualifiers that are needed for accuracy.
State what controls the behavior and what the reader should do.
### Scope preservation
When updating existing documentation, resist the urge to expand
unnecessarily. Users value brevity.
**Understand the current document:**
Read it fully to grasp its scope, length, and character. Is it a minimal
how-to or a comprehensive reference?
**Match the existing character:**
If the document is brief and direct (90 lines), keep it that way. Don't
transform a focused guide into an exhaustive tutorial.
**Add only what's genuinely missing:**
Fill gaps, don't elaborate. If the document already covers a topic
adequately, don't expand it.
**Value brevity:**
Say what needs to be said, then stop. Not every topic needs
prerequisites, troubleshooting, best practices, and examples sections.
**Respect the original intent:**
The document exists in its current form for a reason. Improve it, don't
remake it.
Good additions fill genuine gaps. Bad additions change the document's
character. When in doubt, add less rather than more.
Include caveats, failure scenarios, and fallback behavior only when they affect
a decision or action. Don't turn a clarification into a catalog of edge
cases.
## Grammar and style
Write in US English with US grammar.
### Acronyms and initialisms
- Spell out lesser-known acronyms on first use, then follow with the
acronym in parentheses: "single sign-on (SSO)"
- Don't spell out common acronyms like URL, HTML, API
- Use all caps for file type acronyms: JPEG, PNG
- Don't use apostrophes for plurals: URLs not URL's
- Avoid introducing acronyms in headings - introduce them in the body
text that follows
### Capitalization
Use sentence case for almost everything: headings, titles, links, buttons,
navigation labels.
- Capitalize Docker solutions: Docker Desktop, Docker Hub, Docker Extensions
- Capitalize job titles only when they immediately precede a name:
"Chief Executive Officer Scott Johnston" but "Scott Johnston, chief
executive officer"
- Follow company capitalization preferences: DISH, bluecrux
- Match UI capitalization when referring to specific interface elements
### Contractions
Use contractions to maintain a conversational tone, but don't overdo it.
- Stay consistent - don't switch between "you are" and "you're" in the
same content
- Avoid negative contractions when possible (can't, don't, won't) -
rewrite to be positive
- Never contract a noun with a verb (your container is ready, not your
container's ready)
### Clear subjects and modifiers
Name the actor when a system includes multiple tools or components. Repeat the
noun instead of using an ambiguous pronoun. For example, distinguish between
what a CLI creates, what an agent edits, and what remains on the host.
Avoid unclear subjects:
- ❌ After enabling auto-log-out, your users are logged out
- ✅ When you enable auto-log-out, your users are logged out
### Dates and numbers
- Use US date format: June 26, 2021 or Jun. 26, 2021
- Spell out numbers one through nine, except in units: 4 MB
- Use numerals for 10 and above: 10, 625, 1000
- Use decimals instead of fractions: 0.5 not ½
- For numbers with five or more digits, use spaces instead of commas:
14 586 not 14,586
- For version numbers: version 4.8.2, v1.0, Docker Hub API v2
### Punctuation
- **Commas:** Use the Oxford comma (serial comma) in lists
- **Colons:** Use to introduce lists or provide explanations
- **Semicolons:** Don't use - write two sentences instead
- **Em dashes:** Use sparingly with spaces on either side: "text - like
this - text"
- **Hyphens:** Use for compound adjectives before nouns:
"up-to-date documentation"
- **Exclamation marks:** Avoid
- **Parentheses:** Avoid in technical documentation - they reduce
readability
### Conciseness and redundant phrases
Remove unnecessary words to make documentation clearer and more direct.
Keep an adjective or qualifier only when it changes how readers understand the
behavior or complete the task. If removing it doesn't change an outcome,
decision, or next step, remove it. Apply the same test to implementation
details.
**Eliminate redundant phrases:**
- ❌ "in order to" → ✅ "to"
- ❌ "serves the purpose of" → ✅ state what it does directly
- ❌ "allows you to" → ✅ "lets you" or state what it does
- ❌ "enables you to" → ✅ "lets you" or state what it does
### Bold and italics
Use bold **only** for UI elements (buttons, menus, field labels). Never
use bold for emphasis, product names, or feature names.
- ✅ Select **Save** (UI button - use bold)
- ✅ Docker Hub provides storage (product name - no bold)
- ✅ This is important to understand (emphasis - no bold)
- ❌ **Docker Desktop** is a tool (product name - don't bold)
- ❌ This is **very important** (emphasis - don't bold)
- ❌ The **build** command (command name - don't bold)
**Italics:**
Use italics sparingly, as this formatting can be difficult to read in
digital experiences. Notable exceptions are titles of articles, blog
posts, or specification documents.
## Formatting
### Content types and detail balance
Different content types require different writing approaches. Match your
style and detail level to the content type.
**Getting Started / Tutorials:**
- Step-by-step instructions
- Assume beginner knowledge
- Explain _why_ at each step
- Include more context and explanation
**How-to Guides:**
- Task-focused and goal-oriented
- Assume intermediate knowledge
- Focus on _how_ efficiently
- Less explanation, more direct steps
**Reference Documentation:**
- Comprehensive and exhaustive
- Assume advanced knowledge
- Focus on _what_ precisely
- Complete parameter lists and options
**Concept Explanations:**
- Educational and foundational
- Any skill level
- Focus on _understanding_ over doing
- Theory before practice
**Match detail to context:**
- **First mention** of a concept: explain it
- **Subsequent mentions**: link to the explanation or use the term
directly if recently explained
- **Common knowledge** (to your audience): state it, don't explain it
- **Edge cases**: mention them but don't let them dominate the main flow
### Headings
- Keep headings short (no more than eight words)
- Front-load the most important words
- Use descriptive, action-oriented language
- Skip leading articles (a, the)
- Avoid puns, teasers, and cultural references
- Page titles should be action-oriented: "Install Docker Desktop",
"Enable SCIM"
### Page structure and flow
Every page should answer two questions in the first paragraph:
1. **What will I learn?** - State what the page covers
2. **Why does this matter?** - Explain the benefit or use case
**Good opening:**
```markdown
Docker Compose Watch automatically updates your running containers when
you change code. This eliminates the manual rebuild-restart cycle during
development.
```
**Weak opening:**
```markdown
Docker Compose Watch is a powerful feature that enables developers to
streamline their development workflow by providing automatic
synchronization capabilities.
```
**Transitions and flow:**
Connect ideas naturally. Each section should flow logically from the
previous one. Save detailed discussions for after showing basic usage -
don't front-load complexity.
**Good flow:**
1. Prerequisites
2. Basic usage (show the simple case first)
3. Advanced options (add complexity after basics are clear)
**Jarring flow:**
1. Prerequisites
2. Overview of all capabilities (too much before seeing it work)
3. Basic usage
**Avoid structural problems:**
- Don't start multiple sentences or sections with the same structure
(varies pacing and improves readability)
- Don't over-explain obvious things (trust the reader's competence)
- Don't use "**Bold:** format" for subsection labels (use plain text
with colon)
### Guide structure
Guides are single-page - don't split a guide into multiple sub-pages
(for example, separate "overview", "configure", and "deploy" pages for
one guide). Cover the full task on one page and use headings to
organize sections.
Store each guide as a single Markdown file directly under
`content/guides/` (for example, `content/guides/django.md`), not
wrapped in its own directory with an `index.md`. Guide images belong in
the shared `content/guides/images/` folder, prefixed with the guide's
slug, not in a per-guide directory - see [Images](STYLE.md#images).
### Lists
- Limit bulleted lists to five items when possible
- Don't add commas or semicolons to list item ends
- Capitalize list items for ease of scanning
- Make all list items parallel in structure
- Start each item with a capital letter unless it's a parameter or
command
- For nested sequential lists, use lowercase letters: 1. Top level,
a. Child step
**Avoid marketing-style list formatting:**
Don't use "**Term** - Description" format, which reads like marketing
copy:
❌ **Bad example:**
- **Build** - Creates images from Dockerfiles
- **Run** - Starts containers from images
- **Push** - Uploads images to registries
✅ **Good alternatives:**
Use simple descriptive bullets:
- Build images from Dockerfiles
- Start containers from images
- Upload images to registries
Or use proper prose when appropriate:
"Docker lets you build images from Dockerfiles, start containers from
images, and upload images to registries."
### Code and commands
Format Docker commands, instructions, filenames, and package names as
inline code using backticks: `docker build`
**Code example pattern:**
Follow this three-step pattern for code examples:
1. **State** what you're doing (brief)
2. **Show** the command or code
3. **Explain** the result or key parts (if not obvious)
**Example:**
````markdown
Build your image:
```console
$ docker build -t my-app .
```
This creates an image tagged `my-app` using the Dockerfile in the
current directory.
````
**When to show command output:**
- Show output when it helps understanding
- Show output when users need to verify results
- Don't show output for commands with obvious results
- Don't show output when it's not relevant to the point
For code block syntax, language hints, variables, and advanced features
(line highlighting, collapsible blocks), see
[COMPONENTS.md](COMPONENTS.md#code-blocks).
### Links
- Use plain, descriptive language (around five words)
- Front-load important terms at the beginning
- Avoid generic calls to action like "click here" or "find out more"
- Don't include end punctuation in link text
- Use relative links with source filenames for internal links
- Don't make link text bold or italic unless it would be in normal
body copy
### Images
**Best practices:**
- Capture only relevant UI - don't include unnecessary white space
- Use realistic text, not lorem ipsum
- Keep images small and focused
- Compress images before adding to repository
- Remove unused images from repository
**File organization:**
- Store guide images in the shared `content/guides/images/` folder,
not in a per-guide directory
- Prefix filenames with the guide's slug to avoid collisions (for
example, `kafka-architecture.webp`)
For image syntax and parameters (sizing, borders), see
[COMPONENTS.md](COMPONENTS.md#images).
### Callouts
Use callouts sparingly to emphasize important information. Use them only
when information truly deserves special emphasis - for warnings, critical
notes, or important context that affects how users approach a task.
Callout types: Note (informational), Tip (helpful suggestion), Important
(moderate issue), Warning (potential damage/loss), Caution (serious risk).
For syntax and detailed usage guidelines, see
[COMPONENTS.md](COMPONENTS.md#callouts).
### Tables
- Use sentence case for table headings
- Don't leave cells empty - use "N/A" or "None" if needed
- Align decimals on the decimal point
### Navigation instructions
- Use location, then action: "From the **Visibility** drop-down list, select Public"
- Be brief and specific: "Select **Save**"
- Start with the reason if a step needs one: "To view changes, select the link"
### Optional steps
Start optional steps with "Optional." followed by the instruction:
_1. Optional. Enter a description for the job._
### File types and units
- Use formal file type names: "a PNG file" not "a .png file"
- Use abbreviated units with spaces: "10 GB" not "10GB" or
"10 gigabytes"
## Word list
### Recommended terms
| Use | Don't use |
| ------------------------------------- | ---------------------- |
| lets | allows |
| turn on, toggle on | enable |
| turn off, toggle off | disable |
| select | click |
| following | below |
| previous | above |
| checkbox | check box |
| username | account name |
| sign in | sign on, log in, login |
| sign up, create account | register |
| for example, such as | e.g. |
| run | execute |
| want | wish |
| Kubernetes | K8s |
| repository | repo |
| administrator (first use), admin (UI) | - |
| and | & (ampersand) |
| move through, navigate to | scroll |
| (be more precise) | respectively |
| versus | vs, vs. |
| use | utilize |
| help | facilitate |
Use "turn on" and "turn off" for UI toggles, switches, and settings a user
flips in the interface. In general prose, "enable" and "disable" are
acceptable when describing a feature or capability becoming available — for
example, "When you enable auto-log-out, your users are logged out." Don't
treat every "enable" or "disable" as a violation.
### Version numbers
- Use "earlier" not "lower": Docker Desktop 4.1 and earlier
- Use "later" not "higher" or "above": Docker Desktop 4.1 and later
### Quick transformations
Common phrases to transform for clearer, more direct writing:
| Instead of... | Write... |
| ------------------------ | ---------------------------- |
| In order to build | To build |
| This allows you to build | This lets you build / Build |
| Simply run the command | Run the command |
| We provide a feature | Docker provides / You can |
| Utilize the API | Use the API |
| This facilitates testing | This helps test / This tests |
| Click the button | Select the button |
| It's worth noting that X | X (state it directly) |
### UI elements
- **tab vs view** - Use "view" for major UI sections, "tab" for
sub-sections
- **toggle** - You "turn on" or "turn off" a toggle
## Docker terminology
### Products and features
- **Docker Compose** - The application or all functionality associated
with it
- **`docker compose`** - Use code formatting for commands
- **Docker Compose CLI** - The family of Compose commands from
Docker CLI
- **Compose plugin** - The add-on for Docker CLI that can be
enabled/disabled
- **compose.yaml** - Current designation for the Compose file (use
code formatting)
### Technical terms
- **Digest** - Long string automatically created when you push an
image
- **Member** - A user of Docker Hub who is part of an organization
- **Namespace** - Organization or user name; every image needs a
namespace
- **Node** - Physical or virtual machine running Docker Engine in
swarm mode
- Manager nodes: Perform swarm management and orchestration
- Worker nodes: Execute tasks
- **Registry** - Online storage for Docker images
- **Repository** - Lets users share container images with team,
customers, or community
### Platform terminology
- **Multi-platform** - Broad: Mac/Linux/Windows; Narrow: Linux/amd64
and Linux/arm64
- **Multi-architecture (multi-arch)** - CPU architecture or
hardware-architecture-based; don't use as synonym for multi-platform
## Quick reference
### Voice checklist
- ✅ Direct and practical
- ✅ Conversational with active voice
- ✅ Specific and actionable
- ✅ Lead with observable outcomes
- ❌ Corporate-speak
- ❌ Condescending
- ❌ Overly formal
### Structure checklist
- ✅ Answer "What will I learn?" in the first paragraph
- ✅ Answer "Why does this matter?" in the first paragraph
- ✅ Front-load important information in headings and lists
- ✅ Connect ideas naturally between sections
- ✅ Use examples to clarify concepts
- ✅ Match content type (tutorial vs how-to vs reference vs concept)
- ✅ Follow code example pattern: state → show → explain
- ✅ Preserve document scope (don't unnecessarily expand)
### Common mistakes
- ❌ Using "click" instead of "select"
- ❌ Using "below" instead of "following"
- ❌ Starting sentences with numbers (recast the sentence)
- ❌ Using apostrophes in plural acronyms
- ❌ Leaving table cells empty
- ❌ Using commas in large numbers (use spaces)
- ❌ Referring to file types by extension (.png file)
- ❌ Using bold for product names or emphasis (only for UI elements)
- ❌ Using "**Term** - Description" format in lists
- ❌ Using hedge words (simply, easily, just, seamlessly)
- ❌ Using meta-commentary (it's worth noting that...)
- ❌ Using "we" instead of "you" or "Docker"
- ❌ Showing command output when it's not needed
- ❌ Not explaining what users will learn in first paragraph
+244
View File
@@ -0,0 +1,244 @@
# Handling Errors { #handling-errors }
There are many situations in which you need to report an error to a client that is using your API.
This client could be a browser with a frontend, a code from someone else, an IoT device, etc.
You could need to tell the client that:
* The client doesn't have enough privileges for that operation.
* The client doesn't have access to that resource.
* The item the client was trying to access doesn't exist.
* etc.
In these cases, you would normally return an **HTTP status code** in the range of **400** (from 400 to 499).
This is similar to the 200 HTTP status codes (from 200 to 299). Those "200" status codes mean that somehow there was a "success" in the request.
The status codes in the 400 range mean that there was an error from the client.
Remember all those **"404 Not Found"** errors (and jokes)?
## Use `HTTPException` { #use-httpexception }
To return HTTP responses with errors to the client you use `HTTPException`.
### Import `HTTPException` { #import-httpexception }
{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Raise an `HTTPException` in your code { #raise-an-httpexception-in-your-code }
`HTTPException` is a normal Python exception with additional data relevant for APIs.
Because it's a Python exception, you don't `return` it, you `raise` it.
This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.
The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.
In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:
{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### The resulting response { #the-resulting-response }
If the client requests `http://example.com/items/foo` (an `item_id` `"foo"`), that client will receive an HTTP status code of 200, and a JSON response of:
```JSON
{
"item": "The Foo Wrestlers"
}
```
But if the client requests `http://example.com/items/bar` (a non-existent `item_id` `"bar"`), that client will receive an HTTP status code of 404 (the "not found" error), and a JSON response of:
```JSON
{
"detail": "Item not found"
}
```
/// tip
When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
You could pass a `dict`, a `list`, etc.
They are handled automatically by **FastAPI** and converted to JSON.
///
## Add custom headers { #add-custom-headers }
There are some situations where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Install custom exception handlers { #install-custom-exception-handlers }
You can add custom exception handlers with [the same exception utilities from Starlette](https://starlette.dev/exceptions/).
Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.
And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
But it will be handled by the `unicorn_exception_handler`.
So, you will receive a clean error, with an HTTP status code of `418` and a JSON content of:
```JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
/// note | Technical Details
You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
///
## Override the default exception handlers { #override-the-default-exception-handlers }
**FastAPI** has some default exception handlers.
These handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.
You can override these exception handlers with your own.
### Override request validation exceptions { #override-request-validation-exceptions }
When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`.
And it also includes a default exception handler for it.
To override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler.
The exception handler will receive a `Request` and the exception.
{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
```JSON
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
```
you will get a text version, with:
```
Validation errors:
Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
```
### Override the `HTTPException` error handler { #override-the-httpexception-error-handler }
The same way, you can override the `HTTPException` handler.
For example, you could want to return a plain text response instead of JSON for these errors:
{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Technical Details
You could also use `from starlette.responses import PlainTextResponse`.
**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
///
/// warning
Have in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to.
But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently.
///
### Use the `RequestValidationError` body { #use-the-requestvalidationerror-body }
The `RequestValidationError` contains the `body` it received with invalid data.
You could use it while developing your app to log the body and debug it, return it to the user, etc.
{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Now try sending an invalid item like:
```JSON
{
"title": "towel",
"size": "XL"
}
```
You will receive a response telling you that the data is invalid containing the received body:
```JSON hl_lines="12-15"
{
"detail": [
{
"loc": [
"body",
"size"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
],
"body": {
"title": "towel",
"size": "XL"
}
}
```
#### FastAPI's `HTTPException` vs Starlette's `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
**FastAPI** has its own `HTTPException`.
And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.
The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it.
So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.
But when you register an exception handler, you should register it for Starlette's `HTTPException`.
This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette `HTTPException`, your handler will be able to catch and handle it.
In this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`:
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
```
### Reuse **FastAPI**'s exception handlers { #reuse-fastapis-exception-handlers }
If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
+326
View File
@@ -0,0 +1,326 @@
# Settings and Environment Variables { #settings-and-environment-variables }
In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.
Most of these settings are variable (can change), like database URLs. And many could be sensitive, like secrets.
For this reason it's common to provide them in environment variables that are read by the application.
An **environment variable** (also known as an **env var**) is a value that lives outside of the Python code, in the operating system, and can be read by your application and other programs.
You can create an environment variable for a command when you run it. You will see the platform-specific commands below.
/// tip
Read the [Environment Variables guide](https://tiangolo.com/guides/environment-variables/) for a detailed explanation of how environment variables work.
///
## Types and validation { #types-and-validation }
These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, such as Linux, Windows, and macOS).
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.
## Pydantic `Settings` { #pydantic-settings }
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with [Pydantic: Settings management](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/).
### Install `pydantic-settings` { #install-pydantic-settings }
Add the `pydantic-settings` package to your project:
<div class="termy">
```console
$ uv add pydantic-settings
---> 100%
```
</div>
It also comes included when you install the `all` extras with:
<div class="termy">
```console
$ uv add "fastapi[all]"
---> 100%
```
</div>
### Create the `Settings` object { #create-the-settings-object }
Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.
The same way as with Pydantic models, you declare class attributes with type annotations, and possibly default values.
You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`.
{* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *}
/// tip
If you want something quick to copy and paste, don't use this example, use the last one below.
///
Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`.
Next it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`).
### Use the `settings` { #use-the-settings }
Then you can use the new `settings` object in your application:
{* ../../docs_src/settings/tutorial001_py310.py hl[18:20] *}
### Run the server { #run-the-server }
Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uv run fastapi run main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ $Env:ADMIN_EMAIL = "deadpool@example.com"
$ $Env:APP_NAME = "ChimichangApp"
$ uv run fastapi run main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
////
/// tip
In Bash, to set multiple env vars for a single command, separate them with a space and put them all before the command.
///
And then the `admin_email` setting would be set to `"deadpool@example.com"`.
The `app_name` would be `"ChimichangApp"`.
And the `items_per_user` would keep its default value of `50`.
## Settings in another module { #settings-in-another-module }
You could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).
For example, you could have a file `config.py` with:
{* ../../docs_src/settings/app01_py310/config.py *}
And then use it in a file `main.py`:
{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
/// tip
You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).
///
## Settings in a dependency { #settings-in-a-dependency }
In some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere.
This could be especially useful during testing, as it's very easy to override a dependency with your own custom settings.
### The config file { #the-config-file }
Coming from the previous example, your `config.py` file could look like:
{* ../../docs_src/settings/app02_an_py310/config.py hl[10] *}
Notice that now we don't create a default instance `settings = Settings()`.
### The main app file { #the-main-app-file }
Now we create a dependency that returns a new `config.Settings()`.
{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
/// tip
We'll discuss the `@lru_cache` in a bit.
For now you can assume `get_settings()` is a normal function.
///
And then we can require it from the *path operation function* as a dependency and use it anywhere we need it.
{* ../../docs_src/settings/app02_an_py310/main.py hl[17,19:21] *}
### Settings and testing { #settings-and-testing }
Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:
{* ../../docs_src/settings/app02_an_py310/test_main.py hl[9:10,13,21] *}
In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object.
Then we can test that it is used.
## Reading a `.env` file { #reading-a-env-file }
If you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables.
This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv".
/// tip
A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS.
But a dotenv file doesn't really have to have that exact filename.
///
Pydantic has support for reading from these types of files using an external library. You can read more at [Pydantic Settings: Dotenv (.env) support](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#dotenv-env-support).
/// tip
For this to work, add `python-dotenv` to your project with `uv add python-dotenv`.
///
### The `.env` file { #the-env-file }
You could have a `.env` file with:
```bash
ADMIN_EMAIL="deadpool@example.com"
APP_NAME="ChimichangApp"
```
### Read settings from `.env` { #read-settings-from-env }
And then update your `config.py` with:
{* ../../docs_src/settings/app03_an_py310/config.py hl[9] *}
/// tip
The `model_config` attribute is used just for Pydantic configuration. You can read more at [Pydantic: Concepts: Configuration](https://pydantic.dev/docs/validation/latest/concepts/config/).
///
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.
But every time we do:
```Python
Settings()
```
a new `Settings` object would be created, and at creation it would read the `.env` file again.
If the dependency function was just like:
```Python
def get_settings():
return Settings()
```
we would create that object for each request, and we would be reading the `.env` file for each request. ⚠️
But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️
{* ../../docs_src/settings/app03_an_py310/main.py hl[1,11] *}
Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
#### `lru_cache` Technical Details { #lru-cache-technical-details }
`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time.
So, the function below it will be executed once for each combination of arguments. And then the values returned by each of those combinations of arguments will be used again and again whenever the function is called with exactly the same combination of arguments.
For example, if you have a function:
```Python
@lru_cache
def say_hi(name: str, salutation: str = "Ms."):
return f"Hello {salutation} {name}"
```
your program could execute like this:
```mermaid
sequenceDiagram
participant code as Code
participant function as say_hi()
participant execute as Execute function
rect rgba(0, 255, 0, .1)
code ->> function: say_hi(name="Camila")
function ->> execute: execute function code
execute ->> code: return the result
end
rect rgba(0, 255, 255, .1)
code ->> function: say_hi(name="Camila")
function ->> code: return stored result
end
rect rgba(0, 255, 0, .1)
code ->> function: say_hi(name="Rick")
function ->> execute: execute function code
execute ->> code: return the result
end
rect rgba(0, 255, 0, .1)
code ->> function: say_hi(name="Rick", salutation="Mr.")
function ->> execute: execute function code
execute ->> code: return the result
end
rect rgba(0, 255, 255, .1)
code ->> function: say_hi(name="Rick")
function ->> code: return stored result
end
rect rgba(0, 255, 255, .1)
code ->> function: say_hi(name="Camila")
function ->> code: return stored result
end
```
In the case of our dependency `get_settings()`, the function doesn't even take any arguments, so it always returns the same value.
That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing.
`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the [Python docs for `@lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache).
## Recap { #recap }
You can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models.
* By using a dependency you can simplify testing.
* You can use `.env` files with it.
* Using `@lru_cache` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing.