| 123 | } |
| 124 | |
| 125 | def analyze_log_directory(directory_path): |
| 126 | grand_total_prompt = 0 |
| 127 | grand_total_cached = 0 |
| 128 | grand_total_completion = 0 |
| 129 | grand_total_tokens = 0 |
| 130 | grand_total_cost = 0.0 |
| 131 | |
| 132 | if not os.path.isdir(directory_path): |
| 133 | return { |
| 134 | "Total Tokens": 0, |
| 135 | "Prompt Tokens": 0, |
| 136 | "Cached Tokens": 0, |
| 137 | "Completion Tokens": 0, |
| 138 | "Total Cost($)": 0.0 |
| 139 | } |
| 140 | |
| 141 | for filename in os.listdir(directory_path): |
| 142 | if filename.endswith(".log"): |
| 143 | file_path = os.path.join(directory_path, filename) |
| 144 | |
| 145 | file_prompt = 0 |
| 146 | file_cached = 0 |
| 147 | file_completion = 0 |
| 148 | file_total = 0 |
| 149 | |
| 150 | with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: |
| 151 | for line in f: |
| 152 | pm = re.search(r"Prompt Tokens:\s*(\d+)", line) |
| 153 | if pm: |
| 154 | file_prompt += int(pm.group(1)) |
| 155 | cm = re.search(r"Completion Tokens:\s*(\d+)", line) |
| 156 | if cm: |
| 157 | file_completion += int(cm.group(1)) |
| 158 | tm = re.search(r"Total Tokens:\s*(\d+)", line) |
| 159 | if tm: |
| 160 | file_total += int(tm.group(1)) |
| 161 | cache_m = re.search(r"Cached Tokens:\s*(\d+)", line) |
| 162 | if cache_m: |
| 163 | file_cached += int(cache_m.group(1)) |
| 164 | |
| 165 | file_uncached = max(0, file_prompt - file_cached) |
| 166 | file_cost = ( |
| 167 | (file_cached / 1_000_000) * PRICE_CACHE_HIT_PER_1M + |
| 168 | (file_uncached / 1_000_000) * PRICE_CACHE_MISS_PER_1M + |
| 169 | (file_completion / 1_000_000) * PRICE_OUTPUT_PER_1M |
| 170 | ) |
| 171 | |
| 172 | grand_total_prompt += file_prompt |
| 173 | grand_total_cached += file_cached |
| 174 | grand_total_completion += file_completion |
| 175 | grand_total_tokens += file_total |
| 176 | grand_total_cost += file_cost |
| 177 | |
| 178 | return { |
| 179 | "Total Tokens": grand_total_tokens, |
| 180 | "Prompt Tokens": grand_total_prompt, |
| 181 | "Cached Tokens": grand_total_cached, |
| 182 | "Completion Tokens": grand_total_completion, |