chat.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. # Copyright 2025 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import json
  16. import os
  17. import platform
  18. import re
  19. import string
  20. import time
  21. from collections.abc import AsyncIterator
  22. from typing import Annotated, Any
  23. from urllib.parse import urljoin, urlparse
  24. import httpx
  25. import requests
  26. import typer
  27. import yaml
  28. from huggingface_hub import AsyncInferenceClient, ChatCompletionStreamOutput
  29. from transformers import GenerationConfig
  30. from transformers.utils import is_rich_available
  31. try:
  32. import readline # noqa importing this enables GNU readline capabilities
  33. except ImportError:
  34. # some platforms may not support readline: https://docs.python.org/3/library/readline.html
  35. pass
  36. if platform.system() != "Windows":
  37. import pwd
  38. if is_rich_available():
  39. from rich import filesize
  40. from rich.console import Console
  41. from rich.live import Live
  42. from rich.markdown import Markdown
  43. from rich.progress import BarColumn, Progress, ProgressColumn, TextColumn, TimeElapsedColumn
  44. from rich.text import Text
  45. DEFAULT_HTTP_ENDPOINT = {"hostname": "localhost", "port": 8000}
  46. ALLOWED_KEY_CHARS = set(string.ascii_letters + string.whitespace)
  47. ALLOWED_VALUE_CHARS = set(
  48. string.ascii_letters + string.digits + string.whitespace + r".!\"#$%&'()*+,\-/:<=>?@[]^_`{|}~"
  49. )
  50. DEFAULT_EXAMPLES = {
  51. "llama": {"text": "There is a Llama in my lawn, how can I get rid of it?"},
  52. "code": {
  53. "text": (
  54. "Write a Python function that integrates any Python function f(x) numerically over an arbitrary "
  55. "interval [x_start, x_end]."
  56. ),
  57. },
  58. "helicopter": {"text": "How many helicopters can a human eat in one sitting?"},
  59. "numbers": {"text": "Count to 10 but skip every number ending with an 'e'"},
  60. "birds": {"text": "Why aren't birds real?"},
  61. "socks": {"text": "Why is it important to eat socks after meditating?"},
  62. "numbers2": {"text": "Which number is larger, 9.9 or 9.11?"},
  63. }
  64. # Printed at the start of a chat session
  65. HELP_STRING_MINIMAL = """
  66. **TRANSFORMERS CHAT INTERFACE**
  67. Chat interface to try out a model. Besides chatting with the model, here are some basic commands:
  68. - **!help**: shows all available commands (set generation settings, save chat, etc.)
  69. - **!status**: shows the current status of the model and generation settings
  70. - **!clear**: clears the current conversation and starts a new one
  71. - **!exit**: closes the interface
  72. """
  73. # Printed when the user types `help` in the chat session
  74. HELP_STRING = f"""
  75. **TRANSFORMERS CHAT INTERFACE HELP**
  76. Full command list:
  77. - **!help**: shows this help message
  78. - **!clear**: clears the current conversation and starts a new one
  79. - **!status**: shows the current status of the model and generation settings
  80. - **!example {{NAME}}**: loads example named `{{NAME}}` from the config and uses it as the user input.
  81. Available example names: `{"`, `".join(DEFAULT_EXAMPLES.keys())}`
  82. - **!set {{ARG_1}}={{VALUE_1}} {{ARG_2}}={{VALUE_2}}** ...: changes the system prompt or generation settings (multiple
  83. settings are separated by a space). Accepts the same flags and format as the `generate_flags` CLI argument.
  84. If you're a new user, check this basic flag guide: https://huggingface.co/docs/transformers/llm_tutorial#common-options
  85. - **!save {{SAVE_NAME}} (optional)**: saves the current chat and settings to file by default to
  86. `./chat_history/{{MODEL_ID}}/chat_{{DATETIME}}.yaml` or `{{SAVE_NAME}}` if provided
  87. - **!exit**: closes the interface
  88. """
  89. class RichInterface:
  90. def __init__(self, model_id: str, user_id: str, base_url: str):
  91. self._console = Console()
  92. self.model_id = model_id
  93. self.user_id = user_id
  94. self.base_url = base_url
  95. async def stream_output(self, stream: AsyncIterator[ChatCompletionStreamOutput]) -> tuple[str, str | Any | None]:
  96. self._console.print(f"[bold blue]<{self.model_id}>:")
  97. with Live(console=self._console, refresh_per_second=4) as live:
  98. text = ""
  99. completion_tokens = 0
  100. start_time = time.time()
  101. finish_reason: str | None = None
  102. async for token in await stream:
  103. outputs = token.choices[0].delta.content
  104. finish_reason = getattr(token.choices[0], "finish_reason", finish_reason)
  105. usage = getattr(token, "usage", None)
  106. if usage is not None:
  107. completion_tokens = getattr(usage, "completion_tokens", completion_tokens)
  108. if not outputs:
  109. continue
  110. # Escapes single words encased in <>, e.g. <think> -> \<think\>, for proper rendering in Markdown.
  111. # It only escapes single words that may have `_`, optionally following a `/` (e.g. </think>)
  112. outputs = re.sub(r"<(/*)(\w*)>", r"\<\1\2\>", outputs)
  113. text += outputs
  114. # Render the accumulated text as Markdown
  115. # NOTE: this is a workaround for the rendering "unstandard markdown"
  116. # in rich. The chatbots output treat "\n" as a new line for
  117. # better compatibility with real-world text. However, rendering
  118. # in markdown would break the format. It is because standard markdown
  119. # treat a single "\n" in normal text as a space.
  120. # Our workaround is adding two spaces at the end of each line.
  121. # This is not a perfect solution, as it would
  122. # introduce trailing spaces (only) in code block, but it works well
  123. # especially for console output, because in general the console does not
  124. # care about trailing spaces.
  125. lines = []
  126. for line in text.splitlines():
  127. lines.append(line)
  128. if line.startswith("```"):
  129. # Code block marker - do not add trailing spaces, as it would
  130. # break the syntax highlighting
  131. lines.append("\n")
  132. else:
  133. lines.append(" \n")
  134. markdown = Markdown("".join(lines).strip(), code_theme="github-dark")
  135. # Update the Live console output
  136. live.update(markdown, refresh=True)
  137. elapsed = time.time() - start_time
  138. if elapsed > 0 and completion_tokens > 0:
  139. tok_per_sec = completion_tokens / elapsed
  140. self._console.print()
  141. self._console.print(f"[dim]{completion_tokens} tokens in {elapsed:.1f}s ({tok_per_sec:.1f} tok/s)[/dim]")
  142. self._console.print()
  143. return text, finish_reason
  144. def input(self) -> str:
  145. """Gets user input from the console."""
  146. input = self._console.input(f"[bold red]<{self.user_id}>:\n")
  147. self._console.print()
  148. return input
  149. def clear(self):
  150. """Clears the console."""
  151. self._console.clear()
  152. def print_user_message(self, text: str):
  153. """Prints a user message to the console."""
  154. self._console.print(f"[bold red]<{self.user_id}>:[/ bold red]\n{text}")
  155. self._console.print()
  156. def print_color(self, text: str, color: str):
  157. """Prints text in a given color to the console."""
  158. self._console.print(f"[bold {color}]{text}")
  159. self._console.print()
  160. def confirm(self, message: str, default: bool = False) -> bool:
  161. """Displays a yes/no prompt to the user, returning True for confirmation."""
  162. default_hint = "Y/n" if default else "y/N"
  163. response = self._console.input(f"[bold yellow]{message} ({default_hint}): ")
  164. self._console.print()
  165. response = response.strip().lower()
  166. if not response:
  167. return default
  168. return response in {"y", "yes"}
  169. def print_help(self, minimal: bool = False):
  170. """Prints the help message to the console."""
  171. self._console.print(Markdown(HELP_STRING_MINIMAL if minimal else HELP_STRING))
  172. self._console.print()
  173. def print_model_load(self, model: str):
  174. response = requests.post(f"{self.base_url.rstrip('/')}/load_model", json={"model": model}, stream=True)
  175. response.raise_for_status()
  176. class StatsColumn(ProgressColumn):
  177. def render(self, task):
  178. if not task.total:
  179. return Text("")
  180. if task.fields.get("unit") == "bytes":
  181. done = filesize.decimal(int(task.completed))
  182. tot = filesize.decimal(int(task.total))
  183. speed = f" {filesize.decimal(int(task.speed))}/s" if task.speed else ""
  184. if task.time_remaining is not None:
  185. eta = f" {int(task.time_remaining // 60)}:{int(task.time_remaining % 60):02d}"
  186. else:
  187. eta = ""
  188. return Text(f"{done}/{tot}{speed}{eta}", style="progress.download")
  189. return Text(f"{int(task.completed)}/{int(task.total)}")
  190. stage_labels = {
  191. "processor": "Loading processor",
  192. "config": "Loading config",
  193. "download": "Downloading files",
  194. "weights": "Loading into memory",
  195. }
  196. # Include the model name prefix in descriptions only when the terminal is wide enough.
  197. # The bar, stats, and elapsed columns need ~70 chars; the model prefix needs len(model)+5.
  198. show_model_prefix = self._console.width >= len(model) + 5 + 70
  199. def _label(stage_key):
  200. stage_text = stage_labels.get(stage_key, stage_key)
  201. if show_model_prefix:
  202. return f"{model} → {stage_text}"
  203. return stage_text
  204. progress = Progress(
  205. TextColumn("[bold]{task.description}"),
  206. BarColumn(bar_width=40),
  207. StatsColumn(),
  208. TimeElapsedColumn(),
  209. console=self._console,
  210. )
  211. task_id = progress.add_task(_label("processor"), total=None)
  212. cached = False
  213. with Live(progress, console=self._console, transient=True):
  214. for line in response.iter_lines():
  215. if not line or not line.startswith(b"data: "):
  216. continue
  217. event = json.loads(line[6:])
  218. status = event.get("status")
  219. if status == "ready":
  220. cached = event.get("cached", False)
  221. break
  222. if status == "error":
  223. raise RuntimeError(event.get("message", "Unknown error"))
  224. if status == "loading":
  225. stage = event.get("stage")
  226. prog = event.get("progress")
  227. label = _label(stage)
  228. if prog:
  229. unit = "bytes" if stage == "download" else "items"
  230. progress.update(
  231. task_id, description=label, completed=prog["current"], total=prog.get("total"), unit=unit
  232. )
  233. else:
  234. progress.update(task_id, description=label, completed=0, total=None)
  235. if cached:
  236. self._console.print(Markdown(f"_*{model} was already loaded.*_"))
  237. else:
  238. self._console.print(Markdown(f"_*{model} is warm.*_"))
  239. self._console.print()
  240. def print_status(self, config: GenerationConfig):
  241. """Prints the status of the model and generation settings to the console."""
  242. self._console.print(f"[bold blue]Model: {self.model_id}\n")
  243. self._console.print(f"[bold blue]{config}")
  244. self._console.print()
  245. class Chat:
  246. """Chat with a model from the command line."""
  247. # Defining a class to help with internal state but in practice it's just a method to call
  248. # TODO: refactor into a proper module with helpers + 1 main method
  249. def __init__(
  250. self,
  251. model_id: Annotated[str, typer.Argument(help="ID of the model to use (e.g. 'HuggingFaceTB/SmolLM3-3B').")],
  252. base_url: Annotated[
  253. str | None, typer.Argument(help="Base url to connect to (e.g. http://localhost:8000/v1).")
  254. ] = f"http://{DEFAULT_HTTP_ENDPOINT['hostname']}:{DEFAULT_HTTP_ENDPOINT['port']}",
  255. generate_flags: Annotated[
  256. list[str] | None,
  257. typer.Argument(
  258. help=(
  259. "Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, "
  260. "and lists of integers, more advanced parameterization should be set through --generation-config. "
  261. "Example: `transformers chat <base_url> <model_id> max_new_tokens=100 do_sample=False eos_token_id=[1,2]`. "
  262. "If you're a new user, check this basic flag guide: "
  263. "https://huggingface.co/docs/transformers/llm_tutorial#common-options"
  264. )
  265. ),
  266. ] = None,
  267. # General settings
  268. user: Annotated[
  269. str | None,
  270. typer.Option(help="Username to display in chat interface. Defaults to the current user's name."),
  271. ] = None,
  272. system_prompt: Annotated[str | None, typer.Option(help="System prompt.")] = None,
  273. save_folder: Annotated[str, typer.Option(help="Folder to save chat history.")] = "./chat_history/",
  274. examples_path: Annotated[str | None, typer.Option(help="Path to a yaml file with examples.")] = None,
  275. # Generation settings
  276. generation_config: Annotated[
  277. str | None,
  278. typer.Option(
  279. help="Path to a local generation config file or to a HuggingFace repo containing a `generation_config.json` file. Other generation settings passed as CLI arguments will be applied on top of this generation config."
  280. ),
  281. ] = None,
  282. ) -> None:
  283. """Chat with a model from the command line."""
  284. self.base_url = base_url
  285. parsed = urlparse(self.base_url)
  286. if parsed.hostname == DEFAULT_HTTP_ENDPOINT["hostname"] and parsed.port == DEFAULT_HTTP_ENDPOINT["port"]:
  287. self.check_health(self.base_url)
  288. self.model_id = model_id
  289. self.system_prompt = system_prompt
  290. self.save_folder = save_folder
  291. # Generation settings
  292. config = load_generation_config(generation_config)
  293. config.update(do_sample=True, max_new_tokens=256) # some default values
  294. config.update(**parse_generate_flags(generate_flags))
  295. self.config = config
  296. self.settings = {"base_url": base_url, "model_id": model_id, "config": self.config.to_dict()}
  297. # User settings
  298. self.user = user if user is not None else get_username()
  299. # Load examples
  300. if examples_path:
  301. with open(examples_path) as f:
  302. self.examples = yaml.safe_load(f)
  303. else:
  304. self.examples = DEFAULT_EXAMPLES
  305. # Check requirements
  306. if not is_rich_available():
  307. raise ImportError("You need to install rich to use the chat interface. (`pip install rich`)")
  308. # Run chat session
  309. asyncio.run(self._inner_run())
  310. @staticmethod
  311. def check_health(url):
  312. health_url = urljoin(url + "/", "health")
  313. try:
  314. output = httpx.get(health_url)
  315. if output.status_code != 200:
  316. raise ValueError(
  317. f"The server running on {url} returned status code {output.status_code} on health check (/health)."
  318. )
  319. except httpx.ConnectError:
  320. raise ValueError(
  321. f"No server currently running on {url}. To run a local server, please run `transformers serve` in a"
  322. f"separate shell. Find more information here: https://huggingface.co/docs/transformers/serving"
  323. )
  324. return True
  325. def handle_non_exit_user_commands(
  326. self,
  327. user_input: str,
  328. interface: RichInterface,
  329. examples: dict[str, dict[str, str]],
  330. config: GenerationConfig,
  331. chat: list[dict],
  332. ) -> tuple[list[dict], GenerationConfig]:
  333. """
  334. Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the
  335. generation config (e.g. set a new flag).
  336. """
  337. valid_command = True
  338. if user_input == "!clear":
  339. chat = new_chat_history(self.system_prompt)
  340. interface.clear()
  341. elif user_input == "!help":
  342. interface.print_help()
  343. elif user_input.startswith("!save") and len(user_input.split()) < 2:
  344. split_input = user_input.split()
  345. filename = (
  346. split_input[1]
  347. if len(split_input) == 2
  348. else os.path.join(self.save_folder, self.model_id, f"chat_{time.strftime('%Y-%m-%d_%H-%M-%S')}.json")
  349. )
  350. save_chat(filename=filename, chat=chat, settings=self.settings)
  351. interface.print_color(text=f"Chat saved to {filename}!", color="green")
  352. elif user_input.startswith("!set"):
  353. # splits the new args into a list of strings, each string being a `flag=value` pair (same format as
  354. # `generate_flags`)
  355. new_generate_flags = user_input[4:].strip()
  356. new_generate_flags = new_generate_flags.split()
  357. # sanity check: each member in the list must have an =
  358. for flag in new_generate_flags:
  359. if "=" not in flag:
  360. interface.print_color(
  361. text=(
  362. f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
  363. "`arg_1=value_1 arg_2=value_2 ...`."
  364. ),
  365. color="red",
  366. )
  367. break
  368. else:
  369. # Update config from user flags
  370. config.update(**parse_generate_flags(new_generate_flags))
  371. elif user_input.startswith("!example") and len(user_input.split()) == 2:
  372. example_name = user_input.split()[1]
  373. if example_name in examples:
  374. interface.clear()
  375. chat = []
  376. interface.print_user_message(examples[example_name]["text"])
  377. chat.append({"role": "user", "content": examples[example_name]["text"]})
  378. else:
  379. example_error = (
  380. f"Example {example_name} not found in list of available examples: {list(examples.keys())}."
  381. )
  382. interface.print_color(text=example_error, color="red")
  383. elif user_input == "!status":
  384. interface.print_status(config=config)
  385. else:
  386. valid_command = False
  387. interface.print_color(text=f"'{user_input}' is not a valid command. Showing help message.", color="red")
  388. interface.print_help()
  389. return chat, valid_command, config
  390. async def _inner_run(self):
  391. interface = RichInterface(model_id=self.model_id, user_id=self.user, base_url=self.base_url)
  392. interface.clear()
  393. chat = new_chat_history(self.system_prompt)
  394. # Starts the session with a minimal help message at the top, so that a user doesn't get stuck
  395. interface.print_help(minimal=True)
  396. interface.print_model_load(self.model_id)
  397. config = self.config
  398. async with AsyncInferenceClient(base_url=self.base_url) as client:
  399. pending_user_input: str | None = None
  400. while True:
  401. try:
  402. if pending_user_input is not None:
  403. user_input = pending_user_input
  404. pending_user_input = None
  405. interface.print_user_message(user_input)
  406. else:
  407. user_input = interface.input()
  408. # User commands
  409. if user_input == "!exit":
  410. break
  411. elif user_input == "!clear":
  412. chat = new_chat_history(self.system_prompt)
  413. interface.clear()
  414. continue
  415. elif user_input == "!help":
  416. interface.print_help()
  417. continue
  418. elif user_input.startswith("!save") and len(user_input.split()) < 2:
  419. split_input = user_input.split()
  420. filename = (
  421. split_input[1]
  422. if len(split_input) == 2
  423. else os.path.join(
  424. self.save_folder, self.model_id, f"chat_{time.strftime('%Y-%m-%d_%H-%M-%S')}.json"
  425. )
  426. )
  427. save_chat(filename=filename, chat=chat, settings=self.settings)
  428. interface.print_color(text=f"Chat saved to {filename}!", color="green")
  429. continue
  430. elif user_input.startswith("!set"):
  431. # splits the new args into a list of strings, each string being a `flag=value` pair (same format as
  432. # `generate_flags`)
  433. new_generate_flags = user_input[4:].strip()
  434. new_generate_flags = new_generate_flags.split()
  435. # sanity check: each member in the list must have an =
  436. for flag in new_generate_flags:
  437. if "=" not in flag:
  438. interface.print_color(
  439. text=(
  440. f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
  441. "`arg_1=value_1 arg_2=value_2 ...`."
  442. ),
  443. color="red",
  444. )
  445. break
  446. else:
  447. # Update config from user flags
  448. config.update(**parse_generate_flags(new_generate_flags))
  449. continue
  450. elif user_input.startswith("!example") and len(user_input.split()) == 2:
  451. example_name = user_input.split()[1]
  452. if example_name in self.examples:
  453. interface.clear()
  454. chat = []
  455. interface.print_user_message(self.examples[example_name]["text"])
  456. chat.append({"role": "user", "content": self.examples[example_name]["text"]})
  457. else:
  458. example_error = f"Example {example_name} not found in list of available examples: {list(self.examples.keys())}."
  459. interface.print_color(text=example_error, color="red")
  460. elif user_input == "!status":
  461. interface.print_status(config=config)
  462. continue
  463. elif user_input.startswith("!"):
  464. interface.print_color(
  465. text=f"'{user_input}' is not a valid command. Showing help message.", color="red"
  466. )
  467. interface.print_help()
  468. continue
  469. else:
  470. chat.append({"role": "user", "content": user_input})
  471. extra_body = {
  472. "generation_config": config.to_json_string(),
  473. "model": self.model_id,
  474. }
  475. stream = client.chat_completion(
  476. chat,
  477. stream=True,
  478. model=self.model_id,
  479. extra_body=extra_body,
  480. )
  481. model_output, finish_reason = await interface.stream_output(stream)
  482. chat.append({"role": "assistant", "content": model_output})
  483. if finish_reason == "length":
  484. interface.print_color("Generation stopped after reaching the token limit.", "yellow")
  485. if interface.confirm("Continue generating?"):
  486. pending_user_input = "Please continue. Do not repeat text.”"
  487. continue
  488. except KeyboardInterrupt:
  489. break
  490. def load_generation_config(generation_config: str | None) -> GenerationConfig:
  491. if generation_config is None:
  492. return GenerationConfig()
  493. if ".json" in generation_config: # is a local file
  494. dirname = os.path.dirname(generation_config)
  495. filename = os.path.basename(generation_config)
  496. return GenerationConfig.from_pretrained(dirname, filename)
  497. else:
  498. return GenerationConfig.from_pretrained(generation_config)
  499. def parse_generate_flags(generate_flags: list[str] | None) -> dict:
  500. """Parses the generate flags from the user input into a dictionary of `generate` kwargs."""
  501. if generate_flags is None or len(generate_flags) == 0:
  502. return {}
  503. # Assumption: `generate_flags` is a list of strings, each string being a `flag=value` pair, that can be parsed
  504. # into a json string if we:
  505. # 1. Add quotes around each flag name
  506. generate_flags_as_dict = {'"' + flag.split("=")[0] + '"': flag.split("=")[1] for flag in generate_flags}
  507. # 2. Handle types:
  508. # 2. a. booleans should be lowercase, None should be null
  509. generate_flags_as_dict = {
  510. k: v.lower() if v.lower() in ["true", "false"] else v for k, v in generate_flags_as_dict.items()
  511. }
  512. generate_flags_as_dict = {k: "null" if v == "None" else v for k, v in generate_flags_as_dict.items()}
  513. # 2. b. strings should be quoted
  514. def is_number(s: str) -> bool:
  515. # handle negative numbers
  516. s = s.removeprefix("-")
  517. return s.replace(".", "", 1).isdigit()
  518. generate_flags_as_dict = {k: f'"{v}"' if not is_number(v) else v for k, v in generate_flags_as_dict.items()}
  519. # 2. c. [no processing needed] lists are lists of ints because `generate` doesn't take lists of strings :)
  520. # We also mention in the help message that we only accept lists of ints for now.
  521. # 3. Join the result into a comma separated string
  522. generate_flags_string = ", ".join([f"{k}: {v}" for k, v in generate_flags_as_dict.items()])
  523. # 4. Add the opening/closing brackets
  524. generate_flags_string = "{" + generate_flags_string + "}"
  525. # 5. Remove quotes around boolean/null and around lists
  526. generate_flags_string = generate_flags_string.replace('"null"', "null")
  527. generate_flags_string = generate_flags_string.replace('"true"', "true")
  528. generate_flags_string = generate_flags_string.replace('"false"', "false")
  529. generate_flags_string = generate_flags_string.replace('"[', "[")
  530. generate_flags_string = generate_flags_string.replace(']"', "]")
  531. # 6. Replace the `=` with `:`
  532. generate_flags_string = generate_flags_string.replace("=", ":")
  533. try:
  534. processed_generate_flags = json.loads(generate_flags_string)
  535. except json.JSONDecodeError:
  536. raise ValueError(
  537. "Failed to convert `generate_flags` into a valid JSON object."
  538. "\n`generate_flags` = {generate_flags}"
  539. "\nConverted JSON string = {generate_flags_string}"
  540. )
  541. return processed_generate_flags
  542. def new_chat_history(system_prompt: str | None = None) -> list[dict]:
  543. """Returns a new chat conversation."""
  544. return [{"role": "system", "content": system_prompt}] if system_prompt else []
  545. def save_chat(filename: str, chat: list[dict], settings: dict) -> str:
  546. """Saves the chat history to a file."""
  547. os.makedirs(os.path.dirname(filename), exist_ok=True)
  548. with open(filename, "w") as f:
  549. json.dump({"settings": settings, "chat_history": chat}, f, indent=4)
  550. return os.path.abspath(filename)
  551. def get_username() -> str:
  552. """Returns the username of the current user."""
  553. if platform.system() == "Windows":
  554. return os.getlogin()
  555. else:
  556. return pwd.getpwuid(os.getuid()).pw_name
  557. if __name__ == "__main__":
  558. Chat(model_id="meta-llama/Llama-3.2-3b-Instruct")