Making an Azure AI API request with the content being a big dictionary

I’m a newbie and I need to make a request like in the example below, but my issue is that ‘my_dict’ far to big and I keep getting ‘400 Bad Request’ errors, and when I try to split it and make multiple calls I get ‘429 Too Many Requests’ errors. Another issue is that when I test it on smaller data samples it takes ages to finish.

This is the structure of ‘my_dict’, I get it from an Excel file using pandas:

my_dict = {
    "key1": {
            0: "value1.1",
            1: "value2.1",
            ...
            1999: "value2000.1"
    },
    "key2": {
            0: "value1.2",
            1: "value2.2",
            ...
            1999: "value2000.2"
    },
    "key3": {
            0: "value1.3",
            1: "value2.3",
            ...
            1999: "value2000.3"
    },
    "key4": {
            0: "value1.4",
            1: "value2.4",
            ...
            1999: "value2000.4"
    },
}

I need the ai to return a value based on the first items in each of the inner dictionaries, then based on the second items and so on.

import requests

endpoint = 'https://resource-name.openai.azure.com/openai/deployments/deployment-id/chat/completions?api-version=2024-02-01'
api_key = '1q2w3e4r5t6y7u8i9o0p'

headers = {
    'Content-Type': 'application/json',
    'api-key': api_key
}

payload = {
    "messages": [
        {
            "role": "system",
            "content": "Prompt..."
                       f"Dictionary: {my_dict}"
        },
    ],
    "temperature": 0.7
}

response = requests.post(endpoint , headers=headers, json=payload)

print(response.json())

I’d appreciate any help or advice.

4

I tried the below code to manage a large dictionary by splitting it into smaller chunks and making API requests to OpenAI’s GPT-4o model. The objective is to return values from each inner dictionary based on the order of indices (i.e., index 0, index 1, and index 1999).

  • chunk_dict Function: Splits a large dictionary into smaller, manageable chunks based on a specified size for easier handling of large datasets.

  • process_large_dict Function: Iterates through each chunk, sending POST requests to the Azure OpenAI endpoint. The API prompt directs the model to process and return values for indices 0, 1, and 1999 in order.

Code :

import requests
import time

endpoint = 'https://<openai_name>.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-02-15-preview'
api_key = '<api_key>'

headers = {
    'Content-Type': 'application/json',
    'api-key': api_key
}

my_dict = {
    "key1": {
        0: "value1.1",
        1: "value2.1",
        # ...
        1999: "value2000.1"
    },
    "key2": {
        0: "value1.2",
        1: "value2.2",
        # ...
        1999: "value2000.2"
    },
    "key3": {
        0: "value1.3",
        1: "value2.3",
        # ...
        1999: "value2000.3"
    },
    "key4": {
        0: "value1.4",
        1: "value2.4",
        # ...
        1999: "value2000.4"
    },
}

def chunk_dict(d, chunk_size):
    """Split dictionary into smaller chunks."""
    items = list(d.items())
    for i in range(0, len(items), chunk_size):
        yield dict(items[i:i + chunk_size])

def make_request(chunk):
    """Make API request with chunk of data."""
    content = (
        f"Please process the following dictionary and return the values based on the order of their indices:"
        f"n{chunk}nn"
        f"For each key, return the value for index 0 first, then for index 1, and finally for index 1999."
    )
    payload = {
        "messages": [
            {
                "role": "system",
                "content": content
            }
        ],
        "temperature": 0.7
    }
    try:
        response = requests.post(endpoint, headers=headers, json=payload)
        if response.status_code == 429:
            print("Rate limit exceeded. Waiting before retrying...")
            time.sleep(10)  
            return make_request(chunk) 
        elif response.status_code == 200:
            return response.json()
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return None
    except requests.RequestException as e:
        print(f"Request exception: {e}")
        return None

def process_large_dict(my_dict, chunk_size):
    """Process the large dictionary in chunks."""
    chunks = chunk_dict(my_dict, chunk_size)
    results = []
    for chunk in chunks:
        result = make_request(chunk)
        if result:
            results.append(result)
        else:
            print("Failed to get response for chunk.")
    return results

chunk_size = 10 
results = process_large_dict(my_dict, chunk_size)
for result in results:
    print(result)

Output :

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật