Spaces:
Sleeping
Sleeping
Islam Mamedov commited on
Commit ·
c94d0fe
1
Parent(s): bbb66cb
Baseline v0: recall@5 0.91, MRR 0.71, correct 0.89
Browse files- data/eval_cache.json +93 -1
- src/ask.py +1 -1
- src/eval.py +22 -13
data/eval_cache.json
CHANGED
|
@@ -20,5 +20,97 @@
|
|
| 20 |
"d26701006986fce5": "You can add a WebSocket endpoint to a FastAPI app by:\n\n1. **Importing the `WebSocket` class** (it’s re‑exported by FastAPI from Starlette)【4】. \n2. **Declaring a function decorated with `@app.websocket(...)`** that receives a `WebSocket` parameter. \n3. **Accepting the connection** with `await websocket.accept()`. \n4. **Reading and writing** using the `receive_*` and `send_*` methods (e.g., `receive_text`, `send_text`). \n5. **Running the app** (e.g., `fastapi dev`) and connecting from a browser or client【2】.\n\n```python\nfrom fastapi import FastAPI, WebSocket, WebSocketException, status\n\napp = FastAPI()\n\n@app.websocket(\"/items/{item_id}/ws\")\nasync def websocket_endpoint(\n *,\n websocket: WebSocket,\n item_id: str,\n):\n # Example of raising a client‑error exception\n # raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)\n\n await websocket.accept() # accept the connection\n while True:\n data = await websocket.receive_text() # read a message\n await websocket.send_text(\n f\"Message text was: {data}, for item ID: {item_id}\"\n ) # send a response\n```\n\n* The `WebSocketException` class can be raised to close the connection with a specific WebSocket close code (e.g., `status.WS_1008_POLICY_VIOLATION`)【5】. \n\nRun the app:\n\n```bash\n$ fastapi dev\nINFO: Uvicorn running on http://127.0.0.1:8000\n```\n\nThen open `http://127.0.0.1:8000` in a browser, type messages, and see the server’s responses【2】.",
|
| 21 |
"63e74d7941780851": "{\"faithful\": true, \"correct\": true}",
|
| 22 |
"f82568e4b9ac6687": "I couldn't find this in the indexed codebase.",
|
| 23 |
-
"d427347a9f2028cb": "I couldn't find this in the indexed codebase."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
}
|
|
|
|
| 20 |
"d26701006986fce5": "You can add a WebSocket endpoint to a FastAPI app by:\n\n1. **Importing the `WebSocket` class** (it’s re‑exported by FastAPI from Starlette)【4】. \n2. **Declaring a function decorated with `@app.websocket(...)`** that receives a `WebSocket` parameter. \n3. **Accepting the connection** with `await websocket.accept()`. \n4. **Reading and writing** using the `receive_*` and `send_*` methods (e.g., `receive_text`, `send_text`). \n5. **Running the app** (e.g., `fastapi dev`) and connecting from a browser or client【2】.\n\n```python\nfrom fastapi import FastAPI, WebSocket, WebSocketException, status\n\napp = FastAPI()\n\n@app.websocket(\"/items/{item_id}/ws\")\nasync def websocket_endpoint(\n *,\n websocket: WebSocket,\n item_id: str,\n):\n # Example of raising a client‑error exception\n # raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)\n\n await websocket.accept() # accept the connection\n while True:\n data = await websocket.receive_text() # read a message\n await websocket.send_text(\n f\"Message text was: {data}, for item ID: {item_id}\"\n ) # send a response\n```\n\n* The `WebSocketException` class can be raised to close the connection with a specific WebSocket close code (e.g., `status.WS_1008_POLICY_VIOLATION`)【5】. \n\nRun the app:\n\n```bash\n$ fastapi dev\nINFO: Uvicorn running on http://127.0.0.1:8000\n```\n\nThen open `http://127.0.0.1:8000` in a browser, type messages, and see the server’s responses【2】.",
|
| 21 |
"63e74d7941780851": "{\"faithful\": true, \"correct\": true}",
|
| 22 |
"f82568e4b9ac6687": "I couldn't find this in the indexed codebase.",
|
| 23 |
+
"d427347a9f2028cb": "I couldn't find this in the indexed codebase.",
|
| 24 |
+
"63c398e7be976dcf": "Declare the type in the function signature with a normal Python type annotation. For example:\n\n```python\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int):\n return {\"item_id\": item_id}\n```\n\nHere `item_id` is annotated as `int`, so FastAPI treats the path parameter as an integer. [1]",
|
| 25 |
+
"b7850021ed20860f": "{\"faithful\": true, \"correct\": true}",
|
| 26 |
+
"b2dbb03c61757986": "I couldn't find this in the indexed codebase.",
|
| 27 |
+
"5b2f524a9bd960ab": "{\"faithful\": false, \"correct\": false}",
|
| 28 |
+
"07a6c9363ce7a548": "Use FastAPI’s **`Form`** class for the parameters you want to read from an HTML form instead of the request body JSON. \nDeclare the parameters with `Form(...)` in the path‑operation function, and make sure the **python‑multipart** package is installed so FastAPI can parse the form data.\n\n```python\nfrom fastapi import FastAPI, Form\n\napp = FastAPI()\n\n@app.post(\"/login\")\nasync def login(username: str = Form(...), password: str = Form(...)):\n return {\"username\": username, \"password\": password}\n```\n\n* Install the required dependency:\n\n```bash\npip install python-multipart\n```\n\n[1][5]",
|
| 29 |
+
"0742a4533adf6ac4": "{\"faithful\": true, \"correct\": true}",
|
| 30 |
+
"eeb5d39f6f16aa5f": "You can build the response yourself and return it, setting the HTTP code you need.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse # or from starlette.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n if item_id not in database:\n # custom error payload\n return JSONResponse(\n content={\"detail\": f\"Item {item_id} not found\"},\n status_code=404, # any status you want\n )\n return {\"item_id\": item_id}\n```\n\n* Import `JSONResponse` (or any `Response` subclass) and return it directly, setting `status_code` to the desired value — this bypasses FastAPI’s automatic `JSONResponse` wrapping and lets you control both the body and the code [1][4].\n* The same effect can be achieved by declaring `status_code` on the decorator, but returning a `Response` lets you choose the exact payload for an error [2].\n\nSo, create a `JSONResponse` (or `Response`) with the error message in `content` and the required `status_code`, and return it from the path operation.",
|
| 31 |
+
"837741b8d5e29609": "{\"faithful\": true, \"correct\": true}",
|
| 32 |
+
"f3784fabf4ffaa7d": "Use the **`response_model`** argument of the path‑operation decorator. \nFastAPI will take whatever you return (a dict, a DB object, a Pydantic model, …) and **convert‑filter it to the fields declared in the model** — any extra attributes are dropped [2][5].\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass PublicItem(BaseModel):\n name: str\n price: float # only these fields will be sent back\n\n@app.get(\"/items/{item_id}\", response_model=PublicItem)\nasync def read_item(item_id: int):\n # internal object has many more fields\n internal = {\"name\": \"Foo\", \"price\": 12.5, \"secret\": \"hide me\"}\n return internal # FastAPI returns only name & price\n```\n\n### Fine‑grained control\n\n* **Exclude unset/default values** – add `response_model_exclude_unset=True` (or `response_model_exclude_defaults=True`, `response_model_exclude_none=True`) [3].\n* **Include or exclude specific fields** – use `response_model_include` or `response_model_exclude` with a set of field names [3].\n\n```python\n@app.get(\n \"/items/{item_id}\",\n response_model=PublicItem,\n response_model_exclude_unset=True,\n response_model_exclude={\"price\"},\n)\nasync def read_item(item_id: int):\n ...\n```\n\nIn short, declare the desired output schema with `response_model`, and optionally tweak it with the `*_exclude_*` or `*_include*` parameters to control exactly which fields appear in the JSON response. [2][3][4]",
|
| 33 |
+
"0d1f51a707abb452": "{\"faithful\": false, \"correct\": true}",
|
| 34 |
+
"39e9884cd277fc37": "You serve static assets by mounting a **StaticFiles** instance on a URL path.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\napp = FastAPI()\n\n# Serve everything inside the local “static” folder at “/static”\napp.mount(\n \"/static\",\n StaticFiles(directory=\"static\"),\n name=\"static\",\n)\n```\n\nAfter this, any file placed in the `static/` directory (e.g., images, CSS, JavaScript) is automatically available at URLs like `http://<host>/static/logo.png` or `http://<host>/static/styles.css` [1][3]. \n\nIn templates you can refer to them with `url_for(\"static\", path=\"styles.css\")` or directly as `/static/styles.css` [2]. ",
|
| 35 |
+
"0f1eaa9f16e4ae6c": "{\"faithful\": true, \"correct\": true}",
|
| 36 |
+
"8fa78a85977bd5ff": "Add the **CORSMiddleware** to your FastAPI app and list the origins that are allowed to call it.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware # ← import\n\napp = FastAPI()\n\norigins = [\n \"http://localhost:8080\", # ← frontend URL\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins, # list of allowed origins\n allow_credentials=True, # if you need cookies / auth headers\n allow_methods=[\"*\"], # or e.g. [\"GET\", \"POST\"]\n allow_headers=[\"*\"], # or specific header names\n)\n```\n\n* Create a list of the frontend URLs that may access the API — the browser will send an `OPTIONS` pre‑flight request and the middleware will return the proper CORS headers for those origins [1]. \n* Import `CORSMiddleware`, pass the `allow_*` arguments (origins, methods, headers, credentials, etc.), and add it as middleware to the FastAPI application [2]. \n\nWith this configuration the frontend running at `http://localhost:8080` can successfully call the API.",
|
| 37 |
+
"c0de653d63479dc4": "{\"faithful\": true, \"correct\": true}",
|
| 38 |
+
"d8922fbc3d40ed82": "Use the **`response_model`** argument of the path‑operation decorator and declare a Pydantic model that contains only the fields you want to expose. FastAPI will:\n\n* validate the returned data against that model, \n* filter out any extra attributes, and \n* serialize only the declared fields in the HTTP response【2†L1-L9】【2†L19-L27】.\n\n```python\nfrom typing import Any\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass PublicItem(BaseModel):\n name: str\n description: str | None = None # only these fields will be returned\n\n@app.get(\"/items/me\", response_model=PublicItem)\nasync def get_item() -> Any: # return any type (dict, DB object, etc.)\n # could be a dict, ORM object, or a model with extra fields\n return {\"name\": \"Foo\", \"description\": \"A very nice Item\", \"secret_key\": \"hide\"}\n```\n\nThe response will contain only `name` and `description`; `secret_key` is omitted because it isn’t defined in `PublicItem`【5†L1-L14】.\n\nIf you also want to omit fields that have default values and weren’t explicitly set, add `response_model_exclude_unset=True` (or `response_model_exclude_defaults=True`, `response_model_exclude_none=True`) to the decorator【3†L1-L9】【3†L11-L14】. This further controls which fields appear in the final JSON.",
|
| 39 |
+
"c84ce01728faabba": "You can set a custom status code for an endpoint in several ways. \n\nOne way is to pass the status code directly to the path operation decorator, such as `@app.get(status_code=404)`. The `status_code` parameter can receive an integer or an `IntEnum`, like Python's `http.HTTPStatus` [5].\n\nAlternatively, you can define the status code using shortcut constants from `fastapi.status` or `starlette.status`, which is more readable and self-explanatory [2].\n\nIf you need to return a different status code than the default one based on certain conditions, you can return a `Response` object directly, such as `JSONResponse`, and set the status code as needed [1].\n\nFor example:\n```python\nfrom fastapi import FastAPI, JSONResponse\nfrom fastapi.status import HTTP_201_CREATED\n\napp = FastAPI()\n\n@app.post(status_code=200)\nasync def create_item(item: dict):\n # If the item is created successfully\n return JSONResponse(content={\"message\": \"Item created\"}, status_code=HTTP_201_CREATED)\n```",
|
| 40 |
+
"afbdda909919d0eb": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 41 |
+
"b64bfc2ffb7e2587": "To receive an uploaded file in an endpoint, you can define a path operation function parameter as `UploadFile` or use `File` to receive the file as \"form data\". \n\nFirst, ensure you have `python-multipart` installed:\n```console\n$ pip install python-multipart\n```\nThen, you can use `UploadFile` directly from `fastapi`:\n```python\nfrom fastapi import UploadFile\n```\nAlternatively, use `File`, which is a class that inherits directly from `Form` [2][1][5].\n\nYou can also use `bytes` to receive the file contents as bytes, but be aware that this stores the whole contents in memory [5]. \n\nHere's an example of using `File` and `UploadFile`:\n```python\nfrom fastapi import FastAPI, File, UploadFile\n\napp = FastAPI()\n\n@app.post(\"/uploadfile/\")\nasync def create_upload_file(file: UploadFile = File(...)):\n return {\"filename\": file.filename}\n\n@app.post(\"/uploadfilebytes/\")\nasync def create_upload_file_bytes(file: bytes = File(...)):\n return {\"file_size\": len(file)}\n```",
|
| 42 |
+
"c2a97409bd7ff246": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 43 |
+
"0c77bd79425791e0": "To run a task in the background after returning a response, you can use the `BackgroundTasks` feature in FastAPI. Here's an example of how to use it:\n\nYou can declare a parameter in a path operation function or dependency function with the type `BackgroundTasks`, and then use it to schedule the execution of background tasks after the response is sent [2].\n\n```python\nfrom fastapi import FastAPI, BackgroundTasks\n\napp = FastAPI()\n\ndef task1():\n print(\"Task 1 is running in the background\")\n\n@app.get(\"/items/\")\nasync def read_items(background_tasks: BackgroundTasks):\n background_tasks.add_task(task1)\n return {\"message\": \"Item read in the background\"}\n```\n\nIn this example, `task1` will be executed in the background after the response is sent.\n\nBackground tasks are useful for operations that need to happen after a request, but that the client doesn't really have to be waiting for the operation to complete before receiving the response. This includes, for example, email notifications sent after performing an action, or processing data [1].\n\nNote that background tasks only run if a 2xx response is sent back. If an exception is raised, such as an `HTTPException`, the background tasks will not be executed [3]. \n\nYou can also use it with dependencies and path operation functions.\n\nYou can find more information about `BackgroundTasks` in the FastAPI documentation [2] and in the FastAPI codebase [4].",
|
| 44 |
+
"972a4017ae75fff6": "{\"faithful\": true, \"correct\": true}",
|
| 45 |
+
"93e4da38febbad45": "To enable CORS in FastAPI, you can use the `CORSMiddleware`. Here's how:\n\n* Import `CORSMiddleware`.\n* Create a list of allowed origins (as strings).\n* Add it as a \"middleware\" to your FastAPI application.\n\nYou can configure the following parameters:\n* `allow_origins` - A list of origins that should be permitted to make cross-origin requests.\n* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`.\n* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`.\n* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`.\n\nExample:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\norigins = [\"http://localhost:8080\"]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n```\nThis will enable CORS for your frontend to call the API [2]. \n\nFor more information on CORS, you can check the [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) [3].",
|
| 46 |
+
"ed4e88a34c414f39": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 47 |
+
"73278802f8c96ab7": "You can declare optional query parameters with default values by setting their default value to a specific value, such as `None`, or other default values. For example, to declare an optional query parameter `q` with a default value of `\"fixedquery\"` and a `min_length` of `3`, you can use [2]:\n```python\nq: str | None = \"fixedquery\"\n```\nAlternatively, you can declare an optional query parameter by setting its default value to `None` [1]:\n```python\nq: str | None = None\n```\nThis makes the parameter optional, and it will be `None` by default if not provided. You can also use other default values, such as integers, like `skip=0` and `limit=10` [4]. \n\nYou can also declare some parameters as required, some as having a default value, and some entirely optional [3]. \n\nFor more complex scenarios, such as declaring a required parameter that can be `None`, you can declare that `None` is a valid type but simply do not declare a default value [5].",
|
| 48 |
+
"bd3081c4d8477eb9": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 49 |
+
"6aaaaa987c09a280": "You can declare the type of a path parameter in the function using standard Python type annotations. For example, to declare a path parameter `item_id` with type `int`, you can do [1]:\n```python\n# item_id is declared to be an int\n```\nThis will give you editor support inside of your function, with error checks, completion, etc. \n\nHere's an example code snippet [1]:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n return {\"item_id\": item_id}\n```",
|
| 50 |
+
"3a4ead16201ccee3": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 51 |
+
"8bfe811dd2aa8aa7": "To receive a JSON request body using a Pydantic model, you need to declare a Pydantic model with the fields you want to receive and then use it as a parameter in your route function. \n\nHere's a basic example using `BaseModel` from Pydantic [5]:\n```python\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n name: str\n description: str\n```\nThen, you can use `Item` as a parameter in your route function:\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n name: str\n description: str\n\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n return item\n```\nIn this example, FastAPI will automatically extract the JSON data from the request body, validate it against the `Item` model, and return it as a JSON response. \n\nYou can find more information about using Pydantic models with FastAPI in the documentation [5].",
|
| 52 |
+
"a33754f075943c6c": "```\n{\n \"faithful\": false,\n \"correct\": true\n}\n```",
|
| 53 |
+
"ded9e337fafb7dbe": "To receive form data instead of JSON, you can use `Form` in your FastAPI application. First, ensure you have `python-multipart` installed, for example, by running `pip install python-multipart` in your virtual environment.\n\nYou can declare form parameters using `Form` the same way you would for `Body` or `Query`. For instance, to receive `username` and `password` as form fields, you can define them as `Form` parameters. Here's a basic example of how to define a `Form` parameter [5]:\n```python\nfrom fastapi import FastAPI, Form\n\napp = FastAPI()\n\n@app.post(\"/login/\")\ndef login(username: str = Form(...), password: str = Form(...)):\n return {\"username\": username}\n```\nThis way, FastAPI will correctly parse the form data sent in the request body.\n\nNote that when using `Form`, you cannot also declare `Body` fields that you expect to receive as JSON in the same request, as the request body will be encoded using `application/x-www-form-urlencoded` or `multipart/form-data` instead of `application/json` [3][2].",
|
| 54 |
+
"dea9f0756a44f5ab": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 55 |
+
"31bbe18f96bad94e": "To return a custom error response with a specific status code and message, you can return a `Response` object directly, such as a `JSONResponse`, and set the status code and content accordingly.\n\nFor example, you can use `JSONResponse` to return a custom error response:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n # Custom error response\n return JSONResponse(content={\"error\": \"Item not found\"}, status_code=404)\n```\nAlternatively, you can use the `status_code` parameter in a path operation decorator to specify the status code, and return a response body:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/items/\", status_code=404)\ndef read_items():\n return {\"error\": \"Item not found\"}\n```\nNote that when returning a `Response` object directly, it will not be serialized with a model, so make sure to include the required data and ensure it is valid JSON if using `JSONResponse` [1][2].",
|
| 56 |
+
"05e7a16f3c5af35b": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 57 |
+
"ed6d99c40582e3f3": "You can use the `response_model` parameter in FastAPI to control which fields are returned in the response. This is particularly useful when you want to filter data to expose only public fields and avoid exposing sensitive information.\n\nHere's an example:\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass InternalItem(BaseModel):\n name: str\n description: str | None = None\n secret_key: str\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> InternalItem:\n item = InternalItem(\n name=\"Foo\", description=\"A very nice Item\", secret_key=\"supersecret\"\n )\n return item\n```\nIn this example, even though the `get_item` function returns an `InternalItem` instance, the `response_model` parameter ensures that only the fields defined in the `Item` model are returned in the response, effectively filtering out the `secret_key` field [5].\n\nYou can also use `response_model_exclude_unset=True` to exclude fields with default values that are not explicitly set [3].\n\nAdditionally, you can use inheritance to define a response model that filters out certain fields. For example:\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass BaseUser(BaseModel):\n name: str\n email: str\n\nclass UserIn(BaseUser):\n password: str\n\n@app.get(\"/users/me\", response_model=BaseUser)\nasync def get_user() -> UserIn:\n user = UserIn(\n name=\"Foo\", email=\"foo@example.com\", password=\"supersecret\"\n )\n return user\n```\nIn this example, even though the `get_user` function returns a `UserIn` instance, the `response_model` parameter ensures that only the fields defined in the `BaseUser` model are returned in the response, effectively filtering out the `password` field [1].",
|
| 58 |
+
"6e53660fda3fe6f0": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 59 |
+
"30c573ad8e31a894": "You can serve static files like images or CSS using the `StaticFiles` class in FastAPI. To do this, you would import `StaticFiles` from `fastapi.staticfiles` and then mount a `StaticFiles()` instance at a specific path [1].\n\nHere's an example of how to serve static files:\n```python\nfrom fastapi.staticfiles import StaticFiles\n\n# Mount StaticFiles at the \"/static\" path\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```\nIn this example, any files in the `static` directory will be served at the `/static` path.\n\nYou can also use `url_for()` inside templates to link to static files. For example, you can link to a CSS file at `static/styles.css` like this:\n```jinja\n<link rel=\"stylesheet\" href=\"{{ url_for('static', path='styles.css') }}\">\n```\nThis will link to the CSS file at `/static/styles.css` [2].\n\nFastAPI will automatically serve static files from the specified directory. For example, if you have a file `styles.css` in the `static` directory, it will be served at `/static/styles.css` [3].\n\nYou can also self-host JavaScript and CSS files for the API docs. To do this, you would download the required files and serve them using `StaticFiles`. For example, you can serve Swagger UI and ReDoc files like this:\n```python\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```\nThen, you can access the files at `/static/redoc.standalone.js`, `/static/swagger-ui-bundle.js`, and `/static/swagger-ui.css` [4].",
|
| 60 |
+
"a68ebfbd00feda42": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 61 |
+
"039a8d5c6c45498a": "To write tests for your FastAPI endpoints, you can use the `TestClient` provided by Starlette, which is the foundation of FastAPI. This allows you to simulate HTTP requests to your application and verify the responses.\n\nHere's a basic example of how you can structure your tests:\n\nYou can write synchronous tests using the `TestClient` without using `async` functions, as you've seen so far. However, for more complex scenarios, such as querying your database asynchronously, you might want to use asynchronous functions in your tests [1].\n\nFastAPI testing is based on [HTTPX](https://www.python-httpx.org), which is designed based on Requests, making it familiar and intuitive. You can use [pytest](https://docs.pytest.org/) directly with FastAPI for testing [5].\n\nFor an example of creating a test client and writing tests, refer to the documentation on [Testing](../tutorial/testing.md) in the FastAPI docs.\n\nIf you're looking for information on how to upgrade FastAPI versions, ensure you have tests for your app, then you can upgrade and verify that all your code works correctly by running your tests [4].",
|
| 62 |
+
"1d8b76937c42b199": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```",
|
| 63 |
+
"e927b7e65574fea1": "To use WebSockets in FastAPI, you can create a WebSocket endpoint using the `@app.websocket()` decorator. Here's an example [4]:\n```python\nfrom fastapi import FastAPI, WebSocket\n\napp = FastAPI()\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Message text was: {data}\")\n```\nThis code creates a WebSocket endpoint at `/ws` that accepts WebSocket connections, receives text messages, and sends responses back to the client.\n\nYou can also use the `WebSocket` class directly from `fastapi` [5]:\n```python\nfrom fastapi import WebSocket\n```\nFastAPI provides the `WebSocket` class as a convenience, but it comes directly from Starlette [3].\n\nTo try out WebSockets with FastAPI, you can run your application using `fastapi dev` and access it in your browser at `http://127.0.0.1:8000` [2].",
|
| 64 |
+
"89bf4501c53c4bfa": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 65 |
+
"141b59b90f7c2b7c": "You can set a cookie in a response by declaring a parameter of type `Response` in your path operation function and then setting the cookie in that response object. \n\nHere's an example of setting cookies using the `Response` parameter [2]:\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items(response: Response):\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return [{\"item\": \"Item 1\"}]\n```\n\nAlternatively, you can create a response directly and set cookies in it [1]:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n response = JSONResponse(content=[{\"item\": \"Item 1\"}], media_type=\"application/json\")\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return response\n```\n\nYou can also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse` for this purpose [1]. \n\nFor more information on available parameters and options, check the [Starlette documentation](https://www.starlette.dev/responses/#set-cookie).",
|
| 66 |
+
"bc6cf586200ed0da": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 67 |
+
"8ec7c21825a56cc5": "You can add custom headers to a response by returning a `Response` directly and passing the headers as an additional parameter [1].\n\nFor example, you can create a response and add headers using the `headers` parameter:\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n headers = {\"X-Custom-Header\": \"Custom Value\"}\n return Response(content=\"Hello, World!\", media_type=\"text/plain\", headers=headers)\n```\nAlternatively, you can add custom headers when handling errors [3].\n\nIt's also worth noting that when returning a custom `Response`, you can add headers directly to the `Response` object [4].\n\nAdditionally, custom proprietary headers can be added using the `X-` prefix, but if you want a client in a browser to be able to see them, you need to add them to your CORS configurations [2].",
|
| 68 |
+
"4d096a4a532f2c1e": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 69 |
+
"975c6f5b87faaf0a": "To implement JWT token authentication, you'll need to follow these steps:\n\n## Step 1: Install Required Modules and Generate a Secret Key\n\nFirst, install the required modules and generate a secure random secret key using OpenSSL [3]:\n```console\n$ openssl rand -hex 32\n```\nCopy the output to the variable `SECRET_KEY`.\n\n## Step 2: Define Constants and Pydantic Model\n\nCreate variables for the algorithm used to sign the JWT token (`ALGORITHM`), expiration of the token, and a Pydantic Model for the token endpoint response [3].\n\n## 3: Handle JWT Tokens\n\nCreate a utility function to generate a new access token.\n\n## 4: Update the `/token` Path Operation\n\nCreate a `timedelta` with the expiration time of the token and return a real JWT access token [5].\n\n## 5: Use the JWT Token for Authentication\n\nUse the JWT token to authenticate users. For example, you can use the `Authorization` header with the `Bearer` token to authenticate requests [1].\n\nHere's an example of how the JWT token might look:\n```\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\n```\nNote that the JWT token is not encrypted, but it's signed, allowing you to verify its authenticity [4].\n\n## Example Code\n\nHere's an example code snippet that demonstrates how to generate a JWT token:\n```python\n# Create a random secret key\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\n\n# Define constants\nALGORITHM = \"HS256\"\n\n# Create a Pydantic Model for the token endpoint response\nfrom pydantic import BaseModel\n\nclass Token(BaseModel):\n access_token: str\n token_type: str\n\n# Create a utility function to generate a new access token\nimport jwt\nfrom datetime import datetime, timedelta\n\ndef create_access_token(data: dict, expires_delta: timedelta | None = None):\n to_encode = data.copy()\n if expires_delta:\n expire = datetime.utcnow() + expires_delta\n else:\n expire = datetime.utcnow() + timedelta(minutes=15)\n to_encode.update({\"exp\": expire})\n encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n return encoded_jwt\n```\n[3][5]",
|
| 70 |
+
"272379647bac6cdc": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```",
|
| 71 |
+
"f0fe845072d0bd1c": "FastAPI's dependency injection system allows your code, specifically path operation functions, to declare dependencies that are required to work. The system then takes care of providing these dependencies, minimizing code repetition. This is achieved by declaring dependencies as functions that can take parameters similar to path operation functions. You then use the `Depends` annotation to specify these dependencies in your path operation functions. FastAPI will execute the dependency functions and inject their results into your path operation functions [2][1][3].\n\nFor example, you can create a dependency function that expects query parameters and returns a dictionary containing those values. You then declare this dependency in your path operation function using `Depends`, and FastAPI will take care of executing it and injecting the results [5].\n\nIt's also recommended to avoid creating class dependencies when possible, and instead create regular function dependencies that return class instances [4]. \n\nHere is an example of a simple dependency:\n```python\nfrom fastapi import Depends, FastAPI, Query\n\napp = FastAPI()\n\ndef get_query(q: str = Query(None, description=\"Query string\")):\n return {\"q\": q}\n\n@app.get(\"/items/\")\nasync def read_items(query: dict = Depends(get_query)):\n return query\n```",
|
| 72 |
+
"7265993334fc7260": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 73 |
+
"2e2c8e796f8cf952": "`jsonable_encoder()` is a function provided by FastAPI to convert data types, such as Pydantic models, to JSON-compatible data structures, like `dict` or `list`. This is necessary when you need to store data in a database or return it in a response, as some data types, like `datetime` objects, are not compatible with JSON [1].\n\nYou need `jsonable_encoder()` in scenarios such as [2][4][5]:\n* Storing data in a database that only accepts JSON-compatible data.\n* Returning Pydantic models in a response, like `JSONResponse`, without modifying them first.\n* When you don't declare a response model, FastAPI uses `jsonable_encoder` to convert data to JSON.\n\nThe function takes an object, like a Pydantic model, and returns its JSON-compatible version. For example, it converts `datetime` objects to strings in ISO format and Pydantic models to dictionaries [2].\n\nHere's an example of using `jsonable_encoder`:\n```python\nfrom fastapi.encoders import jsonable_encoder\nfrom datetime import datetime\n\nclass Item:\n def __init__(self, name: str, created_at: datetime):\n self.name = name\n self.created_at = created_at\n\nitem = Item(\"Example Item\", datetime.now())\nencoded_item = jsonable_encoder(item)\n```\nIn this case, `encoded_item` would be a dictionary with `name` and `created_at` (as a string in ISO format) [3].",
|
| 74 |
+
"50f57221bcd0428c": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 75 |
+
"2ae758cb8291a8b0": "In FastAPI, the main difference between using `async def` and `def` for endpoints (or path operations) lies in how they handle asynchronous operations.\n\nWhen you declare an endpoint with `async def`, FastAPI expects that the function will perform asynchronous operations using `await`. This allows the event loop to continue running other tasks while waiting for I/O operations to complete.\n\nOn the other hand, if you declare an endpoint with `def`, FastAPI runs it in an external threadpool. This allows the endpoint to perform blocking operations without blocking the event loop.\n\nHere are some guidelines on when to use each:\n\n* Use `async def` when:\n\t+ You're using third-party libraries that support asynchronous operations with `await`.\n\t+ Your endpoint needs to perform I/O-bound operations, such as making API calls or reading from a database that supports async operations.\n* Use `def` when:\n\t+ You're using third-party libraries that don't support asynchronous operations.\n\t+ Your endpoint performs CPU-bound operations or blocking I/O operations.\n\nYou can mix and match `async def` and `def` endpoints in your application, and FastAPI will handle them accordingly.\n\nIt's worth noting that if you're unsure, using `def` is a safe choice, and FastAPI will still work asynchronously and be fast. However, using `async def` when possible can provide some performance optimizations [1][5].",
|
| 76 |
+
"bdab31ce6c7731a6": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 77 |
+
"68687f93e494f3fd": "To run cleanup code after the response is sent, a dependency can use the default `scope=\"request\"` when defined with `yield`. This is the default behavior for dependencies with `yield`, as stated in [1][2].\n\nHere's an example:\n```python\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close() # This will run after the response is sent\n\n@app.get(\"/items/\")\nasync def read_items(db: Annotated[DBSession, Depends(get_db)]):\n return db.query(Item).all()\n```\nIn this case, the `db.close()` code will run after the response is sent back to the client.\n\nAlternatively, you can explicitly set `scope=\"request\"`:\n```python\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close() # This will run after the response is sent\n\n@app.get(\"/items/\")\nasync def read_items(db: Annotated[DBSession, Depends(get_db, scope=\"request\")]):\n return db.query(Item).all()\n```",
|
| 78 |
+
"13f8ab268d24a581": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 79 |
+
"4e90aeb13dead0e1": "To customize or extend the generated OpenAPI schema in FastAPI, you can override the default OpenAPI schema generation by creating a custom function, typically named `custom_openapi()`. This function utilizes the utility function `get_openapi()` to generate the OpenAPI schema, allowing for modifications as needed.\n\nHere's a step-by-step approach:\n\n1. **Generate the OpenAPI Schema**: Use `get_openapi()` to create the OpenAPI schema within your `custom_openapi()` function.\n2. **Modify the Schema**: Adjust the generated schema according to your requirements. For example, you can add a custom logo by including a `x-logo` extension in the `info` object.\n3. **Cache the Schema**: Implement caching by storing the generated schema in the `.openapi_schema` property. This ensures the schema is generated only once and reused for subsequent requests.\n4. **Override the `.openapi()` Method**: Replace the default `.openapi()` method of your FastAPI application with your `custom_openapi()` function.\n\nExample code snippets illustrate these steps [1]:\n```python\n# Generate the OpenAPI schema\ndef custom_openapi(self) -> dict[str, Any]:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n # ... other parameters\n )\n # Modify the OpenAPI schema\n self.openapi_schema[\"info\"][\"x-logo\"] = {\"url\": \"https://example.com/logo.png\"}\n return self.openapi_schema\n\n# Cache the OpenAPI schema\napp.openapi_schema = custom_openapi(app)\n\n# Override the method\napp.openapi = custom_openapi.__get__(app, type(app))\n```\nFastAPI internally calls the `.openapi()` method to generate the OpenAPI schema. The first time it's called, the result is stored in `app.openapi_schema`. Subsequent calls return the cached result to avoid regeneration costs [3].\n\nBy following these steps and examples, you can effectively customize and extend the generated OpenAPI schema in your FastAPI application.",
|
| 80 |
+
"0ba2a174778ba593": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 81 |
+
"139935ae46ae6944": "When request validation fails in FastAPI, it returns a `RequestValidationError`, which is a sub-class of `ValidationException`, but not directly a sub-class of Pydantic's `ValidationError` as previously documented [1].\n\nThe default error response for `RequestValidationError` includes a JSON payload with a 422 status code, containing details about the validation errors.\n\nTo customize the error response, you can create a custom exception handler for `RequestValidationError`. Here's an example:\n\n```python\nfrom fastapi import FastAPI, Request, status\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request: Request, exc: RequestValidationError):\n return JSONResponse(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n content={\"detail\": exc.errors()},\n )\n```\n\nThis handler returns a JSON response with a 422 status code and the validation error details.\n\nNote that if you want to handle both `RequestValidationError` and `ValidationError`, you need to create separate exception handlers for each, as they are not directly related [1].\n\nAlso, when using Pydantic V2, the OpenAPI definitions for `ValidationError` and `HTTPValidationError` might need to be updated [2].",
|
| 82 |
+
"86fb8afb91309d8c": "```\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 83 |
+
"bb6c0853d33c66ee": "The OAuth2 password flow in FastAPI works as follows [1]:\n* The user types their `username` and `password` in the frontend and hits `Enter`.\n* The frontend sends the `username` and `password` to a specific URL in the API (declared with `tokenUrl=\"token\"`).\n* The API checks the `username` and `password` and responds with a \"token\".\n* The frontend stores the token temporarily.\n* When the frontend needs to fetch more data from the API, it sends a header `Authorization` with a value of `Bearer` plus the token.\n\nFastAPI provides tools to implement this flow, including:\n* `OAuth2PasswordBearer`: a class for OAuth2 with the Password flow, using a Bearer token.\n* `OAuth2PasswordRequestForm`: a dependency class to collect `username` and `password` as form data for an OAuth2 password flow.\n* `OAuth2PasswordRequestFormStrict`: similar to `OAuth2PasswordRequestForm`, but requires the client to send the form field `grant_type` with the value `\"password\"`.\n\nHere's an example of using `OAuth2PasswordRequestForm` [3]:\n```python\nfrom typing import Annotated\nfrom fastapi import Depends, FastAPI\nfrom fastapi.security import OAuth2PasswordRequestForm\n\napp = FastAPI()\n\n@app.post(\"/login\")\ndef login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):\n # process form data\n return {}\n```",
|
| 84 |
+
"488a51700cb3ac1f": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 85 |
+
"c9129442f61cf09d": "You can run code on application startup and shutdown using event handlers. \n\nFor startup, you can use the `startup` event handler. To add a function that should be run before the application starts, declare it with the event `\"startup\"`. \n\nFor shutdown, you can use the `shutdown` event handler. To add a function that should be run when the application is shutting down, declare it with the event `\"shutdown\"`.\n\nHowever, the recommended way is to use the `lifespan` parameter of the `FastAPI` app. \n\nHere is an example of how to use `startup` and `shutdown` event handlers [3]:\n```python\n# Add event handlers\n@app.on_event(\"startup\")\nasync def startup_event():\n # Code to run on startup\n pass\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n # Code to run on shutdown\n pass\n```\n\nAlternatively, you can use `lifespan` [3]:\n```python\n# Use lifespan\n@app.lifespan\nasync def lifespan(app: FastAPI):\n # Code to run on startup\n try:\n # Startup code here\n yield\n finally:\n # Shutdown code here\n pass\n```\n\nYou can also define these event handlers in an `APIRouter` [1][5]:\n```python\n# Define event handlers in APIRouter\nrouter = APIRouter()\n\n@router.on_event(\"startup\")\nasync def startup_event():\n # Code to run on startup\n pass\n\n@router.on_event(\"shutdown\")\nasync def shutdown_event():\n # Code to run on shutdown\n pass\n```",
|
| 86 |
+
"5b5ba7e5f82cf146": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 87 |
+
"882d04fd423d011b": "Yes, you can mount another FastAPI application under a path prefix. This is achieved through the `mount` method, which allows you to add a completely independent application at a specific path. The sub-application will handle everything under that path, with its own path operations [2].\n\nFor example, you can create a main FastAPI application and a sub-application, then mount the sub-application at a specific path:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\nsubapi = FastAPI()\n\n@app.get(\"/\")\ndef read_main():\n return {\"message\": \"Hello World from main app\"}\n\n@subapi.get(\"/sub\")\ndef read_sub():\n return {\"message\": \"Hello World from sub API\"}\n\napp.mount(\"/subapi\", subapi)\n```\nIn this case, the sub-application `subapi` will be served at the path `/subapi` [2].\n\nFastAPI will internally use the `root_path` smartly, so it will just work when mounting a sub-application while using a proxy [1].\n\nHowever, there is a known limitation when trying to mount a sub-application under an `APIRouter`. Currently, the best practice is to mount your sub-application directly to the main FastAPI instance using the full path prefix [5].",
|
| 88 |
+
"be775199270966f3": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 89 |
+
"82bd35ba5e92141c": "FastAPI runs regular `def` endpoints without blocking the event loop by executing them in an external threadpool. This is done using the `run_in_threadpool` function, which is called from `run_endpoint_function` in `fastapi/routing.py`. When a path operation function or dependency is defined with a normal `def` instead of `async def`, FastAPI runs it in this external threadpool and then awaits the result, preventing the server from being blocked [4][1]. \n\nFor example, in `fastapi/routing.py`, the `run_endpoint_function` is defined as:\n```python\nasync def run_endpoint_function(\n *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool\n) -> Any:\n # Only called by get_request_handler. Has been split into its own function to\n # facilitate profiling endpoints, since inner functions are harder to profile.\n assert dependant.call is not None, \"dependant.call must be a function\"\n\n if is_coroutine:\n return await dependant.call(**values)\n else:\n return await run_in_threadpool(dependant.call, **values)\n``` [4]\n\nThis allows regular `def` functions to be used for I/O-bound operations without blocking the event loop, while still allowing `async def` functions to be used for true asynchronous operations.",
|
| 90 |
+
"d6b83241e3601866": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 91 |
+
"c44ee40f72c8863d": "To manage configuration and settings with environment variables, you can use Pydantic's `Settings` management utility. First, install the `pydantic-settings` package using pip:\n```console\n$ pip install pydantic-settings\n```\nor install the `all` extras with FastAPI:\n```console\n$ pip install \"fastapi[all]\"\n```\nThen, create a `Settings` object by importing `BaseSettings` from Pydantic and creating a sub-class. Declare class attributes with type annotations and possibly default values. Pydantic will read environment variables in a case-insensitive way, convert and validate the data, and provide it in the `settings` object [1].\n\nFor example, you can create a `config.py` file with:\n```python\nfrom pydantic import BaseSettings\n\nclass Settings(BaseSettings):\n app_name: str\n admin_email: str\n```\nAnd use it in a `main.py` file:\n```python\nfrom config import Settings\n\nsettings = Settings()\n\nprint(settings.app_name)\nprint(settings.admin_email)\n```\nYou can also use the `settings` object in your application and run the server with environment variables:\n```console\n$ ADMIN_EMAIL=\"deadpool@example.com\" APP_NAME=\"ChimichangApp\" fastapi run main.py\n```\nAdditionally, you can put the settings in another module file, use it in a dependency, and simplify testing by overriding the dependency with custom settings [2][4].",
|
| 92 |
+
"e4f78193d68b6b6e": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 93 |
+
"82d9aa9f9a576050": "The `APIRouter` class is defined in the `fastapi.routing` module, specifically in the `fastapi/routing.py` file [5]. You can also import it directly from `fastapi` using `from fastapi import APIRouter` [1].",
|
| 94 |
+
"b0bb3a40077f98e0": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 95 |
+
"59438f17dbc84b4b": "The `OAuth2PasswordBearer` class is implemented in the `fastapi/security/oauth2.py` file [1].",
|
| 96 |
+
"792efaddc809e2e6": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 97 |
+
"c818ba985d54aa6d": "The `jsonable_encoder` function is implemented in the `fastapi/encoders.py` file [2]. \n\nHere's a code snippet showing its definition:\n```python\ndef jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n # ... rest of the function definition ...\n```\nYou can also find more information about this function in the documentation [1][3][4].",
|
| 98 |
+
"10a6b3b325de51fd": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 99 |
+
"9227dcdf1035977f": "The `BackgroundTasks` class is defined in `fastapi/background.py`, and it directly inherits from `StarletteBackgroundTasks` [4].\n\nIt's also mentioned that `BackgroundTasks` comes directly from [`starlette.background`](https://www.starlette.dev/background/), but is imported into FastAPI for convenience [1]. \n\nYou can import it directly from `fastapi`:\n```python\nfrom fastapi import BackgroundTasks\n``` [3]",
|
| 100 |
+
"a4dc6f99562939c6": "```\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 101 |
+
"592174ef25b3328f": "The `HTTPException` in FastAPI is defined in `fastapi/exceptions.py` [1]. \n\nHere's a code snippet showing its definition:\n\n```python\nclass HTTPException(StarletteHTTPException):\n # ...\n```",
|
| 102 |
+
"60df36e73095ba80": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 103 |
+
"38b76e1b62e47833": "The main FastAPI application class is defined in the `FastAPI` class, which can be imported directly from `fastapi`:\n\n```python\nfrom fastapi import FastAPI\n```\n\nYou can find more information about the `FastAPI` class, including its parameters, attributes, and methods, in the [FastAPI class documentation][2].",
|
| 104 |
+
"c2b74838e135b77b": "```json\n{\n \"faithful\": true,\n \"correct\": false\n}\n```",
|
| 105 |
+
"5712d5ff0bd192bb": "I couldn't find this in the indexed codebase.",
|
| 106 |
+
"8bb62331c0aed10c": "```json\n{\n \"faithful\": true,\n \"correct\": false\n}\n```",
|
| 107 |
+
"2a2e671673420332": "The `TestClient` that FastAPI provides for testing is located in `fastapi.testclient`. You can import it directly as follows [1][4]:\n```python\nfrom fastapi.testclient import TestClient\n```\nAlternatively, you can also use `from starlette.testclient import TestClient`, as FastAPI provides the same `starlette.testclient` as `fastapi.testclient` for convenience [2].",
|
| 108 |
+
"5871612da574c71d": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```",
|
| 109 |
+
"e2287d243f06562c": "I couldn't find this in the indexed codebase.",
|
| 110 |
+
"d7ed84a4e1ac2f4c": "I couldn't find this in the indexed codebase.",
|
| 111 |
+
"8fd62cb6e1b9d29c": "To integrate Celery task queues with FastAPI, you can use Celery as a task queue manager, which allows you to run background tasks in multiple processes and servers. Here's a general approach:\n\nFirst, install the required packages:\n```bash\npip install celery\npip install redis # or other message brokers like RabbitMQ\n```\nThen, configure Celery with a message broker like Redis or RabbitMQ.\n\nNext, create a Celery instance and define your tasks:\n```python\nfrom celery import Celery\n\ncelery = Celery(\"tasks\", broker=\"redis://localhost:6379/0\")\n\n@celery.task\ndef my_task(x, y):\n # perform some task\n print(f\"Task result: {x + y}\")\n```\nIn your FastAPI application, import the Celery instance and use it to run tasks:\n```python\nfrom fastapi import FastAPI\nfrom celery import Celery\n\napp = FastAPI()\ncelery = Celery(\"tasks\", broker=\"redis://localhost:6379/0\")\n\n@app.get(\"/\")\ndef read_root():\n celery.send_task(\"my_task\", args=[2, 2])\n return {\"message\": \"Task sent\"}\n```\nMake sure to run the Celery worker separately:\n```bash\ncelery -A tasks worker --loglevel=info\n```\nThis is a basic example to get you started. For more information, refer to the Celery documentation and FastAPI documentation [2].",
|
| 112 |
+
"9b0871cd909b0135": "I couldn't find this in the indexed codebase.",
|
| 113 |
+
"5f4a45bd0a897d76": "I couldn't find this in the indexed codebase.",
|
| 114 |
+
"95b2ceba4706cca8": "I couldn't find this in the indexed codebase.",
|
| 115 |
+
"615a9cbcb33f39c5": "I couldn't find this in the indexed codebase."
|
| 116 |
}
|
src/ask.py
CHANGED
|
@@ -58,7 +58,7 @@ def build_prompt(question: str, hits: list[dict]) -> str:
|
|
| 58 |
parts = []
|
| 59 |
for i, h in enumerate(hits, 1):
|
| 60 |
parts.append(f"[{i}] ({h['meta']['source_type']}: "
|
| 61 |
-
|
| 62 |
context = "\n\n---\n\n".join(parts)
|
| 63 |
return f"Context chunks:\n\n{context}\n\nQuestion: {question}"
|
| 64 |
|
|
|
|
| 58 |
parts = []
|
| 59 |
for i, h in enumerate(hits, 1):
|
| 60 |
parts.append(f"[{i}] ({h['meta']['source_type']}: "
|
| 61 |
+
f"{h['meta']['path']})\n{h['text'][:2500]}")
|
| 62 |
context = "\n\n---\n\n".join(parts)
|
| 63 |
return f"Context chunks:\n\n{context}\n\nQuestion: {question}"
|
| 64 |
|
src/eval.py
CHANGED
|
@@ -33,7 +33,7 @@ EMBED_MODEL = "BAAI/bge-small-en-v1.5"
|
|
| 33 |
QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
|
| 34 |
K = 5
|
| 35 |
REFUSAL_TEXT = "I couldn't find this in the indexed codebase"
|
| 36 |
-
SLEEP_BETWEEN_LLM_CALLS =
|
| 37 |
|
| 38 |
JUDGE_PROMPT = """\
|
| 39 |
You are grading a RAG system's answer. Given the question, the context the
|
|
@@ -126,18 +126,27 @@ def main() -> None:
|
|
| 126 |
llm_model = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")
|
| 127 |
|
| 128 |
def llm(prompt: str, system: str | None = None) -> str:
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
refusal_ok, faithful, correct = [], [], []
|
| 143 |
for item, hits in zip(items, retrieved_per_q):
|
|
|
|
| 33 |
QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
|
| 34 |
K = 5
|
| 35 |
REFUSAL_TEXT = "I couldn't find this in the indexed codebase"
|
| 36 |
+
SLEEP_BETWEEN_LLM_CALLS = 5 # stay under free-tier rate limits
|
| 37 |
|
| 38 |
JUDGE_PROMPT = """\
|
| 39 |
You are grading a RAG system's answer. Given the question, the context the
|
|
|
|
| 126 |
llm_model = os.environ.get("GROQ_MODEL", "openai/gpt-oss-120b")
|
| 127 |
|
| 128 |
def llm(prompt: str, system: str | None = None) -> str:
|
| 129 |
+
key = cache_key(llm_model, system or "", prompt)
|
| 130 |
+
if key in cache:
|
| 131 |
+
return cache[key]
|
| 132 |
+
messages = ([{"role": "system", "content": system}] if system else [])
|
| 133 |
+
messages.append({"role": "user", "content": prompt})
|
| 134 |
+
out = None
|
| 135 |
+
for attempt in range(4):
|
| 136 |
+
try:
|
| 137 |
+
out = client.chat.completions.create(
|
| 138 |
+
model=llm_model, messages=messages,
|
| 139 |
+
temperature=0.1).choices[0].message.content
|
| 140 |
+
break
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f" [retry {attempt + 1}/4] {str(e)[:200]}; waiting 30s")
|
| 143 |
+
time.sleep(30)
|
| 144 |
+
if out is None:
|
| 145 |
+
raise RuntimeError("LLM call failed 4 times; try again later")
|
| 146 |
+
cache[key] = out
|
| 147 |
+
save_cache(cache)
|
| 148 |
+
time.sleep(SLEEP_BETWEEN_LLM_CALLS)
|
| 149 |
+
return out
|
| 150 |
|
| 151 |
refusal_ok, faithful, correct = [], [], []
|
| 152 |
for item, hits in zip(items, retrieved_per_q):
|