### Install and Run LawGPT Source: https://github.com/ayuugoyal/lawgpt/blob/main/README.md Clone the repository, install dependencies using pnpm, and start the development server. ```bash git clone https://github.com/ayuugoyal/lawgpt cd lawgpt pnpm install pnpm run dev ``` -------------------------------- ### Chat with Document Context using cURL Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Example of initiating a chat session with document context using the /chat/ endpoint via cURL. The query is sent as form data. ```bash # POST /chat/ - Chat with document context curl -X POST "http://localhost:8000/chat/" \ -F "query=What does the document say about lease agreements?" # Response: # { # "answer": "Based on the uploaded documents...", # "context": [ # "A lease agreement under Section 105 of Transfer of Property Act...", # "The essential elements of a valid lease include..." # ] # } ``` -------------------------------- ### Upload Documents using Python Client Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Example of uploading multiple PDF documents to the /upload-documents/ endpoint using the requests library in Python. Ensure files are opened in binary read mode. ```python # Python client example import requests files = [ ('files', ('contract.pdf', open('contract.pdf', 'rb'), 'application/pdf')), ('files', ('ipc_sections.pdf', open('ipc_sections.pdf', 'rb'), 'application/pdf')) ] response = requests.post("http://localhost:8000/upload-documents/", files=files) print(response.json()) # {'message': 'Documents processed successfully', 'chunk_count': 89} ``` -------------------------------- ### Perform Document Search using Python Client Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Example of performing a semantic search query using the /search/ endpoint with a Python client. The response is parsed to display similarity scores and content snippets. ```python # Python client example import requests query = {"query": "grounds for eviction under Rent Control Act"} response = requests.post("http://localhost:8000/search/", json=query) results = response.json() for result in results["results"]: print(f"Similarity: {result['similarity']:.2f}") print(f"Content: {result['content'][:200]}...") print("---") ``` -------------------------------- ### Perform Document Search using cURL Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Example of performing a semantic search query against uploaded documents using the /search/ endpoint via cURL. The query is sent as a JSON payload. ```bash # POST /search/ - Search through processed documents curl -X POST "http://localhost:8000/search/" \ -H "Content-Type: application/json" \ -d '{"query": "What are the penalties for breach of contract?"}' # Response: # { # "results": [ # { "content": "Section 73 of the Indian Contract Act, 1872 provides that when a contract has been broken...", "similarity": 0.89 }, # { "content": "Compensation for loss or damage caused by breach of contract...", "similarity": 0.82 }, # { "content": "The measure of damages is not affected by...", "similarity": 0.76 } # ] # } ``` -------------------------------- ### Check Document Processing Status using cURL Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Example of checking the document processing status and system readiness using the /status/ endpoint via cURL. Responses indicate whether documents have been processed and if the system is ready for search. ```bash # GET /status/ - Check document processing status curl "http://localhost:8000/status/" # Response when ready: # { "documents_processed": true, "ready_for_search": true } # Response when no documents uploaded: # { "documents_processed": false, "ready_for_search": false } ``` -------------------------------- ### Drizzle ORM Database Schema for NeonDB Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Defines the 'chats' and 'messages' tables using Drizzle ORM for PostgreSQL (NeonDB). Includes schema for chat IDs, user IDs, titles, timestamps, message roles, and content. Also shows database connection setup and an example query. ```typescript // src/db/schema.ts import { pgTable, uuid, text, timestamp, varchar } from "drizzle-orm/pg-core"; import { relations } from "drizzle-orm"; export const chats = pgTable("chats", { id: uuid("id").defaultRandom().primaryKey(), userId: varchar("user_id", { length: 256 }).notNull(), title: text("title").default("New Chat"), createdAt: timestamp("created_at").defaultNow().notNull(), updatedAt: timestamp("updated_at").defaultNow().notNull(), }); export const messages = pgTable("messages", { id: uuid("id").defaultRandom().primaryKey(), chatId: uuid("chat_id").references(() => chats.id).notNull(), role: varchar("role", { length: 20 }).notNull(), // "user" or "assistant" content: text("content").notNull(), createdAt: timestamp("created_at").defaultNow().notNull(), }); // Database connection import { neon } from "@neondatabase/serverless"; import { drizzle } from "drizzle-orm/neon-http"; import * as schema from "./schema"; const sql = neon(process.env.DATABASE_URL!); export const db = drizzle(sql, { schema }); // Example query - fetch user's chats with messages const userChats = await db.query.chats.findMany({ where: eq(chats.userId, userId), with: { messages: true }, orderBy: (chats, { desc }) => [desc(chats.updatedAt)], }); ``` -------------------------------- ### Chat Messages API (Next.js) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Handles storing and retrieving individual messages within a chat session. Messages are ordered chronologically and linked to their parent chat. Use these endpoints to get all messages in a chat or save new messages. ```typescript // GET /api/chats/[chatId]/messages - Get all messages in a chat const response = await fetch(`/api/chats/${chatId}/messages`); const messages = await response.json(); // Response: [ // { "id": "uuid-1", "chatId": "chat-uuid", "role": "user", "content": "What is bail?", "createdAt": "2024-01-15T10:00:00Z" }, // { "id": "uuid-2", "chatId": "chat-uuid", "role": "assistant", "content": "Bail is the temporary release...", "createdAt": "2024-01-15T10:00:05Z" } // ] // POST /api/chats/[chatId]/messages - Save a new message const saveMessage = async (role: string, content: string) => { const response = await fetch(`/api/chats/${chatId}/messages`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role, content }), }); return response.json(); }; // Save user message await saveMessage("user", "What are my rights during arrest?"); // Save assistant response await saveMessage("assistant", "Under Article 22 of the Constitution..."); ``` -------------------------------- ### Upload Documents for RAG (FastAPI) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Upload PDF files to the FastAPI backend for RAG-based search. The backend extracts text, chunks it, generates embeddings, and stores them in a FAISS vector database. This endpoint is used for processing legal documents. ```bash # POST /upload-documents/ - Upload PDF files for processing curl -X POST "http://localhost:8000/upload-documents/" \ -F "files=@/path/to/legal_document.pdf" \ -F "files=@/path/to/case_law.pdf" ``` -------------------------------- ### Status Endpoint Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Checks the processing status of uploaded documents and system readiness for search queries. ```APIDOC ## GET /status/ ### Description Checks if documents have been processed and if the system is ready to accept search queries. ### Method GET ### Endpoint /status/ ### Response #### Success Response (200) - **documents_processed** (boolean) - Indicates if documents have been processed. - **ready_for_search** (boolean) - Indicates if the system is ready for search queries. #### Response Example (Ready) ```json { "documents_processed": true, "ready_for_search": true } ``` #### Response Example (Not Ready) ```json { "documents_processed": false, "ready_for_search": false } ``` ``` -------------------------------- ### POST /upload-documents/ - Document Upload for RAG Source: https://context7.com/ayuugoyal/lawgpt/llms.txt This endpoint, part of the Python FastAPI backend, handles the upload of PDF documents for the Retrieval-Augmented Generation (RAG) system. It processes the documents to enable semantic search. ```APIDOC ## POST /upload-documents/ ### Description Uploads PDF documents to the FastAPI backend for processing. The backend extracts text, chunks it, generates embeddings using HuggingFace, and stores them in a FAISS vector database for RAG-based search. ### Method POST ### Endpoint /upload-documents/ ### Parameters #### Form Data - **files** (file) - Required - One or more PDF files to upload. ### Request Example ```bash curl -X POST "http://localhost:8000/upload-documents/" \ -F "files=@/path/to/legal_document.pdf" \ -F "files=@/path/to/case_law.pdf" ``` ### Response - **Success Response** - The response format for success is not explicitly defined in the provided text, but typically would indicate successful processing or provide a status update. ``` -------------------------------- ### Stream AI Chat Responses (Next.js) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Use this endpoint to stream AI chat responses from the Google Gemini AI model. It processes conversation history and requires a JSON body with messages. Client-side usage involves the Vercel AI SDK. ```typescript // POST /api/chat - Stream AI chat responses // Request body { "messages": [ { "id": "msg-1", "role": "user", "content": "What are the grounds for divorce under Hindu Marriage Act?" }, { "id": "msg-2", "role": "assistant", "content": "Under Section 13..." } ] } // Client-side usage with Vercel AI SDK import { useChat } from "ai/react"; const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ id: chatId, api: "/api/chat", onFinish: async (message) => { // Save assistant response to database await fetch(`/api/chats/${chatId}/messages`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role: "assistant", content: message.content }), }); } }); ``` ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -d '{"messages": [{"id": "1", "role": "user", "content": "What is Section 420 IPC?"}]}' ``` -------------------------------- ### Chat Session Management API (Next.js) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Provides CRUD operations for managing chat sessions. Requires user authentication via Clerk. Each session includes a title and timestamps. Use these endpoints to list, create, update, or delete chat sessions. ```typescript // GET /api/chats - List all user's chat sessions const response = await fetch("/api/chats"); const chats = await response.json(); // Response: [{ "id": "uuid", "userId": "user_123", "title": "Property dispute...", "createdAt": "2024-01-15T10:00:00Z", "updatedAt": "2024-01-15T10:30:00Z" }] // POST /api/chats - Create a new chat session const newChat = await fetch("/api/chats", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "Question about property law..." }), }); const chat = await newChat.json(); // Response: { "id": "550e8400-e29b-41d4-a716-446655440000", "userId": "user_123", "title": "Question about property law...", "createdAt": "2024-01-15T10:00:00Z" } // PATCH /api/chats/[chatId] - Update chat title await fetch(`/api/chats/${chatId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "Updated title" }), }); // DELETE /api/chats/[chatId] - Delete chat and all messages await fetch(`/api/chats/${chatId}`, { method: "DELETE" }); // Returns 204 No Content on success ``` -------------------------------- ### Chat Messages API (/api/chats/[chatId]/messages) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Handles the storage and retrieval of individual messages within a specific chat session. Messages are ordered chronologically. ```APIDOC ## Chat Messages API ### Description Manages individual messages within a chat session. Allows retrieval of all messages for a given chat and posting new messages. ### Endpoints #### GET /api/chats/[chatId]/messages ##### Description Retrieves all messages associated with a specific chat session, ordered chronologically. ##### Method GET ##### Endpoint /api/chats/[chatId]/messages ##### Parameters ###### Path Parameters - **chatId** (string) - Required - The ID of the chat session whose messages are to be retrieved. ##### Response ##### Success Response (200) - **messages** (array) - An array of message objects. - **id** (string) - Unique identifier for the message. - **chatId** (string) - Identifier for the chat session the message belongs to. - **role** (string) - The role of the message sender (e.g., "user", "assistant"). - **content** (string) - The content of the message. - **createdAt** (string) - Timestamp when the message was created (ISO 8601 format). ##### Response Example ```json [ { "id": "uuid-1", "chatId": "chat-uuid", "role": "user", "content": "What is bail?", "createdAt": "2024-01-15T10:00:00Z" }, { "id": "uuid-2", "chatId": "chat-uuid", "role": "assistant", "content": "Bail is the temporary release...", "createdAt": "2024-01-15T10:00:05Z" } ] ``` #### POST /api/chats/[chatId]/messages ##### Description Saves a new message to a specific chat session. ##### Method POST ##### Endpoint /api/chats/[chatId]/messages ##### Parameters ###### Path Parameters - **chatId** (string) - Required - The ID of the chat session to which the message will be added. ##### Request Body - **role** (string) - Required - The role of the message sender (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. ##### Request Example ```typescript const saveMessage = async (role: string, content: string) => { const response = await fetch(`/api/chats/${chatId}/messages`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role, content }), }); return response.json(); }; // Save user message await saveMessage("user", "What are my rights during arrest?"); // Save assistant response await saveMessage("assistant", "Under Article 22 of the Constitution..."); ``` ``` -------------------------------- ### Chat Endpoint with RAG Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Provides conversational responses by retrieving relevant context from documents and using it to enhance AI-generated answers. ```APIDOC ## POST /chat/ ### Description Engages in a conversation by retrieving relevant document context and generating an AI-powered answer. ### Method POST ### Endpoint /chat/ ### Parameters #### Form Data - **query** (string) - Required - The user's chat query. ### Request Example ```bash curl -X POST "http://localhost:8000/chat/" \ -F "query=What does the document say about lease agreements?" ``` ### Response #### Success Response (200) - **answer** (string) - The AI-generated answer based on the document context. - **context** (array) - A list of document snippets used to generate the answer. - (string) - A relevant document snippet. #### Response Example ```json { "answer": "Based on the uploaded documents...", "context": [ "A lease agreement under Section 105 of Transfer of Property Act...", "The essential elements of a valid lease include..." ] } ``` ``` -------------------------------- ### POST /api/chat - Stream AI Chat Responses Source: https://context7.com/ayuugoyal/lawgpt/llms.txt This endpoint streams AI responses using Google Gemini AI, processing conversation history and returning streaming responses via a LangChain adapter. It is designed for the main chat interface of LawGPT. ```APIDOC ## POST /api/chat ### Description Streams AI chat responses using Google Gemini AI with a specialized legal system prompt focused on Indian law. Processes conversation history and returns streaming responses via LangChain adapter. ### Method POST ### Endpoint /api/chat ### Request Body - **messages** (array) - Required - An array of message objects representing the conversation history. - **id** (string) - Required - Unique identifier for the message. - **role** (string) - Required - The role of the message sender (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. ### Request Example ```json { "messages": [ { "id": "msg-1", "role": "user", "content": "What are the grounds for divorce under Hindu Marriage Act?" }, { "id": "msg-2", "role": "assistant", "content": "Under Section 13..." } ] } ``` ### Response - **Streaming Response** - The response is streamed chunk by chunk. ### Client-side Usage Example (Vercel AI SDK) ```typescript import { useChat } from "ai/react"; const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ id: chatId, api: "/api/chat", onFinish: async (message) => { // Save assistant response to database await fetch(`/api/chats/${chatId}/messages`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role: "assistant", content: message.content }), }); } }); ``` ### cURL Example ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -d '{"messages": [{"id": "1", "role": "user", "content": "What is Section 420 IPC?"}]}' ``` ``` -------------------------------- ### TypeScript Types for Chat Application Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Core TypeScript type definitions for messages and chat states within the application. Includes interfaces for individual messages, the overall chat state (including loading and error status), and chat sessions. ```typescript // src/types/chat.ts export interface Message { id: string; type: "user" | "bot"; text: string; createdAt?: Date; } export interface ChatState { messages: Message[]; loading: boolean; error: string | null; } export type ChatSession = { id: number; title: string; messages: Message[]; createdAt: Date; updatedAt: Date; }; export interface NewMsg { id: string; role: string; // "user" | "assistant" content: string; createdAt?: Date; updatedAt?: Date; } ``` -------------------------------- ### Document Upload API Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Upload PDF documents for processing. Handles multiple files and returns a success message with the chunk count or an error message for non-PDF files. ```APIDOC ## POST /upload-documents/ ### Description Uploads PDF documents to the system for processing. Supports multiple file uploads. ### Method POST ### Endpoint /upload-documents/ ### Parameters #### Form Data - **files** (file) - Required - One or more PDF files to upload. ### Request Example ```python import requests files = [ ('files', ('contract.pdf', open('contract.pdf', 'rb'), 'application/pdf')), ('files', ('ipc_sections.pdf', open('ipc_sections.pdf', 'rb'), 'application/pdf')) ] response = requests.post("http://localhost:8000/upload-documents/", files=files) print(response.json()) ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **chunk_count** (integer) - The number of document chunks created. #### Error Response (400) - **detail** (string) - Error message indicating a non-PDF file was uploaded. #### Response Example (Success) ```json { "message": "Documents processed successfully", "chunk_count": 145 } ``` #### Response Example (Error) ```json { "detail": "document.txt is not a PDF file" } ``` ``` -------------------------------- ### Document Search API Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Performs semantic similarity search across uploaded documents using a query. Returns relevant document chunks with similarity scores. ```APIDOC ## POST /search/ ### Description Searches uploaded documents for content semantically similar to the provided query. Returns a list of relevant document chunks and their similarity scores. ### Method POST ### Endpoint /search/ ### Parameters #### Request Body - **query** (string) - Required - The search query string. ### Request Example (cURL) ```bash curl -X POST "http://localhost:8000/search/" \ -H "Content-Type: application/json" \ -d '{"query": "What are the penalties for breach of contract?"}' ``` ### Request Example (Python) ```python import requests query = {"query": "grounds for eviction under Rent Control Act"} response = requests.post("http://localhost:8000/search/", json=query) results = response.json() for result in results["results"]: print(f"Similarity: {result['similarity']:.2f}") print(f"Content: {result['content'][:200]}...") print("---") ``` ### Response #### Success Response (200) - **results** (array) - A list of search results. - **content** (string) - The content of the relevant document chunk. - **similarity** (float) - The similarity score between the query and the content. #### Response Example ```json { "results": [ { "content": "Section 73 of the Indian Contract Act, 1872 provides that when a contract has been broken...", "similarity": 0.89 }, { "content": "Compensation for loss or damage caused by breach of contract...", "similarity": 0.82 }, { "content": "The measure of damages is not affected by...", "similarity": 0.76 } ] } ``` ``` -------------------------------- ### Chat Session Management API (/api/chats) Source: https://context7.com/ayuugoyal/lawgpt/llms.txt Provides full CRUD operations for managing chat sessions. Each session is associated with a user and includes a title and timestamps. Authentication is handled via Clerk. ```APIDOC ## Chat Session Management API ### Description Manages chat sessions, allowing users to create, retrieve, update, and delete their conversations. Each chat session is linked to a user and has a title and timestamps. Authentication is handled via Clerk. ### Endpoints #### GET /api/chats ##### Description Retrieves a list of all chat sessions associated with the authenticated user. ##### Method GET ##### Endpoint /api/chats ##### Response ##### Success Response (200) - **chats** (array) - An array of chat session objects. - **id** (string) - Unique identifier for the chat session. - **userId** (string) - Identifier for the user who owns the chat session. - **title** (string) - The title of the chat session. - **createdAt** (string) - Timestamp when the chat session was created (ISO 8601 format). - **updatedAt** (string) - Timestamp when the chat session was last updated (ISO 8601 format). ##### Response Example ```json [ { "id": "uuid", "userId": "user_123", "title": "Property dispute...", "createdAt": "2024-01-15T10:00:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ] ``` #### POST /api/chats ##### Description Creates a new chat session for the authenticated user. ##### Method POST ##### Endpoint /api/chats ##### Request Body - **title** (string) - Required - The desired title for the new chat session. ##### Request Example ```json { "title": "Question about property law..." } ``` ##### Response ##### Success Response (200) - **chat** (object) - The newly created chat session object. - **id** (string) - Unique identifier for the chat session. - **userId** (string) - Identifier for the user who owns the chat session. - **title** (string) - The title of the chat session. - **createdAt** (string) - Timestamp when the chat session was created (ISO 8601 format). ##### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "userId": "user_123", "title": "Question about property law...", "createdAt": "2024-01-15T10:00:00Z" } ``` #### PATCH /api/chats/[chatId] ##### Description Updates the title of an existing chat session. ##### Method PATCH ##### Endpoint /api/chats/[chatId] ##### Parameters ###### Path Parameters - **chatId** (string) - Required - The ID of the chat session to update. ##### Request Body - **title** (string) - Required - The new title for the chat session. ##### Request Example ```json { "title": "Updated title" } ``` #### DELETE /api/chats/[chatId] ##### Description Deletes a chat session and all associated messages. ##### Method DELETE ##### Endpoint /api/chats/[chatId] ##### Parameters ###### Path Parameters - **chatId** (string) - Required - The ID of the chat session to delete. ##### Response ##### Success Response (204) - No content is returned on successful deletion. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.