Fix my code.

Code:
import os
from typing import List, Dict
from pinecone import Pinecone, ServerlessSpec
from pdfminer.high_level import extract_text
from llama_parse import LlamaParse
from langchain.text_splitter import RecursiveCharacterTextSplitter
from sentence_transformers import SentenceTransformer
import torch
from tqdm.auto import tqdm
from google.colab import files
import tempfile

class RAGSystem:
    def __init__(self, pinecone_api_key: str, llama_api_key: str, index_name: str):
        # Initialize Pinecone with new API
        self.pc = Pinecone(api_key=pinecone_api_key)

        # Create or get existing index
        if index_name not in self.pc.list_indexes().names():
            self.pc.create_index(
                name=index_name,
                dimension=768,  # Using 768 for 'all-MiniLM-L6-v2' embeddings
                metric='cosine',
                spec=ServerlessSpec(
                    cloud='aws',
                    region='us-west-2'
                )
            )
        self.index = self.pc.Index(index_name)

        # Initialize the embedding model
        self.embedder = SentenceTransformer('all-MiniLM-L6-v2')

        # Initialize text splitter
        self.text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50
        )

        # Initialize Llama Parser with API key
        self.llama_parser = LlamaParse(api_key=llama_api_key)

    def extract_text_from_pdf(self, pdf_path: str) -> str:
        """Extract text content from PDF using PDFMiner"""
        return extract_text(pdf_path)

    def extract_images_from_pdf(self, pdf_path: str) -> List[Dict]:
        """Extract images and their descriptions using Llama Parser"""
        parsed_doc = self.llama_parser.load(pdf_path)
        return parsed_doc.get_images()

    def process_document(self, pdf_path: str, document_id: str):
        """Process a PDF document and store its embeddings in Pinecone"""
        print(f"Processing {document_id}...")

        # Extract text content
        text_content = self.extract_text_from_pdf(pdf_path)
        text_chunks = self.text_splitter.split_text(text_content)

        # Extract images and their descriptions
        try:
            images = self.extract_images_from_pdf(pdf_path)
            image_descriptions = [img['caption'] for img in images]
        except Exception as e:
            print(f"Warning: Image extraction failed for {document_id}: {str(e)}")
            image_descriptions = []

        # Combine text chunks and image descriptions
        all_chunks = text_chunks + image_descriptions

        # Generate embeddings
        print(f"Generating embeddings for {len(all_chunks)} chunks...")
        embeddings = self.embedder.encode(all_chunks, show_progress_bar=True)

        # Prepare vectors for Pinecone
        vectors = []
        for i, (chunk, embedding) in enumerate(zip(all_chunks, embeddings)):
            vectors.append({
                'id': f"{document_id}_chunk_{i}",
                'values': embedding.tolist(),
                'metadata': {
                    'text': chunk,
                    'document_id': document_id,
                    'chunk_type': 'text' if i < len(text_chunks) else 'image_description'
                }
            })

        # Upload vectors to Pinecone in batches
        batch_size = 100
        print(f"Uploading vectors to Pinecone in batches...")
        for i in range(0, len(vectors), batch_size):
            batch = vectors[i:i + batch_size]
            self.index.upsert(vectors=batch)

        print(f"Successfully processed {document_id}")

    def query(self, query_text: str, top_k: int = 5) -> List[Dict]:
        """Query the RAG system"""
        # Generate embedding for the query
        query_embedding = self.embedder.encode(query_text)

        # Query Pinecone
        results = self.index.query(
            vector=query_embedding.tolist(),
            top_k=top_k,
            include_metadata=True
        )

        return results

