(messages: list[dict], stream: bool = True, extra_stop: list = None)
| 94 | _server_proc = None |
| 95 | |
| 96 | def infer(messages: list[dict], stream: bool = True, extra_stop: list = None) -> str: |
| 97 | global last_tps |
| 98 | _start_server() |
| 99 | cfg = MODEL_CONFIG |
| 100 | |
| 101 | stop_tokens = list(cfg["stop"]) + [ |
| 102 | "</tool>", "</write_file>", "</shell>", |
| 103 | # Prevent model from echoing system prompt sections into its response |
| 104 | "\n## Current Project", "\n## Project Map", "\n## Loaded Files", |
| 105 | "\n## Project Memory", "\nuser\n", "\nUSER\n", "\nUser\n", |
| 106 | "<|im_start|>user", "<|im_start|>system", |
| 107 | ] |
| 108 | if extra_stop: |
| 109 | stop_tokens += [s for s in extra_stop if s not in stop_tokens] |
| 110 | |
| 111 | payload = json.dumps({ |
| 112 | "model": "codey", |
| 113 | "messages": messages, |
| 114 | "max_tokens": cfg["max_tokens"], |
| 115 | "temperature": cfg["temperature"], |
| 116 | "top_p": cfg["top_p"], |
| 117 | "top_k": cfg["top_k"], |
| 118 | "repeat_penalty": cfg["repeat_penalty"], |
| 119 | "stop": stop_tokens, |
| 120 | "stream": stream, |
| 121 | }).encode("utf-8") |
| 122 | |
| 123 | req = urllib.request.Request( |
| 124 | CHAT_URL, |
| 125 | data=payload, |
| 126 | headers={"Content-Type": "application/json"}, |
| 127 | method="POST", |
| 128 | ) |
| 129 | |
| 130 | response_text = "" |
| 131 | |
| 132 | _t0 = time.time() |
| 133 | try: |
| 134 | with urllib.request.urlopen(req, timeout=300) as resp: |
| 135 | if stream: |
| 136 | print("\033[1;32mCodey:\033[0m ", end="", flush=True) |
| 137 | for raw_line in resp: |
| 138 | line = raw_line.decode("utf-8").strip() |
| 139 | if not line or not line.startswith("data: "): |
| 140 | continue |
| 141 | chunk = line[6:] |
| 142 | if chunk == "[DONE]": |
| 143 | break |
| 144 | try: |
| 145 | data = json.loads(chunk) |
| 146 | token = data["choices"][0]["delta"].get("content", "") |
| 147 | response_text += token |
| 148 | print(token, end="", flush=True) |
| 149 | except Exception: |
| 150 | continue |
| 151 | print() |
| 152 | _elapsed = time.time() - _t0 |
| 153 | if _elapsed > 0 and response_text: |
nothing calls this directly
no test coverage detected