code:
import os
import openai
# from tqdm.auto import tqdm 
# from time import sleep
from pinecone import Pinecone, ServerlessSpec
# from dotenv import load_dotenv
import spacy
import tiktoken
import json
import logging
import datetime
import azure.functions as func
from pathlib import Path
import uuid

openai_key = "<TRUFFLEHOG_REDACTED_OPENAI>"  # os.getenv("openai_key")
openAI_client = openai.OpenAI(api_key=openai_key)
pckey = "ad5d3f6f-ae7d-4880-9b1b-0fa937fe67ad"  # os.getenv("pinecone_key")
pc =  Pinecone(api_key=pckey)
model_path = Path(__file__).parent / "spacy_model/en_core_web_sm-3.8.0"
nlp = spacy.load(model_path)    # spacy.load('en_core_web_sm')
tokenizer = tiktoken.get_encoding("cl100k_base")    # embed_model tokenizer

index_name = os.getenv('index_name') or 'id-pc1-01'

CHUNK_SIZE_LIMIT = 500

embed_model = "text-embedding-ada-002"

# UTILITY FUNCTIONS 👇
def get_index():
    try:
        if not pc.has_index(index_name):
            pc.create_index(
                name=index_name,
                dimension=1536,
                metric='cosine',
                spec=ServerlessSpec(cloud='aws', region='us-east-1')
            )
        return pc.Index(index_name)
    except Exception as e:
        logging.error(f"Error encountered while getting index from pinecone: {str(e)}")

def embed_text(text):   # convert text to embeddings
    try:
        res = openAI_client.embeddings.create(
            input=[text],
            model=embed_model
        )
        return res.data[0].embedding
    except Exception as e:
        logging.error(f"Error encountered while embedding text: {str(e)}")

def tokenize(text): # tokenize text
    try:
        return tokenizer.encode(text)
    except Exception as e:
        logging.error(f"Error encountered while tokenizing text: {str(e)}")

def generate_unique_id(user_id=None):
    try:
        base_id = uuid.uuid4()
        components = [str(base_id)]

        if user_id:
            components.append(f"user-{user_id}")
        
        unique_id = "_".join(components)
        return unique_id
    except Exception as e:
        logging.error(f"Error encountered while generating Unique ID: {str(e)}")

def get_metadata(data, max_token=CHUNK_SIZE_LIMIT): # extract metadata from input text, data is a string
    try:
        curr = nlp(data)
        sentences = list(curr.sents)

        texts = []
        metadata = []
        curr_chunk_size = 0
        curr_texts = []
        curr_metadata = {}
        for j, sent in enumerate(sentences, 1):
            sent_text = str(sent)
            sent_tokens = tokenize(sent_text)

            if curr_chunk_size + len(sent_tokens) > max_token:
                if curr_texts:
                    texts.append(" ".join(curr_texts))
                    metadata.append(curr_metadata)
                
                curr_texts = [sent_text]
                curr_metadata = {}
                curr_chunk_size = len(sent_tokens)
            else:
                curr_texts.append(sent_text)
                curr_chunk_size += len(sent_tokens)

            sent_metadata = {}
            for i, ent in enumerate(sent.ents, 1):
                sent_metadata[f"{j}_entity_{i}_text"] = ent.text
                sent_metadata[f"{j}_entity_{i}_label"] = ent.label_
            
            noun_chunks = [chunk.text.strip() for chunk in sent.noun_chunks]
            for i, chunk in enumerate(noun_chunks):
                sent_metadata[f"{j}_noun_chunk_{i}"] = chunk
            
            curr_metadata.update(sent_metadata)

        if curr_texts:
            texts.append(" ".join(curr_texts))
            metadata.append(curr_metadata)
        
        return {"texts": texts, "metadata": metadata}

    except Exception as e:
        logging.error(f"Error encountered while getting metadata: {str(e)}")

# MAIN FUNCTION 👇
def main(req: func.HttpRequest) -> func.HttpResponse:   # add data into pinecone
    """
    Upserts data into pinecone database.

    Args(HttpRequest):
        device_id(string): Users device_id (used as namespace)
        text(string): Data to be stored in database
    
    Returns:
        HttpResponse

    """
    try:
        input_data = req.get_json()
        device_id = input_data.get('device_id')
        if not device_id:
            return func.HttpResponse(json.dumps({"error": "Device ID not found!"}), status_code=400, mimetype="application/json")
        
        text = input_data.get('text')
        if not text:
            return func.HttpResponse(json.dumps({"error": "Text not provided!"}), status_code=400, mimetype="application/json")
        
        data = get_metadata(text)
        
        index = get_index()
        texts = data.get('texts', [])
        metadata = data.get('metadata', [])
        
        if len(texts) != len(metadata):
            return func.HttpResponse(json.dumps({"error": "Number of texts and metadata should be the same"}), status_code=400, mimetype="application/json")
        
        vectors = []
        for i, text in enumerate(texts):
            try:
                embedding = embed_text(text)
                current_metadata = {"text": text, "timestamp": datetime.datetime.now().isoformat()}
                if metadata and metadata[i]:
                    current_metadata.update(metadata[i])
                vectors.append({"id": f"id_{i}", 
                                "values": embedding,
                                "metadata": current_metadata})
            except Exception as e:
                logging.error(f"Error embedding text {i}: {str(e)}")
        
        unique_id = generate_unique_id(device_id)
        index.upsert(vectors=[(unique_id, vectors)], namespace=device_id)
        logging.info(f"Data successfully saved for {device_id}")
        return func.HttpResponse(json.dumps({"message": f"Successfully added {len(vectors)} vectors to the index"}), status_code=200, mimetype="application/json")
    
    except Exception as e:
        logging.error(f"Error while upserting data: {str(e)}")
        return func.HttpResponse(json.dumps({"error": str(e)}), status_code=500, mimetype="application/json")

input:
{
    "device_id": "1182024",
    "text": "I need to buy aloo and pyaaz, also I have a meeting at 20:30 in the evening!"
}
error: Error while upserting data: Invalid type for variable '0'. Required value type is float and passed type was dict at ['values'][0]