|
| 1 | +# Groq Batch Processing |
| 2 | + |
| 3 | +This tutorial will guide you through the process of uploading and processing batch jobs using the Groq API. |
| 4 | + |
| 5 | + |
| 6 | +https://github.com/user-attachments/assets/8ef2e06b-6153-43d3-9122-6bc11b786efd |
| 7 | + |
| 8 | + |
| 9 | +## Step 1: Set Up Dependencies: |
| 10 | + |
| 11 | +Before interacting with the Groq API, you need to install and import the required dependencies. |
| 12 | + |
| 13 | +``` |
| 14 | +import os |
| 15 | +from dotenv import load_dotenv |
| 16 | +import requests # Install with: pip install requests |
| 17 | +import time |
| 18 | +
|
| 19 | +# Load environment variables from .env file |
| 20 | +load_dotenv() |
| 21 | +
|
| 22 | +# Access environment variables |
| 23 | +api_key = os.getenv("GROQ_API_KEY") |
| 24 | +``` |
| 25 | +Make sure you have a `.env` file containing your `GROQ_API_KEY`. If you don't have one already, you can create a free account and generate one [here](https://console.groq.com/keys). |
| 26 | + |
| 27 | +### Create a virtual environment |
| 28 | +`python3 -m venv venv` |
| 29 | + |
| 30 | +### Activate it |
| 31 | +`source venv/bin/activate` |
| 32 | + |
| 33 | +### Install the packages |
| 34 | +`pip3 install groq requests python-dotenv` |
| 35 | + |
| 36 | +# Step 2: Upload the JSONL File to Groq |
| 37 | +``` |
| 38 | +def upload_file_to_groq(api_key, file_path): |
| 39 | + url = "https://api.groq.com/openai/v1/files" |
| 40 | + |
| 41 | + headers = { |
| 42 | + "Authorization": f"Bearer {api_key}" |
| 43 | + } |
| 44 | + |
| 45 | + files = { |
| 46 | + "file": ("batch_file.jsonl", open(file_path, "rb")) |
| 47 | + } |
| 48 | + |
| 49 | + data = {"purpose": "batch"} |
| 50 | + |
| 51 | + response = requests.post(url, headers=headers, files=files, data=data) |
| 52 | + return response.json() |
| 53 | +
|
| 54 | +file_path = "batch_input.jsonl" # Path to your JSONL file |
| 55 | +file_id = "" |
| 56 | +
|
| 57 | +try: |
| 58 | + result = upload_file_to_groq(api_key, file_path) |
| 59 | + file_id = result["id"] |
| 60 | + print("This is the file_id from Step 2: " + file_id) |
| 61 | +except Exception as e: |
| 62 | + print(f"Error: {e}") |
| 63 | +``` |
| 64 | + |
| 65 | +# Step 3: Create a Batch Object |
| 66 | + |
| 67 | +Create a batch object using the uploaded file ID. |
| 68 | + |
| 69 | +``` |
| 70 | +def create_batch(api_key, input_file_id): |
| 71 | + url = "https://api.groq.com/openai/v1/batches" |
| 72 | + |
| 73 | + headers = { |
| 74 | + "Authorization": f"Bearer {api_key}", |
| 75 | + "Content-Type": "application/json" |
| 76 | + } |
| 77 | + |
| 78 | + data = { |
| 79 | + "input_file_id": input_file_id, |
| 80 | + "endpoint": "/v1/chat/completions", |
| 81 | + "completion_window": "24h" |
| 82 | + } |
| 83 | + |
| 84 | + response = requests.post(url, headers=headers, json=data) |
| 85 | + return response.json() |
| 86 | +
|
| 87 | +batch_id = "" |
| 88 | +try: |
| 89 | + result = create_batch(api_key, file_id) |
| 90 | + batch_id = result["id"] |
| 91 | + print("This is the Batch object id from Step 3: " + batch_id) |
| 92 | +except Exception as e: |
| 93 | + print(f"Error: {e}") |
| 94 | +``` |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | +# Step 4: Get the Batch Status |
| 99 | + |
| 100 | +Monitor the batch job's status until it completes. |
| 101 | + |
| 102 | +``` |
| 103 | +def get_batch_status(api_key, batch_id): |
| 104 | + url = f"https://api.groq.com/openai/v1/batches/{batch_id}" |
| 105 | + |
| 106 | + headers = { |
| 107 | + "Authorization": f"Bearer {api_key}", |
| 108 | + "Content-Type": "application/json" |
| 109 | + } |
| 110 | + |
| 111 | + response = requests.get(url, headers=headers) |
| 112 | + return response.json() |
| 113 | +
|
| 114 | +output_file_id = "" |
| 115 | +try: |
| 116 | + result = get_batch_status(api_key, batch_id) |
| 117 | + print("\nStep 4 results: ") |
| 118 | + |
| 119 | + count = 0 |
| 120 | + while result["status"] != "completed" and count < 100: |
| 121 | + result = get_batch_status(api_key, batch_id) |
| 122 | + time.sleep(3) |
| 123 | + print("Your batch status is: " + result["status"]) |
| 124 | + count += 1 |
| 125 | +
|
| 126 | + output_file_id = result.get("output_file_id") |
| 127 | + print("This is your output_file_id from Step 4: " + output_file_id) |
| 128 | +except Exception as e: |
| 129 | + print(f"Error: {e}") |
| 130 | +``` |
| 131 | + |
| 132 | + |
| 133 | +# Step 5: Retrieve Batch Results |
| 134 | + |
| 135 | +Download and save the batch job results. |
| 136 | + |
| 137 | +``` |
| 138 | +def download_file_content(api_key, output_file_id, output_file): |
| 139 | + url = f"https://api.groq.com/openai/v1/files/{output_file_id}/content" |
| 140 | + |
| 141 | + headers = { |
| 142 | + "Authorization": f"Bearer {api_key}" |
| 143 | + } |
| 144 | + |
| 145 | + response = requests.get(url, headers=headers) |
| 146 | + |
| 147 | + with open(output_file, 'wb') as f: |
| 148 | + f.write(response.content) |
| 149 | + |
| 150 | + return f"\nFile downloaded successfully to {output_file}" |
| 151 | +
|
| 152 | +output_file = "batch_output.jsonl" |
| 153 | +try: |
| 154 | + result = download_file_content(api_key, output_file_id, output_file) |
| 155 | + print(result) |
| 156 | +except Exception as e: |
| 157 | + print(f"Error: {e}") |
| 158 | +``` |
| 159 | + |
| 160 | +Now you have successfully uploaded, processed, and retrieved batch job results using the Groq API! |
| 161 | + |
| 162 | + |
| 163 | +## How to run it in your terminal: |
| 164 | +`python3 main.py` |
| 165 | + |
| 166 | + |
| 167 | +### Example output in terminal: |
| 168 | +``` |
| 169 | +This is the file_id from Step 2: file_01jpthgx92e3ts09bma0bfchmt |
| 170 | +This is the Batch object id from Step 3: batch_01jpthgxffe8ms4zqdkf1aejjp |
| 171 | +
|
| 172 | +Step 4 results: |
| 173 | +Your batch status is: validating |
| 174 | +Your batch status is: in_progress |
| 175 | +Your batch status is: completed |
| 176 | +This is your output_file_id from Step 4: file_01jpthh1e3e739wba761nfgvj2 |
| 177 | +
|
| 178 | +File downloaded successfully to batch_output.jsonl |
| 179 | +``` |
| 180 | + |
| 181 | +Example input .jsonl file |
| 182 | +``` |
| 183 | +{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "llama-3.1-8b-instant", "messages": [{"role": "system", "content": "You are a helpful translation assistant. Translate the following into spanish."}, {"role": "user", "content": "Hello, how are you today?"}]}} |
| 184 | +``` |
| 185 | + |
| 186 | +Example output .jsonl file |
| 187 | +``` |
| 188 | +{"id":"batch_req_out_01jpra5p4ve4v8k14zkqn6agjm","custom_id":"request-2","response":{"status_code":200,"request_id":"req_01jpra5n2qef6s66k65v8sy51h","body":{"id":"chatcmpl-f822c700-75aa-4fa3-8f2c-3f65cca8a1d3","object":"chat.completion","created":1742425217,"model":"llama-3.1-8b-instant","choices":[{"index":0,"message":{"role":"assistant","content":"\"Hola, ¿cómo estás hoy\" or more commonly in informal settings: \"Hola, ¿qué onda hoy\". \n\nIf you want it to be a more formal conversation, you could use: \"Buenos días, ¿cómo está hoy?\""},"logprobs":null,"finish_reason":"stop"}],"usage":{"queue_time":1.0087154420000002,"prompt_tokens":55,"prompt_time":0.009901563,"completion_tokens":55,"completion_time":0.073333333,"total_tokens":110,"total_time":0.083234896},"system_fingerprint":"fp_076aab041c","x_groq":{"id":"req_01jpra5n2qef6s66k65v8sy51h"}}},"error":null} |
| 189 | +``` |
| 190 | + |
| 191 | +View more detailed documentation on batch processing [here.](https://console.groq.com/docs/batch) |
0 commit comments