charla 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
charla/__about__.py ADDED
@@ -0,0 +1,5 @@
1
+ # SPDX-FileCopyrightText: 2024-present Ramiro Gómez <code@ramiro.org>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ __version__ = "1.0.0"
5
+ __name__ = "charla"
charla/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2024-present Ramiro Gómez <code@ramiro.org>
2
+ #
3
+ # SPDX-License-Identifier: MIT
charla/chat.py ADDED
@@ -0,0 +1,74 @@
1
+ from datetime import datetime
2
+ from operator import itemgetter
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from prompt_toolkit import PromptSession
7
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
8
+ from prompt_toolkit.history import FileHistory
9
+ from prompt_toolkit.key_binding import KeyBindings
10
+
11
+ import re
12
+
13
+ import ollama
14
+
15
+
16
+ # UI text
17
+ t_prompt = 'PROMPT: '
18
+ t_prompt_ml = 'PROMPT \N{LATIN SUBSCRIPT SMALL LETTER M}\N{LATIN SUBSCRIPT SMALL LETTER L}: '
19
+ t_response = 'RESPONSE:'
20
+ t_help = '''
21
+ Press CTRL-C or CTRL-D to exit chat.
22
+ Press ALT+M to switch between single and multi line mode.
23
+ Press ALT+RETURN to send prompt in multi line mode.
24
+ Press ↑ and ↓ to navigate previously entered prompts.
25
+ Press → to complete an auto suggested prompt.
26
+ '''
27
+
28
+ def available_models() -> None | list[str]:
29
+ """Return available models sorted by size."""
30
+
31
+ if model_list := ollama.list()['models']:
32
+ return [m for m in sorted(model_list, key=itemgetter('size'))]
33
+
34
+
35
+ def generate(model: str, prompt: str, context: list, output: list) -> str | Any:
36
+ stream = ollama.generate(model=model, prompt=prompt, context=context, stream=True)
37
+
38
+ text = ''
39
+ for chunk in stream:
40
+ if not chunk['done']:
41
+ text += chunk['response']
42
+ print(chunk['response'], end='', flush=True)
43
+
44
+ output.append(f'{t_response}\n\n{text}\n')
45
+ return chunk['context']
46
+
47
+
48
+ def prompt_session(history: Path) -> PromptSession:
49
+ session = PromptSession(message=t_prompt,
50
+ history=FileHistory(history),
51
+ auto_suggest=AutoSuggestFromHistory())
52
+
53
+ print(t_help)
54
+
55
+ bindings = KeyBindings()
56
+
57
+ @bindings.add('escape', 'm')
58
+ def switch_multiline(event):
59
+ session.multiline = not session.multiline
60
+ session.message = t_prompt if session.multiline is False else t_prompt_ml
61
+
62
+ session.key_bindings = bindings
63
+
64
+ return session
65
+
66
+
67
+ def save(chats_path: Path, output: list[str], model_name: str) -> None:
68
+ if len(output) > 1:
69
+ now = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
70
+ slug = re.sub(r'\W', '-', model_name)
71
+ file = chats_path / f'{now}-{slug}.md'
72
+
73
+ print(f'Saving chat in: {file}')
74
+ file.write_text('\n'.join(output))
charla/cli.py ADDED
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env python
2
+ import argparse
3
+ import sys
4
+
5
+ from pathlib import Path
6
+
7
+ from prompt_toolkit import HTML, print_formatted_text as print_fmt
8
+
9
+ from charla import chat, config
10
+
11
+
12
+ def main():
13
+ if (models := chat.available_models()) is None:
14
+ sys.exit('No language models available.')
15
+ model_names = [m['name'] for m in models]
16
+
17
+ parser = argparse.ArgumentParser(description='Chat with local language models.')
18
+ parser.add_argument('--model', '-m',
19
+ choices=model_names,
20
+ help='Language model to chat with.')
21
+ argv = parser.parse_args()
22
+
23
+ # Determine model
24
+ if (model := config.setting('model', argv.model)) == '':
25
+ model = model_names[0]
26
+
27
+ context = [] # Store conversation history to make the model context aware
28
+ output = [f'# Chat with: {model}\n'] # List to store output text
29
+
30
+ history = Path(config.setting('prompt_history'))
31
+ history.parent.mkdir(exist_ok=True, parents=True)
32
+ session = chat.prompt_session(history)
33
+
34
+ print_fmt('Chat with:', HTML(f'<ansigreen>{model}</ansigreen>'), '\n')
35
+
36
+ while True:
37
+ try:
38
+ user_input = session.prompt()
39
+ if not user_input:
40
+ continue
41
+
42
+ output.append(f'{chat.t_prompt}{user_input}\n')
43
+ print(f'\n{chat.t_response}\n')
44
+ context = chat.generate(model, user_input, context, output)
45
+ print('\n')
46
+ # Exit program on CTRL-C and CTRL-D
47
+ except (KeyboardInterrupt, EOFError):
48
+ break
49
+
50
+ chats_path = Path(config.setting('chats_path'))
51
+ chats_path.mkdir(exist_ok=True, parents=True)
52
+ chat.save(chats_path, output, model)
53
+
54
+ print_fmt(HTML('<b>Exiting program.</b>'))
55
+ sys.exit()
56
+
57
+
58
+ if __name__ == '__main__':
59
+ main()
charla/config.py ADDED
@@ -0,0 +1,17 @@
1
+ from platformdirs import user_cache_dir, user_documents_dir
2
+
3
+ from charla import __about__
4
+
5
+
6
+ name = __about__.__name__
7
+
8
+ default_settings = {
9
+ 'model': '',
10
+ 'chats_path': user_documents_dir() + f'/{name}/chats',
11
+ 'prompt_history': user_cache_dir(appname=name) + '/prompt-history.txt'
12
+ }
13
+
14
+
15
+ def setting(key: str, value: str = None) -> str:
16
+ return value if value else default_settings.get(key)
17
+
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.3
2
+ Name: charla
3
+ Version: 1.0.0
4
+ Summary: A terminal based chat application that works with local language models.
5
+ Project-URL: Documentation, https://github.com/yaph/charla#readme
6
+ Project-URL: Issues, https://github.com/yaph/charla/issues
7
+ Project-URL: Source, https://github.com/yaph/charla
8
+ Author-email: Ramiro Gómez <code@ramiro.org>
9
+ License-Expression: MIT
10
+ License-File: LICENSE.txt
11
+ Keywords: chat-client,chatbot,cli,llm,ollama,terminal
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: Implementation :: CPython
18
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: ollama
21
+ Requires-Dist: platformdirs
22
+ Requires-Dist: prompt-toolkit
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Charla: Terminal-Based Chat Application with Ollama Backend Integration
26
+
27
+ [![PyPI - Version](https://img.shields.io/pypi/v/charla.svg)](https://pypi.org/project/charla)
28
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/charla.svg)](https://pypi.org/project/charla)
29
+
30
+ **Charla** is a terminal based chat application that integrates with [Ollama](https://ollama.com/), a backend designed to serve language models. To use Charla, ensure that the `ollama` server is running and at least one language model is installed.
31
+
32
+ ## Installation
33
+
34
+ Install Charla using `pipx`:
35
+
36
+ ```console
37
+ pipx install charla
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ Launch the chat console by typing `charla` in your terminal, or view all available command line options with `charla -h`.
43
+
44
+ ## Features
45
+
46
+ * Terminal-based chat system that supports context aware conversations using local language models.
47
+ * Chat sessions are saved as markdown files in the user's documents directory when ending a chat.
48
+ * Prompt history is saved and previously entered prompts are auto-suggested.
49
+ * Mode switching between single-line and multi-line input without interruption to your chat session.
50
+
51
+ ## Development
52
+
53
+ Run the command-line interface directly from the project source without installing the package:
54
+
55
+ ```console
56
+ python -m charla.cli
57
+ ```
58
+
59
+ ### ollama API
60
+
61
+ Installed models:
62
+
63
+ ```console
64
+ curl http://localhost:11434/api/tags
65
+ ```
66
+
67
+ Model info:
68
+
69
+ ```console
70
+ curl http://localhost:11434/api/show -d '{"name": "phi3"}'
71
+ ```
72
+
73
+ ## License
74
+
75
+ Charla is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
@@ -0,0 +1,10 @@
1
+ charla/__about__.py,sha256=Blg6iKaeiQFme-iczvLMNAHKz6B_cwZ5xlz3GGaq-aA,146
2
+ charla/__init__.py,sha256=Hi18ekz_kKsIjEqVYaHHs-MVJlgZZ0iyoNBNbrYKseU,104
3
+ charla/chat.py,sha256=g89kxW_ORiOn64wN3-DmVCOuvt7OoTKOqtVuRnbikJs,2261
4
+ charla/cli.py,sha256=W-wpe9uICm2_2M_cr0gLap1w43IpFM54UUY_2Bz1GX0,1777
5
+ charla/config.py,sha256=1vKo-piBOqmpi7gOV3Hxdy4LbK6yZFRcPBpZ-A-IJFE,402
6
+ charla-1.0.0.dist-info/METADATA,sha256=N90mp3D3A3EyeWCH3X5nAL3syr91z-HtCQMFRKq90G8,2556
7
+ charla-1.0.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
8
+ charla-1.0.0.dist-info/entry_points.txt,sha256=tiU6hih4woARmY1PQ__iV2zJMXUCASiZv3UUZyjzhd0,43
9
+ charla-1.0.0.dist-info/licenses/LICENSE.txt,sha256=xHAsOfDjwvLq-EgPUtcbXVleLyzpP-CoWJtpff97lcE,1096
10
+ charla-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ charla = charla.cli:main
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present Ramiro Gómez <code@ramiro.org>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.