use these 3 codes and teach me how to effectively implement error handling and logging for error detection and other things as a top tier developer from an organisation like Google:

import os
import json
import logging

import openai
from openai import AzureOpenAI
import azure.functions as func
from pymongo.mongo_client import MongoClient

try:
client = MongoClient(os.getenv('MONGODB_CONN_STRING') or "mongodb+srv://navin:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>/mydatabase?retryWrites=true&w=majority")
db = client['Tracker']
devices_col = db['trackingDevices']
except Exception as e:
logging.error(f"Error while connecting to MongoDB: {str(e)}")
raise

EMBED_MODEL = os.getenv('EMBED_MODEL')
client_embedding = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT_EMBEDDING"),
api_key=os.getenv("OPENAI_API_KEY_EMBEDDING"),
api_version="2024-02-01"
)

UTILITY 👇
def embed_text(text):
try:
response = client_embedding.embeddings.create(
model=EMBED_MODEL,
input=[text]
)


    embedding = response.data[0].embedding
    return embedding
except openai.APIError as e:
    logging.error(f"OpenAI API Error: {str(e)}")
    raise
except Exception as e:
    logging.error(f"Unidentified error: {str(e)}")
    raise
def main(req: func.HttpRequest) -> func.HttpResponse:
try:
agent_email = req.form.get('agentEmail')
status = req.form.get('status')
current_location = req.form.get('currentLocation')
agent_name = req.form.get('agentName')
id = req.form.get('id')
agent_manager = req.form.get('agentManagerName', '')
phone = req.form.get('agentPhone', '')
photo = req.files.get('agentPhoto', '')


    if not all([agent_email, status, current_location, agent_name, id]):
        return func.HttpResponse(
            json.dumps({'message': "Missing one or more required fields."}),
            status_code=400,
            mimetype="application/json"
        )
    
    compiled_info = f"""
                    Agent Email: {agent_email}
                    Status: {status}
                    Current Location: {current_location}
                    Agent Name: {agent_name}
                    Device ID: {id}
                    """
    embedding = embed_text(compiled_info)
    payload = {
        'agentEmail': agent_email,
        'status': status,
        'agentManagerName': agent_manager,
        'currentLocation': current_location,
        'agentName': agent_name,
        'id': id,
        'agentPhone': phone,
        'agentPhoto': photo,
        'embedding': embedding
    }
    res = devices_col.insert_one(payload)
    if res.inserted_id:
        logging.info(f"Insertion successfully with document ID: {res.inserted_id}")
        return func.HttpResponse(
            json.dumps({'message':f"Insertion successful with document Id: {res.inserted_id}"}),
            status_code=200,
            mimetype="application/json"
        )
    else:
        logging.error(f"An error occured.")
        raise

except Exception as e:
    logging.error(f"Error while inserting data(main): {str(e)}")
    return func.HttpResponse(
        json.dumps({'message': 'Error while inserting data.'}),
        status_code=400,
        mimetype="application/json"
    )
END of 1st code

import os
import json
import logging

import openai
from openai import AzureOpenAI
import azure.functions as func
from pymongo.mongo_client import MongoClient

try:
client = MongoClient(os.getenv('MONGODB_CONN_STRING'))
db = client['Tracker']
devices_col = db['trackingDevices']
except Exception as e:
logging.error(f"Error while connecting to MongoDB: {str(e)}")
raise

INDEX_NAME = os.getenv('INDEX_NAME') or "pc1-01"
EMBED_MODEL = os.getenv('EMBED_MODEL') or "text-embedding-3-small"

AZURE_OPENAI_ENDPOINT_LLM = os.getenv('AZURE_OPENAI_ENDPOINT_LLM')
OPENAI_API_KEY_LLM = os.getenv('OPENAI_API_KEY_LLM')
AZURE_OPENAI_ENDPOINT_EMBEDDING = os.getenv('AZURE_OPENAI_ENDPOINT_EMBEDDING')
OPENAI_API_KEY_EMBEDDING = os.getenv('OPENAI_API_KEY_EMBEDDING')

client_embedding = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT_EMBEDDING"),
api_key=os.getenv("OPENAI_API_KEY_EMBEDDING"),
api_version="2024-02-01"
)

client_llm = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT_LLM"),
api_key=os.getenv("OPENAI_API_KEY_LLM"),
api_version="2024-02-01"
)

def embed_text(text):
try:
response = client_embedding.embeddings.create(
model=EMBED_MODEL,
input=[text]
)


    embedding = response.data[0].embedding
    return embedding
except Exception as e:
    logging.error(f"Unidentified error: {str(e)}")
    raise