def process_uploaded_files(pinecone_api_key: str, llama_api_key: str):
    """Handle file uploads in Google Colab"""
    print("Please upload your PDF files when prompted...")
    uploaded = files.upload()  # This will prompt for file upload

    # Initialize RAG system
    rag = RAGSystem(
        pinecone_api_key=pinecone_api_key,
        llama_api_key=llama_api_key,
        index_name='pdf-rag-index'
    )

    # Process each uploaded file
    for filename, content in uploaded.items():
        if filename.endswith('.pdf'):
            print(f"\nProcessing {filename}...")

            # Create a temporary file to store the uploaded content
            with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
                temp_file.write(content)
                temp_path = temp_file.name

            try:
                # Process the document
                document_id = filename.replace('.pdf', '')
                rag.process_document(temp_path, document_id)
                print(f"Successfully processed {filename}")
            except Exception as e:
                print(f"Error processing {filename}: {str(e)}")
            finally:
                # Clean up temporary file
                os.unlink(temp_path)

    return rag

# Example usage in Colab
def main():
    # Set your API keys
    PINECONE_API_KEY = input("Please enter your Pinecone API key: ")
    LLAMA_API_KEY = input("Please enter your Llama Parser API key: ")

    # Process uploaded files
    rag = process_uploaded_files(PINECONE_API_KEY, LLAMA_API_KEY)

    # Example query
    while True:
        query = input("\nEnter your query (or 'quit' to exit): ")
        if query.lower() == 'quit':
            break

        results = rag.query(query)

        print("\nResults:")
        for i, match in enumerate(results.matches, 1):
            print(f"\n{i}. Score: {match.score:.4f}")
            print(f"Text: {match.metadata['text']}")
            print("---")

if __name__ == "__main__":
    main()



Error:
Please enter your Pinecone API key: e93177a5-361c-4411-8ba4-b96fddf1d9ee
Please enter your Llama Parser API key: llx-jXmIpkEdA4sSrVeePq8uRgrOt65qz3K3q50iyZK1tLFNjv7y
Please upload your PDF files when prompted...
Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020.pdf
Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020.pdf(application/pdf) - 465510 bytes, last modified: 3.10.2024 - 100% done
Saving Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020.pdf to Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020 (8).pdf

Processing Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020 (8).pdf...
Processing Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020 (8)...
Warning: Image extraction failed for Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020 (8): 'LlamaParse' object has no attribute 'load'
Generating embeddings for 158 chunks...
Batches: 100%
 5/5 [00:11<00:00,  1.86s/it]
Uploading vectors to Pinecone in batches...
Error processing Collaborative intelligence How human and artificial intelligence create value along the B2B sales funnel_Paschen, 2020 (8).pdf: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Date': 'Sat, 05 Oct 2024 21:12:22 GMT', 'Content-Type': 'application/json', 'Content-Length': '102', 'Connection': 'keep-alive', 'x-pinecone-request-latency-ms': '202', 'x-pinecone-request-id': '7260941262110628948', 'x-envoy-upstream-service-time': '36', 'server': 'envoy'})
HTTP response body: {"code":3,"message":"Vector dimension 384 does not match the dimension of the index 768","details":[]}


Enter your query (or 'quit' to exit): test
---------------------------------------------------------------------------
PineconeApiException                      Traceback (most recent call last)
<ipython-input-20-fa669a6a73f6> in <cell line: 169>()
    168 
    169 if __name__ == "__main__":
--> 170     main()

12 frames
/usr/local/lib/python3.10/dist-packages/pinecone/core/openapi/shared/rest.py in request(self, method, url, query_params, headers, body, post_params, _preload_content, _request_timeout)
    277                 raise ServiceException(http_resp=r)
    278 
--> 279             raise PineconeApiException(http_resp=r)
    280 
    281         return r

PineconeApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Date': 'Sat, 05 Oct 2024 21:12:33 GMT', 'Content-Type': 'application/json', 'Content-Length': '102', 'Connection': 'keep-alive', 'x-pinecone-request-latency-ms': '34', 'x-pinecone-request-id': '4249888205190618387', 'x-envoy-upstream-service-time': '34', 'server': 'envoy'})
HTTP response body: {"code":3,"message":"Vector dimension 384 does not match the dimension of the index 768","details":[]}