| 94 | return await response.json() |
| 95 | |
| 96 | async def run_gemini_api(): |
| 97 | if not os.path.exists(output_path): |
| 98 | open(output_path, "w").close() |
| 99 | with open(output_path, "r", encoding="utf-8") as f: |
| 100 | visited = [json.loads(line)["question"] for line in f] |
| 101 | data_list = [] |
| 102 | for item in ds["question"]: |
| 103 | if item not in visited: |
| 104 | data_list.append(item) |
| 105 | semaphore = asyncio.Semaphore(MAX_CONCURRENT) |
| 106 | async with aiohttp.ClientSession() as session: |
| 107 | if search: |
| 108 | tasks = [ |
| 109 | fetch(session, GEMINI_BASE_URL, headers, { |
| 110 | "model": "gemini-1.5-pro", |
| 111 | "contents": [ |
| 112 | {"role": "user", |
| 113 | "parts": |
| 114 | [ |
| 115 | {"text": query}, |
| 116 | {"tools": { |
| 117 | "google_search_retrieval": { |
| 118 | "dynamic_retrieval_config": { |
| 119 | "mode": "MODE_DYNAMIC", |
| 120 | "dynamic_threshold": 0 |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | ] |
| 126 | } |
| 127 | ] |
| 128 | }, semaphore, query) |
| 129 | for query in data_list |
| 130 | ] |
| 131 | else: |
| 132 | tasks = [ |
| 133 | fetch(session, GEMINI_BASE_URL, headers, { |
| 134 | "model": "gemini-1.5-pro", |
| 135 | "contents": [{"role": "user", "parts": [{"text": query}]}], |
| 136 | "candidates": 1 |
| 137 | }, semaphore, query) |
| 138 | for query in data_list |
| 139 | ] |
| 140 | for future in tqdm.as_completed(tasks, total=len(tasks), desc="Processing queries"): |
| 141 | query_text, result = await future |
| 142 | adic = {"question": query_text, "pred": result["candidates"][0]["content"]["parts"][0]["text"]} |
| 143 | with open(output_path, "a", encoding="utf-8") as f: |
| 144 | f.write(json.dumps(adic, ensure_ascii=False) + "\n") |
| 145 | |
| 146 | asyncio.run(run_gemini_api()) |
| 147 | |