def search(query):
try:
queryVector = embed_text(query)
if not queryVector:
raise ValueError("Embedding returned None.")
logging.info(f"Query Vector: {len(queryVector)}")
pipeline = [
{
'$vectorSearch': {
'exact': False,
'index': INDEX_NAME,
'path': 'embedding',
'queryVector': queryVector,
'limit': 5,
'numCandidates': 10
}
}
]
results = devices_col.aggregate(pipeline)
formatted_docs = []
for i, result in enumerate(results, start=1):
formatted_doc = (
f"Device {i}:\n"
f" - ID: {result.get('id')}\n"
f" - Agent Name: {result.get('agentName')}\n"
f" - Status: {result.get('status')}\n"
f" - Current Location: {result.get('currentLocation')}\n"
f" - Agent Manager: {result.get('agentManagerName')}\n"
f" - Agent Email: {result.get('agentEmail')}\n"
f" - Phone Number: {result.get('phone')}\n"
)
formatted_docs.append(formatted_doc)
return '\n'.join(formatted_docs)


except Exception as e:
    logging.error(f"Error during vectorSearch on database: {str(e)}")
    raise
def query(prompt):
try:
response = client_llm.chat.completions.create(
model="gpt-4o-mini",
messages= [
{"role": "system", "content": "You are a helpful assistant that uses given database entries, answer the query based on this data."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Error when querying LLM: {str(e)}")

def main(req: func.HttpRequest) -> func.HttpResponse:
try:
data = req.get_json()
query_text = data.get('query')
# group_id = data.get('group_id')


    agents_details = search(query_text)
    prompt = f"""
            {query_text}\n
            Details for reference:\n
            {agents_details}\n"""

    response = query(prompt)

    return func.HttpResponse(
        json.dumps({'message':response}),
        status_code=200,
        mimetype="application/json"
    )
except Exception as e:
    logging.error(f"Error while querying (main): {str(e)}")
    return func.HttpResponse(
        json.dumps({'error':str(e)}),
        status_code=400,
        mimetype="application/json"
    )
END of 2nd code

import os
import json
import logging

import openai
from openai import AzureOpenAI
import azure.functions as func
from pymongo.mongo_client import MongoClient
from pymongo.operations import SearchIndexModel

try:
client = MongoClient(os.getenv('MONGODB_CONN_STRING'))
db = client['Tracker']
devices_col = db['trackingDevices']
except Exception as e:
logging.error(f"Error while connecting to MongoDB: {str(e)}")
raise

EMBED_MODEL = os.getenv('EMBED_MODEL')
EMBEDDING_FIELD = os.getenv('EMBEDDING_FIELD')
INDEX_NAME = os.getenv('INDEX_NAME')

client_embedding = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT_EMBEDDING"),
api_key=os.getenv("OPENAI_API_KEY_EMBEDDING"),
api_version="2024-02-01"
)

UTILITY 👇
def embed_text(text):
try:
response = client_embedding.embeddings.create(
model=EMBED_MODEL,
input=[text]
)


    embedding = response.data[0].embedding
    return embedding
except openai.APIError as e:
    logging.error(f"OpenAI API Error: {str(e)}")
    raise
except Exception as e:
    logging.error(f"Unidentified error: {str(e)}")
    raise
def create_index():
"""
Creates a vector index.
"""
try:
search_index_model = SearchIndexModel(
definition={
"fields": [
{
"type": "vector",
"numDimensions": 1536,
"path": "embedding",
"similarity": "cosine"
}
]
},
name = INDEX_NAME,
type = "vectorSearch"
)
result = devices_col.create_search_index(model=search_index_model)
logging.info(f"New search index named {result} is building...")
except Exception as e:
logging.error(f"Error while creating a search index: {str(e)}")
raise

MAIN 👇
def main(req: func.HttpRequest) -> func.HttpResponse:
try:
data = req.get_json()
agent_email = data.get('agentEmail')
status = data.get('status')
current_location = data.get('currentLocation')
agent_name = data.get('agentName')
id = data.get('id')
if not all([agent_email, status, current_location, agent_name, id]):
return func.HttpResponse(
json.dumps({'message': "Missing one or more required fields."}),
status_code=400,
mimetype="application/json"
)


    compiled_info = f"""
                    Agent Email: {agent_email}
                    Status: {status}
                    Current Location: {current_location}
                    Agent Name: {agent_name}
                    Device ID: {id}
                    """
    embedding = embed_text(compiled_info)
    res = devices_col.update_one(
        {'id':id},
        {'$set': {'status':status, 'currentLocation':current_location, 'embedding':embedding}})
    if res.matched_count>0:
        logging.info(f"Document successfully updated with Upsert ID: {res.upserted_id}")
        return func.HttpResponse(
            json.dumps({'message': "Successfully updated information."}),
            status_code=200,
            mimetype="application/json"
        )
    else:
        logging.info(f"No document found with id: {id}")
        return func.HttpResponse(
            json.dumps({'message': "Relevant document not found."}),
            status_code=400,
            mimetype="application/json"
        )
        
except Exception as e:
    logging.error(f"Error while storing data (main): {str(e)}")
    return func.HttpResponse(
        json.dumps({'message': str(e)}),
        status_code=400,
        mimetype="application/json"
    )
END of 3rd code