(model_name, conv, temperature, top_p, api_key=None)
| 234 | |
| 235 | |
| 236 | def bard_api_stream_iter(model_name, conv, temperature, top_p, api_key=None): |
| 237 | del top_p # not supported |
| 238 | del temperature # not supported |
| 239 | |
| 240 | if api_key is None: |
| 241 | api_key = os.environ["BARD_API_KEY"] |
| 242 | |
| 243 | # convert conv to conv_bard |
| 244 | conv_bard = [] |
| 245 | for turn in conv: |
| 246 | if turn["role"] == "user": |
| 247 | conv_bard.append({"author": "0", "content": turn["content"]}) |
| 248 | elif turn["role"] == "assistant": |
| 249 | conv_bard.append({"author": "1", "content": turn["content"]}) |
| 250 | else: |
| 251 | raise ValueError(f"Unsupported role: {turn['role']}") |
| 252 | |
| 253 | params = { |
| 254 | "model": model_name, |
| 255 | "prompt": conv_bard, |
| 256 | } |
| 257 | logger.info(f"==== request ====\n{params}") |
| 258 | |
| 259 | try: |
| 260 | res = requests.post( |
| 261 | f"https://generativelanguage.googleapis.com/v1beta2/models/{model_name}:generateMessage?key={api_key}", |
| 262 | json={ |
| 263 | "prompt": { |
| 264 | "messages": conv_bard, |
| 265 | }, |
| 266 | }, |
| 267 | timeout=30, |
| 268 | ) |
| 269 | except Exception as e: |
| 270 | logger.error(f"==== error ====\n{e}") |
| 271 | yield { |
| 272 | "text": f"**API REQUEST ERROR** Reason: {e}.", |
| 273 | "error_code": 1, |
| 274 | } |
| 275 | |
| 276 | if res.status_code != 200: |
| 277 | logger.error(f"==== error ==== ({res.status_code}): {res.text}") |
| 278 | yield { |
| 279 | "text": f"**API REQUEST ERROR** Reason: status code {res.status_code}.", |
| 280 | "error_code": 1, |
| 281 | } |
| 282 | |
| 283 | response_json = res.json() |
| 284 | if "candidates" not in response_json: |
| 285 | logger.error(f"==== error ==== response blocked: {response_json}") |
| 286 | reason = response_json["filters"][0]["reason"] |
| 287 | yield { |
| 288 | "text": f"**API REQUEST ERROR** Reason: {reason}.", |
| 289 | "error_code": 1, |
| 290 | } |
| 291 | |
| 292 | response = response_json["candidates"][0]["content"] |
| 293 | pos = 0 |
no outgoing calls
no test coverage detected
searching dependent graphs…