### Install Dependencies and Run Application (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Commands to install necessary Python dependencies using 'uv' and to start the FastAPI development server with auto-reloading enabled. ```bash # Install dependencies with UV uv add fastapi[standard] sqlmodel python-dotenv psycopg2-binary # Run development server fastapi dev ``` -------------------------------- ### Verify UV and Python Setup Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Checks if UV and Python are installed correctly by printing their versions. ```bash uv --version uv run python --version ``` -------------------------------- ### Install SQLModel Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Installs the SQLModel library using the UV package manager. ```bash uv add sqlmodel ``` -------------------------------- ### Database Configuration Examples (.env) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Examples of setting the DATABASE_URL environment variable for connecting to SQLite (local development) or PostgreSQL (production). ```bash # .env file for SQLite (local development) DATABASE_URL=sqlite:///database.db # .env file for PostgreSQL (production/Neon) DATABASE_URL=postgresql://user:password@ep-xxx.region.aws.neon.tech/neondb?sslmode=require ``` -------------------------------- ### Install UV Package Manager Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Installs the UV package manager. Use the appropriate command for your operating system. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Install PostgreSQL Driver and Dotenv Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Installs the necessary Python packages for PostgreSQL connectivity and environment variable management. ```bash uv add psycopg2-binary python-dotenv ``` -------------------------------- ### Verify FastAPI Installation Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Confirms the FastAPI installation by importing it and printing its version. ```python import fastapi; print(f'FastAPI version: {fastapi.__version__}') ``` -------------------------------- ### Neon Cloud Database Connection String Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Example of a PostgreSQL connection string for Neon, including user, password, host, database name, and SSL mode. ```dotenv DATABASE_URL=postgresql://user:pass@ep-xxx.region.aws.neon.tech/neondb?sslmode=require ``` -------------------------------- ### Run FastAPI Development Server Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Starts the FastAPI development server. Use 'fastapi dev' for automatic reloading or 'uv run uvicorn main:app --reload' for manual control. ```bash fastapi dev # OR uv run uvicorn main:app --reload ``` -------------------------------- ### FastAPI SQLite Database Setup and CRUD Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md This snippet sets up a FastAPI application with SQLite persistence using SQLModel for defining models and performing CRUD operations on students. ```python from fastapi import FastAPI, HTTPException, Depends from sqlmodel, SQLModel, Field, Session, create_engine, select DATABASE_URL = "sqlite:///students.db" engine = create_engine(DATABASE_URL) def create_db(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session class StudentBase(SQLModel): name: str age: int email: str class Student(StudentBase, table=True): id: int | None = Field(default=None, primary_key=True) class StudentCreate(StudentBase): pass app = FastAPI() @app.on_event("startup") def on_startup(): create_db() @app.post("/students", response_model=Student) def create_student(student: StudentCreate, session: Session = Depends(get_session)): db_student = Student.model_validate(student) session.add(db_student) session.commit() session.refresh(db_student) return db_student @app.get("/students") def list_students(session: Session = Depends(get_session)): return session.exec(select(Student)).all() @app.get("/students/{student_id}") def get_student(student_id: int, session: Session = Depends(get_session)): student = session.get(Student, student_id) if not student: raise HTTPException(404, "Student not found") return student @app.put("/students/{student_id}") def update_student(student_id: int, data: StudentCreate, session: Session = Depends(get_session)): student = session.get(Student, student_id) if not student: raise HTTPException(404, "Student not found") student.name = data.name student.age = data.age student.email = data.email session.commit() session.refresh(db_student) return student @app.delete("/students/{student_id}") def delete_student(student_id: int, session: Session = Depends(get_session)): student = session.get(Student, student_id) if not student: raise HTTPException(404, "Student not found") session.delete(student) session.commit() return {"message": "Student deleted"} ``` -------------------------------- ### Get All Students (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Retrieve a list of all student records from the database. This endpoint returns an array of student objects. ```bash # Get all students curl -X GET http://127.0.0.1:8000/students ``` -------------------------------- ### Get Single Student by ID (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Fetch a specific student record using their unique ID. Returns a 404 error if the student is not found. ```bash # Get student with ID 1 curl -X GET http://127.0.0.1:8000/students/1 # Get non-existent student (returns 404) curl -X GET http://127.0.0.1:8000/students/999 ``` -------------------------------- ### Get All Students Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Retrieves a list of all students currently stored in the database. Each student object includes their ID, name, age, and email. ```APIDOC ## GET /students ### Description Retrieves a list of all students. ### Method GET ### Endpoint /students ### Parameters (No path or query parameters for this endpoint) ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **Array of Student Objects**: Each object contains: - **id** (integer) - The unique identifier for the student. - **name** (string) - The name of the student. - **age** (integer) - The age of the student. - **email** (string) - The email address of the student. #### Response Example ```json [ {"id": 1, "name": "Ali Khan", "age": 20, "email": "ali@example.com"}, {"id": 2, "name": "Fatima Ahmed", "age": 22, "email": "fatima@example.com"} ] ``` ``` -------------------------------- ### Get Single Student by ID Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Retrieves a specific student by their ID from the in-memory list. Returns an error if the student is not found. ```python @app.get("/students/{student_id}") def get_student(student_id: int): for s in students: if s["id"] == student_id: return s return {"error": "Student not found"} ``` -------------------------------- ### Get Single Student by ID Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Retrieves a specific student's record using their unique ID. If the student with the specified ID is not found, a 404 error is returned. ```APIDOC ## GET /students/{student_id} ### Description Retrieves a specific student by their unique ID. ### Method GET ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (integer) - Required - The unique identifier of the student to retrieve. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the student. - **name** (string) - The name of the student. - **age** (integer) - The age of the student. - **email** (string) - The email address of the student. #### Error Response (404) - **detail** (string) - Message indicating the student was not found. #### Response Example (Success) ```json { "id": 1, "name": "Ali Khan", "age": 20, "email": "ali@example.com" } ``` #### Response Example (Not Found) ```json { "detail": "Student not found" } ``` ``` -------------------------------- ### Initialize FastAPI Project with UV Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Initializes a new FastAPI project named 'student-api', creates a virtual environment, and activates it. Assumes you are on Windows. ```bash uv init student-api cd student-api uv venv .venv\Scripts\activate ``` -------------------------------- ### Create New Student (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Add a new student record to the database. Requires name, age, and email. Returns the created student with a 201 status code. ```bash # Create a new student curl -X POST http://127.0.0.1:8000/students \ -H "Content-Type: application/json" \ -d '{"name": "Sara Ali", "age": 21, "email": "sara@example.com"}' ``` -------------------------------- ### Add FastAPI and Uvicorn to Project Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Adds FastAPI with standard extras (including uvicorn and pydantic) to the project dependencies using UV. ```bash uv add fastapi[standard] ``` -------------------------------- ### Troubleshooting Commands Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Provides common commands for troubleshooting FastAPI applications, including syncing dependencies, finding processes, killing processes, and resetting the SQLite database. ```bash uv sync # Fix missing modules lsof -i :8000 # Find process on port 8000 kill -9 # Kill process rm students.db # Reset SQLite ``` -------------------------------- ### Initialize GeminiModel Class Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Initializes the GeminiModel with various configuration options including model name, finetuning status, request distribution, caching, and temperature. It handles dynamic model endpoint construction for distributed requests. ```python class GeminiModel: """Class for the Gemini model.""" def __init__( self, model_name: str = "gemini-2.0-flash-001", finetuned_model: bool = False, distribute_requests: bool = False, cache_name: str | None = None, temperature: float = 0.01, **kwargs, ): self.model_name = model_name self.finetuned_model = finetuned_model self.arguments = kwargs self.distribute_requests = distribute_requests self.temperature = temperature model_name = self.model_name if not self.finetuned_model and self.distribute_requests: random_region = random.choice(GEMINI_AVAILABLE_REGIONS) model_name = GEMINI_URL.format( GCP_PROJECT=GCP_PROJECT, region=random_region, model_name=self.model_name, ) if cache_name is not None: cached_content = caching.CachedContent(cached_content_name=cache_name) self.model = GenerativeModel.from_cached_content( cached_content=cached_content ) else: self.model = GenerativeModel(model_name=model_name) ``` -------------------------------- ### Initialize Gemini LLM Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md A utility function to quickly initialize the Gemini model with a specified model name. ```python def gemini_llm(): return Gemini(model="gemini-1.5-flash") ``` -------------------------------- ### Gemini Class Integration Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md This section details the Gemini class, its supported models, and the asynchronous content generation method. ```APIDOC ## Gemini (BaseLlm Integration) This class extends `BaseLlm` for robust Gemini model integration, supporting asynchronous content generation and handling different API backends like Vertex AI and the Gemini API. ### Class Definition ```python class Gemini(BaseLlm): """Integration for Gemini models. Attributes: model: The name of the Gemini model. """ model: str = 'gemini-1.5-flash' ``` ### Supported Models This method returns a list of models supported by the Gemini integration. #### Method ```python @staticmethod def supported_models() -> list[str]: ``` #### Returns - `list[str]`: A list of supported model identifiers. ### Asynchronous Content Generation This method sends a request to the Gemini model asynchronously, with an option for streaming responses. #### Method ```python async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False) -> AsyncGenerator[LlmResponse, None]: ``` #### Arguments - **llm_request** (`LlmRequest`): The request object containing the prompt and configuration. - **stream** (`bool`, optional): If `True`, enables streaming of the response. Defaults to `False`. #### Yields - `LlmResponse`: The model's response, potentially streamed in chunks. ### API Client This property provides the API client instance used for interacting with the Gemini API. #### Method ```python @cached_property def api_client(self) -> Client: ``` #### Returns - `Client`: An instance of the API client. ### API Backend Detection This property determines the active API backend (Vertex AI or Gemini API). #### Method ```python @cached_property def _api_backend(self) -> GoogleLLMVariant: ``` #### Returns - `GoogleLLMVariant`: An enum value indicating the API backend. ``` -------------------------------- ### Create Student with Pydantic Model Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Defines a Pydantic model for student data and creates a POST endpoint to receive and return new student information. ```python from pydantic import BaseModel class Student(BaseModel): name: str age: int email: str @app.post("/students") def create_student(student: Student): return {"message": "Student created", "student": student} ``` -------------------------------- ### Create Basic FastAPI Endpoint Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Defines a simple FastAPI application with a root endpoint that returns a JSON message. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def home(): return {"message": "Hello, World!"} ``` -------------------------------- ### Create New Student Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Creates a new student record in the database. Requires name, age, and email. Returns the newly created student object with its assigned ID and a 201 status code. ```APIDOC ## POST /students ### Description Creates a new student record. ### Method POST ### Endpoint /students ### Parameters (No path or query parameters for this endpoint) ### Request Body - **name** (string) - Required - The name of the student. - **age** (integer) - Required - The age of the student. - **email** (string) - Required - The email address of the student. ### Request Example ```json { "name": "Sara Ali", "age": 21, "email": "sara@example.com" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created student. - **name** (string) - The name of the student. - **age** (integer) - The age of the student. - **email** (string) - The email address of the student. #### Response Example ```json { "id": 4, "name": "Sara Ali", "age": 21, "email": "sara@example.com" } ``` ``` -------------------------------- ### In-Memory Student Data Endpoint Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Retrieves a list of all students from an in-memory list when the '/students' endpoint is accessed. ```python students = [ {"id": 1, "name": "Ali Khan", "age": 20, "email": "ali@example.com"}, {"id": 2, "name": "Fatima Ahmed", "age": 22, "email": "fatima@example.com"}, {"id": 3, "name": "Hassan Raza", "age": 19, "email": "hassan@example.com"}, ] @app.get("/students") def get_all_students(): return students ``` -------------------------------- ### CreateStudent Pydantic Model (Python) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt A Pydantic model for validating incoming student data during creation. It includes name, age, and email, but not the ID. ```python from pydantic import BaseModel class CreateStudent(BaseModel): name: str age: int email: str ``` -------------------------------- ### Update Existing Student (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Modify an existing student's record. Supports partial updates where only provided fields are changed. Returns 404 if the student is not found. ```bash # Update student's age only (partial update) curl -X PUT http://127.0.0.1:8000/students/1 \ -H "Content-Type: application/json" \ -d '{"age": 21}' # Full update with all fields curl -X PUT http://127.0.0.1:8000/students/1 \ -H "Content-Type: application/json" \ -d '{"name": "Ali Khan Updated", "age": 22, "email": "ali.khan@example.com"}' ``` -------------------------------- ### Check API Health (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Use this command to verify if the FastAPI application is running and accessible. ```bash # Check API health curl -X GET http://127.0.0.1:8000/ ``` -------------------------------- ### Delete Student (Bash) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Remove a student record by their ID. Returns 204 No Content on successful deletion or 404 if the student does not exist. ```bash # Delete student with ID 1 curl -X DELETE http://127.0.0.1:8000/students/1 # Delete non-existent student curl -X DELETE http://127.0.0.1:8000/students/999 ``` -------------------------------- ### Call Gemini Model with Retry Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Calls the Gemini model with a single prompt and applies retry logic for robustness. Optionally processes the LLM output using a provided parser function. Ensure `max_attempts`, `base_delay`, and `backoff_factor` are configured appropriately for the retry decorator. ```python @retry(max_attempts=12, base_delay=2, backoff_factor=2) def call(self, prompt: str, parser_func=None) -> str: """Calls the Gemini model with the given prompt. Args: prompt (str): The prompt to call the model with. parser_func (callable, optional): A function that processes the LLM output. It takes the model"s response as input and returns the processed result. Returns: str: The processed response from the model. """ response = self.model.generate_content( prompt, generation_config=GenerationConfig( temperature=self.temperature, **self.arguments, ), safety_settings=SAFETY_FILTER_CONFIG, ).text if parser_func: return parser_func(response) return response ``` -------------------------------- ### Define Gemini LLM Integration Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Defines the Gemini class, extending BaseLlm for Gemini model integration. It specifies supported models and handles asynchronous content generation. ```python class Gemini(BaseLlm): """Integration for Gemini models. Attributes: model: The name of the Gemini model. """ model: str = 'gemini-1.5-flash' @staticmethod @override def supported_models() -> list[str]: """Provides the list of supported models. Returns: A list of supported models. """ return [ r'gemini-.*', # fine-tuned vertex endpoint pattern r'projects\/.+\/locations\/.+\/endpoints\/.+', # vertex gemini long name r'projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+', ] async def generate_content_async( self, llm_request: LlmRequest, stream: bool = False ) -> AsyncGenerator[LlmResponse, None]: """Sends a request to the Gemini model. Args: llm_request: LlmRequest, the request to send to the Gemini model. stream: bool = False, whether to do streaming call. Yields: LlmResponse: The model response. """ self._preprocess_request(llm_request) self._maybe_append_user_content(llm_request) logger.info( 'Sending out request, model: %s, backend: %s, stream: %s', llm_request.model, self._api_backend, stream, ) logger.info(_build_request_log(llm_request)) # add tracking headers to custom headers given it will override the headers # set in the api client constructor if llm_request.config and llm_request.config.http_options: if not llm_request.config.http_options.headers: llm_request.config.http_options.headers = {} llm_request.config.http_options.headers.update(self._tracking_headers) if stream: responses = await self.api_client.aio.models.generate_content_stream( model=llm_request.model, contents=llm_request.contents, config=llm_request.config, ) response = None thought_text = '' text = '' usage_metadata = None # for sse, similar as bidi (see receive method in gemini_llm_connecton.py), # we need to mark those text content as partial and after all partial # contents are sent, we send an accumulated event which contains all the # previous partial content. The only difference is bidi rely on # complete_turn flag to detect end while sse depends on finish_reason. async for response in responses: logger.info(_build_response_log(response)) llm_response = LlmResponse.create(response) usage_metadata = llm_response.usage_metadata if ( llm_response.content and llm_response.content.parts and llm_response.content.parts[0].text ): part0 = llm_response.content.parts[0] if part0.thought: thought_text += part0.text else: text += part0.text llm_response.partial = True elif (thought_text or text) and ( not llm_response.content or not llm_response.content.parts # don't yield the merged text event when receiving audio data or not llm_response.content.parts[0].inline_data ): parts = [] if thought_text: parts.append(types.Part(text=thought_text, thought=True)) if text: parts.append(types.Part.from_text(text=text)) yield LlmResponse( content=types.ModelContent(parts=parts), usage_metadata=llm_response.usage_metadata, ) thought_text = '' text = '' yield llm_response if ( (text or thought_text) and response and response.candidates and response.candidates[0].finish_reason == types.FinishReason.STOP ): parts = [] if thought_text: parts.append(types.Part(text=thought_text, thought=True)) if text: parts.append(types.Part.from_text(text=text)) yield LlmResponse( content=types.ModelContent(parts=parts), usage_metadata=usage_metadata, ) else: response = await self.api_client.aio.models.generate_content( model=llm_request.model, contents=llm_request.contents, config=llm_request.config, ) logger.info(_build_response_log(response)) yield LlmResponse.create(response) @cached_property def api_client(self) -> Client: """Provides the api client. Returns: The api client. """ return Client( http_options=types.HttpOptions(headers=self._tracking_headers) ) @cached_property def _api_backend(self) -> GoogleLLMVariant: return ( GoogleLLMVariant.VERTEX_AI if self.api_client.vertexai else GoogleLLMVariant.GEMINI_API ) ``` -------------------------------- ### Student SQLModel Definition (Python) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Defines the Student entity using SQLModel, including primary key, name, age, and email fields. This model is used for database operations and API responses. ```python from sqlmodel import SQLModel, Field class Student(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str age: int email: str ``` -------------------------------- ### Update FastAPI Engine for Cloud Database Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md Modifies the database engine creation in FastAPI to use a connection URL retrieved from environment variables, enabling cloud database integration. ```python import os DATABASE_URL = os.environ.get("DATABASE_URL") engine = create_engine(DATABASE_URL, echo=True) ``` -------------------------------- ### Determine API Backend Variant Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Determines the specific Google LLM backend being utilized based on the `vertexai` attribute of the API client. Returns `GoogleLLMVariant.VERTEX_AI` if `vertexai` is true, otherwise returns `GoogleLLMVariant.GEMINI_API`. ```python def _api_backend(self) -> GoogleLLMVariant: return ( GoogleLLMVariant.VERTEX_AI if self.api_client.vertexai else GoogleLLMVariant.GEMINI_API ) ``` -------------------------------- ### UpdateStudent Pydantic Model (Python) Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt A Pydantic model designed for partial updates of student records. All fields (name, age, email) are optional. ```python from pydantic import BaseModel from typing import Optional class UpdateStudent(BaseModel): name: Optional[str] = None age: Optional[int] = None email: Optional[str] = None ``` -------------------------------- ### Student Management API Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/notes.md API endpoints for managing student records. ```APIDOC ## POST /students ### Description Creates a new student record. ### Method POST ### Endpoint /students ### Request Body - **name** (str) - Required - The name of the student. - **age** (int) - Required - The age of the student. - **email** (str) - Required - The email address of the student. ### Request Example ```json { "name": "John Doe", "age": 20, "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (int) - The unique identifier for the student. - **name** (str) - The name of the student. - **age** (int) - The age of the student. - **email** (str) - The email address of the student. #### Response Example ```json { "id": 1, "name": "John Doe", "age": 20, "email": "john.doe@example.com" } ``` ## GET /students ### Description Retrieves a list of all student records. ### Method GET ### Endpoint /students ### Response #### Success Response (200) - List of student objects, each containing: - **id** (int) - The unique identifier for the student. - **name** (str) - The name of the student. - **age** (int) - The age of the student. - **email** (str) - The email address of the student. #### Response Example ```json [ { "id": 1, "name": "John Doe", "age": 20, "email": "john.doe@example.com" } ] ``` ## GET /students/{student_id} ### Description Retrieves a specific student record by its ID. ### Method GET ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (int) - Required - The ID of the student to retrieve. ### Response #### Success Response (200) - **id** (int) - The unique identifier for the student. - **name** (str) - The name of the student. - **age** (int) - The age of the student. - **email** (str) - The email address of the student. #### Response Example ```json { "id": 1, "name": "John Doe", "age": 20, "email": "john.doe@example.com" } ``` ## PUT /students/{student_id} ### Description Updates an existing student record by its ID. ### Method PUT ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (int) - Required - The ID of the student to update. ### Request Body - **name** (str) - Required - The updated name of the student. - **age** (int) - Required - The updated age of the student. - **email** (str) - Required - The updated email address of the student. ### Request Example ```json { "name": "Jane Doe", "age": 21, "email": "jane.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (int) - The unique identifier for the student. - **name** (str) - The updated name of the student. - **age** (int) - The updated age of the student. - **email** (str) - The updated email address of the student. #### Response Example ```json { "id": 1, "name": "Jane Doe", "age": 21, "email": "jane.doe@example.com" } ``` ## DELETE /students/{student_id} ### Description Deletes a student record by its ID. ### Method DELETE ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (int) - Required - The ID of the student to delete. ### Response #### Success Response (200) - **message** (str) - A confirmation message indicating the student was deleted. #### Response Example ```json { "message": "Student deleted" } ``` ``` -------------------------------- ### GeminiModel Class Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md The GeminiModel class facilitates interaction with the Gemini API, offering features like configurable model names, retry logic, and parallel prompt execution. ```APIDOC ## GeminiModel Class ### Description This class provides a simplified interface for interacting with the Gemini API, featuring retry mechanisms and parallel processing for multiple prompts. ### Initialization (`__init__`) Initializes the `GeminiModel` with various configuration options. #### Parameters - **model_name** (str) - Optional - The name of the Gemini model to use (default: "gemini-2.0-flash-001"). - **finetuned_model** (bool) - Optional - Indicates if a finetuned model is being used (default: False). - **distribute_requests** (bool) - Optional - Whether to distribute requests across different regions (default: False). - **cache_name** (str | None) - Optional - The name of the cache to use (default: None). - **temperature** (float) - Optional - The temperature setting for generation (default: 0.01). - **kwargs** - Optional - Additional keyword arguments for model configuration. ### Method: `call` Calls the Gemini model with a single prompt. #### Parameters - **prompt** (str) - Required - The prompt to send to the model. - **parser_func** (callable, optional) - A function to process the model's output. #### Returns - **str**: The processed response from the model. ### Method: `call_parallel` Calls the Gemini model for multiple prompts in parallel using threads with retry logic. #### Parameters - **prompts** (List[str]) - Required - A list of prompts to call the model with. - **parser_func** (callable, optional) - A function to process each response. - **timeout** (int) - Optional - The maximum time (in seconds) to wait for each thread (default: 60). - **max_retries** (int) - Optional - The maximum number of retries for timed-out threads (default: 5). #### Returns - **List[Optional[str]]**: A list of responses, or None for threads that failed. ``` -------------------------------- ### Convert OpenAPI Schema to Gemini Schema Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Converts an OpenAPI schema dictionary to a Gemini Schema object. It sanitizes schema formats before conversion and uses `Schema.from_json_schema` for the transformation. ```python def _to_gemini_schema(openapi_schema: dict[str, Any]) -> Schema: """Converts an OpenAPI schema dictionary to a Gemini Schema object.""" if openapi_schema is None: return None if not isinstance(openapi_schema, dict): raise TypeError("openapi_schema must be a dictionary") openapi_schema = _sanitize_schema_formats_for_gemini(openapi_schema) return Schema.from_json_schema( json_schema=_ExtendedJSONSchema.model_validate(openapi_schema), api_option=get_google_llm_variant(), ) ``` -------------------------------- ### Root Endpoint - Health Check Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt This endpoint serves as a health check for the API. It returns a simple JSON response indicating that the API is running. ```APIDOC ## GET / ### Description Checks if the API is running. ### Method GET ### Endpoint / ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **Hello** (string) - A confirmation message. #### Response Example ```json { "Hello": "World" } ``` ``` -------------------------------- ### Update Existing Student Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Updates an existing student's record identified by their ID. This endpoint supports partial updates, meaning only the fields provided in the request body will be modified. If the student is not found, a 404 error is returned. ```APIDOC ## PUT /students/{student_id} ### Description Updates an existing student record. Supports partial updates. ### Method PUT ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (integer) - Required - The unique identifier of the student to update. ### Request Body - **name** (string) - Optional - The updated name of the student. - **age** (integer) - Optional - The updated age of the student. - **email** (string) - Optional - The updated email address of the student. ### Request Example (Partial Update) ```json { "age": 21 } ``` ### Request Example (Full Update) ```json { "name": "Ali Khan Updated", "age": 22, "email": "ali.khan@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the student. - **name** (string) - The name of the student. - **age** (integer) - The age of the student. - **email** (string) - The email address of the student. #### Error Response (404) - **detail** (string) - Message indicating the student was not found. #### Response Example (Success) ```json { "id": 1, "name": "Ali Khan", "age": 21, "email": "ali@example.com" } ``` ``` -------------------------------- ### Delete Student Source: https://context7.com/hassanfarid6/backend_with_fastapi/llms.txt Deletes a student record from the database using their unique ID. A successful deletion returns a 204 No Content status. If the student is not found, a 404 error is returned. ```APIDOC ## DELETE /students/{student_id} ### Description Deletes a student record by ID. ### Method DELETE ### Endpoint /students/{student_id} ### Parameters #### Path Parameters - **student_id** (integer) - Required - The unique identifier of the student to delete. ### Request Example (No request body for DELETE request) ### Response #### Success Response (204) - No content is returned upon successful deletion. #### Error Response (404) - **detail** (string) - Message indicating the student was not found. #### Response Example (Not Found) ```json { "detail": "Student not found" } ``` ``` -------------------------------- ### Parallel Gemini Model Calls with Threading and Retries Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Executes multiple Gemini model calls concurrently using threads, with built-in retry logic for individual prompt failures and a timeout for the overall operation. Handles results and reports timeouts or errors after retries. ```python def call_parallel( self, prompts: List[str], parser_func: Optional[Callable[[str], str]] = None, timeout: int = 60, max_retries: int = 5, ) -> List[Optional[str]]: """Calls the Gemini model for multiple prompts in parallel using threads with retry logic. Args: prompts (List[str]): A list of prompts to call the model with. parser_func (callable, optional): A function to process each response. timeout (int): The maximum time (in seconds) to wait for each thread. max_retries (int): The maximum number of retries for timed-out threads. Returns: List[Optional[str]]: A list of responses, or None for threads that failed. """ results = [None] * len(prompts) def worker(index: int, prompt: str): """Thread worker function to call the model and store the result with retries.""" retries = 0 while retries <= max_retries: try: return self.call(prompt, parser_func) except Exception as e: # pylint: disable=broad-exception-caught print(f"Error for prompt {index}: {str(e)}") retries += 1 if retries <= max_retries: print(f"Retrying ({retries}/{max_retries}) for prompt {index}") time.sleep(1) # Small delay before retrying else: return f"Error after retries: {str(e)}" # Create and start one thread for each prompt with ThreadPoolExecutor(max_workers=len(prompts)) as executor: future_to_index = { executor.submit(worker, i, prompt): i for i, prompt in enumerate(prompts) } for future in as_completed(future_to_index, timeout=timeout): index = future_to_index[future] try: results[index] = future.result() except Exception as e: # pylint: disable=broad-exception-caught print(f"Unhandled error for prompt {index}: {e}") results[index] = "Unhandled Error" # Handle remaining unfinished tasks after the timeout for future in future_to_index: index = future_to_index[future] if not future.done(): print(f"Timeout occurred for prompt {index}") results[index] = "Timeout" return results ``` -------------------------------- ### Convert Gemini Schema to JSON Schema Source: https://github.com/hassanfarid6/backend_with_fastapi/blob/main/GEMINI.md Converts a Gemini Schema object into a JSON Schema dictionary. Handles various type mappings, validations, and recursive structures for arrays and objects. Raises TypeError for invalid input and ValueError for invalid Gemini Type enums. ```python def gemini_to_json_schema(gemini_schema: Schema) -> Dict[str, Any]: """Converts a Gemini Schema object into a JSON Schema dictionary. Args: gemini_schema: An instance of the Gemini Schema class. Returns: A dictionary representing the equivalent JSON Schema. Raises: TypeError: If the input is not an instance of the expected Schema class. ValueError: If an invalid Gemini Type enum value is encountered. """ if not isinstance(gemini_schema, Schema): raise TypeError( f"Input must be an instance of Schema, got {type(gemini_schema)}" ) json_schema_dict: Dict[str, Any] = {} # Map Type gemini_type = getattr(gemini_schema, "type", None) if gemini_type and gemini_type != Type.TYPE_UNSPECIFIED: json_schema_dict["type"] = gemini_type.lower() else: json_schema_dict["type"] = "null" # Map Nullable if getattr(gemini_schema, "nullable", None) == True: json_schema_dict["nullable"] = True # --- Map direct fields --- direct_mappings = { "title": "title", "description": "description", "default": "default", "enum": "enum", "format": "format", "example": "example", } for gemini_key, json_key in direct_mappings.items(): value = getattr(gemini_schema, gemini_key, None) if value is not None: json_schema_dict[json_key] = value # String validation if gemini_type == Type.STRING: str_mappings = { "pattern": "pattern", "min_length": "minLength", "max_length": "maxLength", } for gemini_key, json_key in str_mappings.items(): value = getattr(gemini_schema, gemini_key, None) if value is not None: json_schema_dict[json_key] = value # Number/Integer validation if gemini_type in (Type.NUMBER, Type.INTEGER): num_mappings = { "minimum": "minimum", "maximum": "maximum", } for gemini_key, json_key in num_mappings.items(): value = getattr(gemini_schema, gemini_key, None) if value is not None: json_schema_dict[json_key] = value # Array validation (Recursive call for items) if gemini_type == Type.ARRAY: items_schema = getattr(gemini_schema, "items", None) if items_schema is not None: json_schema_dict["items"] = gemini_to_json_schema(items_schema) arr_mappings = { "min_items": "minItems", "max_items": "maxItems", } for gemini_key, json_key in arr_mappings.items(): value = getattr(gemini_schema, gemini_key, None) if value is not None: json_schema_dict[json_key] = value # Object validation (Recursive call for properties) if gemini_type == Type.OBJECT: properties_dict = getattr(gemini_schema, "properties", None) if properties_dict is not None: json_schema_dict["properties"] = { prop_name: gemini_to_json_schema(prop_schema) for prop_name, prop_schema in properties_dict.items() } obj_mappings = { "required": "required", "min_properties": "minProperties", "max_properties": "maxProperties", # Note: Ignoring 'property_ordering' as it's not standard JSON Schema } for gemini_key, json_key in obj_mappings.items(): value = getattr(gemini_schema, gemini_key, None) if value is not None: json_schema_dict[json_key] = value # Map anyOf (Recursive call for subschemas) any_of_list = getattr(gemini_schema, "any_of", None) if any_of_list is not None: json_schema_dict["anyOf"] = [ gemini_to_json_schema(sub_schema) for sub_schema in any_of_list ] return json_schema_dict ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.