| 11 | |
| 12 | |
| 13 | def run_query(url, messages, tools=None, stream=False, tool_choice=None): |
| 14 | payload = { |
| 15 | "messages": messages, |
| 16 | "stream": stream, |
| 17 | "max_tokens": 5000, |
| 18 | } |
| 19 | if tools: |
| 20 | payload["tools"] = tools |
| 21 | if tool_choice: |
| 22 | payload["tool_choice"] = tool_choice |
| 23 | |
| 24 | try: |
| 25 | response = requests.post(url, json=payload, stream=stream) |
| 26 | response.raise_for_status() |
| 27 | except requests.exceptions.RequestException as e: |
| 28 | if e.response is not None: |
| 29 | logger.info(f"Response error: {e} for {e.response.content}\n") |
| 30 | else: |
| 31 | logger.info(f"Error connecting to server: {e}\n") |
| 32 | return None |
| 33 | |
| 34 | full_content = "" |
| 35 | reasoning_content = "" |
| 36 | tool_calls = [] |
| 37 | |
| 38 | if stream: |
| 39 | logger.info(f"--- Streaming response (Tools: {bool(tools)}) ---\n") |
| 40 | for line in response.iter_lines(): |
| 41 | if line: |
| 42 | decoded_line = line.decode("utf-8") |
| 43 | if decoded_line.startswith("data: "): |
| 44 | data_str = decoded_line[6:] |
| 45 | if data_str == "[DONE]": |
| 46 | break |
| 47 | try: |
| 48 | data = json.loads(data_str) |
| 49 | if "choices" in data and len(data["choices"]) > 0: |
| 50 | delta = data["choices"][0].get("delta", {}) |
| 51 | |
| 52 | # Content |
| 53 | content_chunk = delta.get("content", "") |
| 54 | if content_chunk: |
| 55 | full_content += content_chunk |
| 56 | logger.info(content_chunk) |
| 57 | |
| 58 | # Reasoning |
| 59 | reasoning_chunk = delta.get("reasoning_content", "") |
| 60 | if reasoning_chunk: |
| 61 | reasoning_content += reasoning_chunk |
| 62 | logger.info(f"\x1B[3m{reasoning_chunk}\x1B[0m") |
| 63 | |
| 64 | # Tool calls |
| 65 | if "tool_calls" in delta: |
| 66 | for tc in delta["tool_calls"]: |
| 67 | index = tc.get("index") |
| 68 | if index is not None: |
| 69 | while len(tool_calls) <= index: |
| 70 | # Using "function" as type default but could be flexible |