lollms-client 0.32.1__py3-none-any.whl → 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.
Potentially problematic release.
This version of lollms-client might be problematic. Click here for more details.
- lollms_client/__init__.py +1 -1
- lollms_client/llm_bindings/azure_openai/__init__.py +6 -10
- lollms_client/llm_bindings/claude/__init__.py +4 -7
- lollms_client/llm_bindings/gemini/__init__.py +3 -7
- lollms_client/llm_bindings/grok/__init__.py +3 -7
- lollms_client/llm_bindings/groq/__init__.py +4 -7
- lollms_client/llm_bindings/hugging_face_inference_api/__init__.py +4 -6
- lollms_client/llm_bindings/litellm/__init__.py +15 -6
- lollms_client/llm_bindings/llamacpp/__init__.py +214 -388
- lollms_client/llm_bindings/lollms/__init__.py +24 -14
- lollms_client/llm_bindings/lollms_webui/__init__.py +6 -12
- lollms_client/llm_bindings/mistral/__init__.py +58 -29
- lollms_client/llm_bindings/ollama/__init__.py +6 -11
- lollms_client/llm_bindings/open_router/__init__.py +45 -14
- lollms_client/llm_bindings/openai/__init__.py +7 -14
- lollms_client/llm_bindings/openllm/__init__.py +12 -12
- lollms_client/llm_bindings/pythonllamacpp/__init__.py +1 -1
- lollms_client/llm_bindings/tensor_rt/__init__.py +8 -13
- lollms_client/llm_bindings/transformers/__init__.py +14 -6
- lollms_client/llm_bindings/vllm/__init__.py +16 -12
- lollms_client/lollms_core.py +296 -487
- lollms_client/lollms_discussion.py +436 -78
- lollms_client/lollms_llm_binding.py +223 -11
- lollms_client/lollms_mcp_binding.py +33 -2
- lollms_client/mcp_bindings/local_mcp/__init__.py +3 -2
- lollms_client/mcp_bindings/remote_mcp/__init__.py +6 -5
- lollms_client/mcp_bindings/standard_mcp/__init__.py +3 -5
- lollms_client/stt_bindings/lollms/__init__.py +6 -8
- lollms_client/stt_bindings/whisper/__init__.py +2 -4
- lollms_client/stt_bindings/whispercpp/__init__.py +15 -16
- lollms_client/tti_bindings/dalle/__init__.py +29 -28
- lollms_client/tti_bindings/diffusers/__init__.py +25 -21
- lollms_client/tti_bindings/gemini/__init__.py +215 -0
- lollms_client/tti_bindings/lollms/__init__.py +8 -9
- lollms_client-1.0.0.dist-info/METADATA +1214 -0
- lollms_client-1.0.0.dist-info/RECORD +69 -0
- {lollms_client-0.32.1.dist-info → lollms_client-1.0.0.dist-info}/top_level.txt +0 -2
- examples/article_summary/article_summary.py +0 -58
- examples/console_discussion/console_app.py +0 -266
- examples/console_discussion.py +0 -448
- examples/deep_analyze/deep_analyse.py +0 -30
- examples/deep_analyze/deep_analyze_multiple_files.py +0 -32
- examples/function_calling_with_local_custom_mcp.py +0 -250
- examples/generate_a_benchmark_for_safe_store.py +0 -89
- examples/generate_and_speak/generate_and_speak.py +0 -251
- examples/generate_game_sfx/generate_game_fx.py +0 -240
- examples/generate_text_with_multihop_rag_example.py +0 -210
- examples/gradio_chat_app.py +0 -228
- examples/gradio_lollms_chat.py +0 -259
- examples/internet_search_with_rag.py +0 -226
- examples/lollms_chat/calculator.py +0 -59
- examples/lollms_chat/derivative.py +0 -48
- examples/lollms_chat/test_openai_compatible_with_lollms_chat.py +0 -12
- examples/lollms_discussions_test.py +0 -155
- examples/mcp_examples/external_mcp.py +0 -267
- examples/mcp_examples/local_mcp.py +0 -171
- examples/mcp_examples/openai_mcp.py +0 -203
- examples/mcp_examples/run_remote_mcp_example_v2.py +0 -290
- examples/mcp_examples/run_standard_mcp_example.py +0 -204
- examples/simple_text_gen_test.py +0 -173
- examples/simple_text_gen_with_image_test.py +0 -178
- examples/test_local_models/local_chat.py +0 -9
- examples/text_2_audio.py +0 -77
- examples/text_2_image.py +0 -144
- examples/text_2_image_diffusers.py +0 -274
- examples/text_and_image_2_audio.py +0 -59
- examples/text_gen.py +0 -30
- examples/text_gen_system_prompt.py +0 -29
- lollms_client-0.32.1.dist-info/METADATA +0 -854
- lollms_client-0.32.1.dist-info/RECORD +0 -101
- test/test_lollms_discussion.py +0 -368
- {lollms_client-0.32.1.dist-info → lollms_client-1.0.0.dist-info}/WHEEL +0 -0
- {lollms_client-0.32.1.dist-info → lollms_client-1.0.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,854 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: lollms_client
|
|
3
|
-
Version: 0.32.1
|
|
4
|
-
Summary: A client library for LoLLMs generate endpoint
|
|
5
|
-
Author-email: ParisNeo <parisneoai@gmail.com>
|
|
6
|
-
License: Apache Software License
|
|
7
|
-
Project-URL: Homepage, https://github.com/ParisNeo/lollms_client
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
-
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
-
Classifier: Operating System :: OS Independent
|
|
16
|
-
Classifier: Intended Audience :: Developers
|
|
17
|
-
Classifier: Intended Audience :: Science/Research
|
|
18
|
-
Requires-Python: >=3.7
|
|
19
|
-
Description-Content-Type: text/markdown
|
|
20
|
-
License-File: LICENSE
|
|
21
|
-
Requires-Dist: requests
|
|
22
|
-
Requires-Dist: ascii-colors
|
|
23
|
-
Requires-Dist: pipmaster
|
|
24
|
-
Requires-Dist: pyyaml
|
|
25
|
-
Requires-Dist: tiktoken
|
|
26
|
-
Requires-Dist: pydantic
|
|
27
|
-
Requires-Dist: numpy
|
|
28
|
-
Requires-Dist: pillow
|
|
29
|
-
Requires-Dist: sqlalchemy
|
|
30
|
-
Dynamic: license-file
|
|
31
|
-
|
|
32
|
-
# LoLLMs Client Library
|
|
33
|
-
|
|
34
|
-
[](https://opensource.org/licenses/Apache-2.0)
|
|
35
|
-
[](https://badge.fury.io/py/lollms_client)
|
|
36
|
-
[](https://pypi.org/project/lollms_client/)
|
|
37
|
-
[](https://pepy.tech/project/lollms-client)
|
|
38
|
-
[](DOC_USE.md)
|
|
39
|
-
[](DOC_DEV.md)
|
|
40
|
-
[](https://github.com/ParisNeo/lollms_client/stargazers/)
|
|
41
|
-
[](https://github.com/ParisNeo/lollms_client/issues)
|
|
42
|
-
|
|
43
|
-
**`lollms_client`** is a powerful and flexible Python library designed to simplify interactions with the **LoLLMs (Lord of Large Language Models)** ecosystem and various other Large Language Model (LLM) backends. It provides a unified API for text generation, multimodal operations (text-to-image, text-to-speech, etc.), and robust function calling through the Model Context Protocol (MCP).
|
|
44
|
-
|
|
45
|
-
Whether you're connecting to a remote LoLLMs server, an Ollama instance, the OpenAI API, or running models locally using GGUF (via `llama-cpp-python` or a managed `llama.cpp` server), Hugging Face Transformers, or vLLM, `lollms-client` offers a consistent and developer-friendly experience.
|
|
46
|
-
|
|
47
|
-
## Key Features
|
|
48
|
-
|
|
49
|
-
* 🔌 **Versatile Binding System:** Seamlessly switch between different LLM backends (LoLLMs, Ollama, OpenAI, Llama.cpp, Transformers, vLLM, OpenLLM) without major code changes.
|
|
50
|
-
* 🗣️ **Multimodal Support:** Interact with models capable of processing images and generate various outputs like speech (TTS) and images (TTI).
|
|
51
|
-
* 🖼️ **Selective Image Activation:** Control which images in a message are active and sent to the model, allowing for fine-grained multimodal context management without deleting the original data.
|
|
52
|
-
* 🤖 **Function Calling with MCP:** Empowers LLMs to use external tools and functions through the Model Context Protocol (MCP), with built-in support for local Python tool execution via `local_mcp` binding and its default tools (file I/O, internet search, Python interpreter, image generation).
|
|
53
|
-
* 🎭 **Personalities as Agents:** Personalities can now define their own set of required tools (MCPs) and have access to static or dynamic knowledge bases (`data_source`), turning them into self-contained, ready-to-use agents.
|
|
54
|
-
* 🚀 **Streaming & Callbacks:** Efficiently handle real-time text generation with customizable callback functions, including during MCP interactions.
|
|
55
|
-
* 📑 **Sequential Summarization:** A `summarize` method to process and summarize texts that exceed the model's context window.
|
|
56
|
-
* 📝 **Advanced Structured Content Generation:** Reliably generate structured JSON output from natural language prompts using the `generate_structured_content` helper method.
|
|
57
|
-
* 💬 **Advanced Discussion Management:** Robustly manage conversation histories with `LollmsDiscussion`, featuring branching, context exporting, and automatic pruning.
|
|
58
|
-
* 🧠 **Persistent Memory & Data Zones:** `LollmsDiscussion` now supports multiple, distinct data zones (`user_data_zone`, `discussion_data_zone`, `personality_data_zone`) and a long-term `memory` field. This allows for sophisticated context layering and state management.
|
|
59
|
-
* ✍️ **Automatic Memorization:** A new `memorize()` method allows the AI to analyze a conversation and extract key facts, appending them to the long-term `memory` for recall in future sessions.
|
|
60
|
-
* 📊 **Detailed Context Analysis:** The `get_context_status()` method now provides a rich, detailed breakdown of the prompt context, showing the content and token count for each individual component (system prompt, data zones, message history).
|
|
61
|
-
* ⚙️ **Configuration Management:** Flexible ways to configure bindings and generation parameters.
|
|
62
|
-
* 🧩 **Extensible:** Designed to easily incorporate new LLM backends and modality services, including custom MCP toolsets.
|
|
63
|
-
* 📝 **High-Level Operations:** Includes convenience methods for complex tasks like sequential summarization and deep text analysis directly within `LollmsClient`.
|
|
64
|
-
|
|
65
|
-
## Installation
|
|
66
|
-
|
|
67
|
-
You can install `lollms_client` directly from PyPI:
|
|
68
|
-
|
|
69
|
-
```bash
|
|
70
|
-
pip install lollms-client
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
This will install the core library. Some bindings may require additional dependencies (e.g., `llama-cpp-python`, `torch`, `transformers`, `ollama`, `vllm`). The library attempts to manage these using `pipmaster`, but for complex dependencies (especially those requiring compilation like `llama-cpp-python` with GPU support), manual installation might be preferred.
|
|
74
|
-
|
|
75
|
-
## Quick Start
|
|
76
|
-
|
|
77
|
-
Here's a very basic example of how to use `LollmsClient` to generate text with a LoLLMs server (ensure one is running at `http://localhost:9600`):
|
|
78
|
-
|
|
79
|
-
```python
|
|
80
|
-
from lollms_client import LollmsClient, MSG_TYPE
|
|
81
|
-
from ascii_colors import ASCIIColors
|
|
82
|
-
|
|
83
|
-
# Callback for streaming output
|
|
84
|
-
def simple_streaming_callback(chunk: str, msg_type: MSG_TYPE, params=None, metadata=None) -> bool:
|
|
85
|
-
if msg_type == MSG_TYPE.MSG_TYPE_CHUNK:
|
|
86
|
-
print(chunk, end="", flush=True)
|
|
87
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_EXCEPTION:
|
|
88
|
-
ASCIIColors.error(f"\nStreaming Error: {chunk}")
|
|
89
|
-
return True # True to continue streaming
|
|
90
|
-
|
|
91
|
-
try:
|
|
92
|
-
# Initialize client to connect to a LoLLMs server
|
|
93
|
-
# For other backends, change 'binding_name' and provide necessary parameters.
|
|
94
|
-
# See DOC_USE.md for detailed initialization examples.
|
|
95
|
-
lc = LollmsClient(
|
|
96
|
-
binding_name="lollms",
|
|
97
|
-
host_address="http://localhost:9600"
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
prompt = "Tell me a fun fact about space."
|
|
101
|
-
ASCIIColors.yellow(f"Prompt: {prompt}")
|
|
102
|
-
|
|
103
|
-
# Generate text with streaming
|
|
104
|
-
ASCIIColors.green("Streaming Response:")
|
|
105
|
-
response_text = lc.generate_text(
|
|
106
|
-
prompt,
|
|
107
|
-
n_predict=100,
|
|
108
|
-
stream=True,
|
|
109
|
-
streaming_callback=simple_streaming_callback
|
|
110
|
-
)
|
|
111
|
-
print("\n--- End of Stream ---")
|
|
112
|
-
|
|
113
|
-
# The 'response_text' variable will contain the full concatenated text
|
|
114
|
-
# if streaming_callback returns True throughout.
|
|
115
|
-
if isinstance(response_text, str):
|
|
116
|
-
ASCIIColors.cyan(f"\nFull streamed text collected: {response_text[:100]}...")
|
|
117
|
-
elif isinstance(response_text, dict) and "error" in response_text:
|
|
118
|
-
ASCIIColors.error(f"Error during generation: {response_text['error']}")
|
|
119
|
-
|
|
120
|
-
except ValueError as ve:
|
|
121
|
-
ASCIIColors.error(f"Initialization Error: {ve}")
|
|
122
|
-
ASCIIColors.info("Ensure a LoLLMs server is running or configure another binding.")
|
|
123
|
-
except ConnectionRefusedError:
|
|
124
|
-
ASCIIColors.error("Connection refused. Is the LoLLMs server running at http://localhost:9600?")
|
|
125
|
-
except Exception as e:
|
|
126
|
-
ASCIIColors.error(f"An unexpected error occurred: {e}")
|
|
127
|
-
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
### Advanced Structured Content Generation
|
|
131
|
-
|
|
132
|
-
The `generate_structured_content` method is a powerful utility for forcing an LLM's output into a specific JSON format. It's ideal for extracting information, getting consistent tool parameters, or any task requiring reliable, machine-readable output.
|
|
133
|
-
|
|
134
|
-
```python
|
|
135
|
-
from lollms_client import LollmsClient
|
|
136
|
-
import json
|
|
137
|
-
|
|
138
|
-
lc = LollmsClient(binding_name="ollama", model_name="llama3")
|
|
139
|
-
|
|
140
|
-
text_block = "John Doe is a 34-year-old software engineer from New York. He loves hiking and Python programming."
|
|
141
|
-
|
|
142
|
-
# Define the exact JSON structure you want
|
|
143
|
-
output_template = {
|
|
144
|
-
"full_name": "string",
|
|
145
|
-
"age": "integer",
|
|
146
|
-
"profession": "string",
|
|
147
|
-
"city": "string",
|
|
148
|
-
"hobbies": ["list", "of", "strings"]
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
# Generate the structured data
|
|
152
|
-
extracted_data = lc.generate_structured_content(
|
|
153
|
-
prompt=f"Extract the relevant information from the following text:\n\n{text_block}",
|
|
154
|
-
output_format=output_template
|
|
155
|
-
)
|
|
156
|
-
|
|
157
|
-
if extracted_data:
|
|
158
|
-
print(json.dumps(extracted_data, indent=2))
|
|
159
|
-
# Expected output:
|
|
160
|
-
# {
|
|
161
|
-
# "full_name": "John Doe",
|
|
162
|
-
# "age": 34,
|
|
163
|
-
# "profession": "software engineer",
|
|
164
|
-
# "city": "New York",
|
|
165
|
-
# "hobbies": ["hiking", "Python programming"]
|
|
166
|
-
# }
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
### Putting It All Together: An Advanced Agentic Example
|
|
170
|
-
|
|
171
|
-
Let's create a **Python Coder Agent**. This agent will use a set of coding rules from a local file as its knowledge base and will be equipped with a tool to execute the code it writes. This demonstrates the synergy between `LollmsPersonality` (with `data_source` and `active_mcps`), `LollmsDiscussion`, and the MCP system.
|
|
172
|
-
|
|
173
|
-
#### Step 1: Create the Knowledge Base (`coding_rules.txt`)
|
|
174
|
-
|
|
175
|
-
Create a simple text file with the rules our agent must follow.
|
|
176
|
-
|
|
177
|
-
```text
|
|
178
|
-
# File: coding_rules.txt
|
|
179
|
-
|
|
180
|
-
1. All Python functions must include a Google-style docstring.
|
|
181
|
-
2. Use type hints for all function parameters and return values.
|
|
182
|
-
3. The main execution block should be protected by `if __name__ == "__main__":`.
|
|
183
|
-
4. After defining a function, add a simple example of its usage inside the main block.
|
|
184
|
-
5. Print the output of the example usage to the console.
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
#### Step 2: The Main Script (`agent_example.py`)
|
|
188
|
-
|
|
189
|
-
This script will define the personality, initialize the client, and run the agent.
|
|
190
|
-
|
|
191
|
-
```python
|
|
192
|
-
from pathlib import Path
|
|
193
|
-
from lollms_client import LollmsClient, LollmsPersonality, LollmsDiscussion, MSG_TYPE, trace_exception
|
|
194
|
-
from ascii_colors import ASCIIColors
|
|
195
|
-
import json
|
|
196
|
-
|
|
197
|
-
# A detailed callback to visualize the agent's process
|
|
198
|
-
def agent_callback(chunk: str, msg_type: MSG_TYPE, params: dict = None, **kwargs) -> bool:
|
|
199
|
-
if not params: params = {}
|
|
200
|
-
|
|
201
|
-
if msg_type == MSG_TYPE.MSG_TYPE_STEP:
|
|
202
|
-
ASCIIColors.yellow(f"\n>> Agent Step: {chunk}")
|
|
203
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_STEP_START:
|
|
204
|
-
ASCIIColors.yellow(f"\n>> Agent Step Start: {chunk}")
|
|
205
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_STEP_END:
|
|
206
|
-
result = params.get('result', '')
|
|
207
|
-
ASCIIColors.green(f"<< Agent Step End: {chunk} -> Result: {json.dumps(result)[:150]}...")
|
|
208
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_THOUGHT_CONTENT:
|
|
209
|
-
ASCIIColors.magenta(f"🤔 Agent Thought: {chunk}")
|
|
210
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_TOOL_CALL:
|
|
211
|
-
ASCIIColors.blue(f"🛠️ Agent Action: {chunk}")
|
|
212
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_OBSERVATION:
|
|
213
|
-
ASCIIColors.cyan(f"👀 Agent Observation: {chunk}")
|
|
214
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_CHUNK:
|
|
215
|
-
print(chunk, end="", flush=True) # Final answer stream
|
|
216
|
-
return True
|
|
217
|
-
|
|
218
|
-
try:
|
|
219
|
-
# --- 1. Load the knowledge base from the file ---
|
|
220
|
-
rules_path = Path("coding_rules.txt")
|
|
221
|
-
if not rules_path.exists():
|
|
222
|
-
raise FileNotFoundError("Please create the 'coding_rules.txt' file.")
|
|
223
|
-
coding_rules = rules_path.read_text()
|
|
224
|
-
|
|
225
|
-
# --- 2. Define the Coder Agent Personality ---
|
|
226
|
-
coder_personality = LollmsPersonality(
|
|
227
|
-
name="Python Coder Agent",
|
|
228
|
-
author="lollms-client",
|
|
229
|
-
category="Coding",
|
|
230
|
-
description="An agent that writes and executes Python code according to specific rules.",
|
|
231
|
-
system_prompt=(
|
|
232
|
-
"You are an expert Python programmer. Your task is to write clean, executable Python code based on the user's request. "
|
|
233
|
-
"You MUST strictly follow all rules provided in the 'Personality Static Data' section. "
|
|
234
|
-
"First, think about the plan. Then, use the `python_code_interpreter` tool to write and execute the code. "
|
|
235
|
-
"Finally, present the code and its output to the user."
|
|
236
|
-
),
|
|
237
|
-
# A) Attach the static knowledge base
|
|
238
|
-
data_source=coding_rules,
|
|
239
|
-
# B) Equip the agent with a code execution tool
|
|
240
|
-
active_mcps=["python_code_interpreter"]
|
|
241
|
-
)
|
|
242
|
-
|
|
243
|
-
# --- 3. Initialize the Client and Discussion ---
|
|
244
|
-
lc = LollmsClient(
|
|
245
|
-
binding_name="ollama", # Or any capable model binding
|
|
246
|
-
model_name="codellama", # A code-specialized model is recommended
|
|
247
|
-
mcp_binding_name="local_mcp" # Enable the local tool execution engine
|
|
248
|
-
)
|
|
249
|
-
discussion = LollmsDiscussion.create_new(lollms_client=lc)
|
|
250
|
-
|
|
251
|
-
# --- 4. The User's Request ---
|
|
252
|
-
user_prompt = "Write a Python function that takes two numbers and returns their sum."
|
|
253
|
-
|
|
254
|
-
ASCIIColors.yellow(f"User Prompt: {user_prompt}")
|
|
255
|
-
print("\n" + "="*50 + "\nAgent is now running...\n" + "="*50)
|
|
256
|
-
|
|
257
|
-
# --- 5. Run the Agentic Chat Turn ---
|
|
258
|
-
response = discussion.chat(
|
|
259
|
-
user_message=user_prompt,
|
|
260
|
-
personality=coder_personality,
|
|
261
|
-
streaming_callback=agent_callback
|
|
262
|
-
)
|
|
263
|
-
|
|
264
|
-
print("\n\n" + "="*50 + "\nAgent finished.\n" + "="*50)
|
|
265
|
-
|
|
266
|
-
# --- 6. Inspect the results ---
|
|
267
|
-
ai_message = response['ai_message']
|
|
268
|
-
ASCIIColors.green("\n--- Final Answer from Agent ---")
|
|
269
|
-
print(ai_message.content)
|
|
270
|
-
|
|
271
|
-
ASCIIColors.magenta("\n--- Tool Calls Made ---")
|
|
272
|
-
print(json.dumps(ai_message.metadata.get("tool_calls", []), indent=2))
|
|
273
|
-
|
|
274
|
-
except Exception as e:
|
|
275
|
-
trace_exception(e)
|
|
276
|
-
|
|
277
|
-
```
|
|
278
|
-
|
|
279
|
-
#### Step 3: What Happens Under the Hood
|
|
280
|
-
|
|
281
|
-
When you run `agent_example.py`, a sophisticated process unfolds:
|
|
282
|
-
|
|
283
|
-
1. **Initialization:** The `LollmsDiscussion.chat()` method is called with the `coder_personality`.
|
|
284
|
-
2. **Knowledge Injection:** The `chat` method sees that `personality.data_source` is a string. It automatically takes the content of `coding_rules.txt` and injects it into the discussion's data zones.
|
|
285
|
-
3. **Tool Activation:** The method also sees `personality.active_mcps`. It enables the `python_code_interpreter` tool for this turn.
|
|
286
|
-
4. **Context Assembly:** The `LollmsClient` assembles a rich prompt for the LLM that includes:
|
|
287
|
-
* The personality's `system_prompt`.
|
|
288
|
-
* The content of `coding_rules.txt` (from the data zones).
|
|
289
|
-
* The list of available tools (including `python_code_interpreter`).
|
|
290
|
-
* The user's request ("Write a function...").
|
|
291
|
-
5. **Reason and Act:** The LLM, now fully briefed, reasons that it needs to use the `python_code_interpreter` tool. It formulates the Python code *according to the rules it was given*.
|
|
292
|
-
6. **Tool Execution:** The `local_mcp` binding receives the code and executes it in a secure local environment. It captures any output (`stdout`, `stderr`) and results.
|
|
293
|
-
7. **Observation:** The execution results are sent back to the LLM as an "observation."
|
|
294
|
-
8. **Final Synthesis:** The LLM now has the user's request, the rules, the code it wrote, and the code's output. It synthesizes all of this into a final, comprehensive answer for the user.
|
|
295
|
-
|
|
296
|
-
This example showcases how `lollms-client` allows you to build powerful, knowledgeable, and capable agents by simply composing personalities with data and tools.
|
|
297
|
-
|
|
298
|
-
### Building Stateful Agents with Memory and Data Zones
|
|
299
|
-
|
|
300
|
-
The `LollmsDiscussion` class provides a sophisticated system for creating stateful agents that can remember information across conversations. This is achieved through a layered system of "context zones" that are automatically combined into the AI's system prompt.
|
|
301
|
-
|
|
302
|
-
#### Understanding the Context Zones
|
|
303
|
-
|
|
304
|
-
The AI's context is more than just chat history. It's built from several distinct components, each with a specific purpose:
|
|
305
|
-
|
|
306
|
-
* **`system_prompt`**: The foundational layer defining the AI's core identity, persona, and primary instructions.
|
|
307
|
-
* **`memory`**: The AI's long-term, persistent memory. It stores key facts about the user or topics, built up over time using the `memorize()` method.
|
|
308
|
-
* **`user_data_zone`**: Holds session-specific information about the user's current state or goals (e.g., "User is currently working on 'file.py'").
|
|
309
|
-
* **`discussion_data_zone`**: Contains state or meta-information about the current conversational task (e.g., "Step 1 of the plan is complete").
|
|
310
|
-
* **`personality_data_zone`**: A knowledge base or set of rules automatically injected from a `LollmsPersonality`'s `data_source`.
|
|
311
|
-
* **`pruning_summary`**: An automatic, AI-generated summary of the oldest messages in a very long chat, used to conserve tokens without losing the gist of the early conversation.
|
|
312
|
-
|
|
313
|
-
The `get_context_status()` method is your window into this system, showing you exactly how these zones are combined and how many tokens they consume.
|
|
314
|
-
|
|
315
|
-
Let's see this in action with a "Personal Assistant" agent that learns about the user over time.
|
|
316
|
-
|
|
317
|
-
```python
|
|
318
|
-
from lollms_client import LollmsClient, LollmsDataManager, LollmsDiscussion, MSG_TYPE
|
|
319
|
-
from ascii_colors import ASCIIColors
|
|
320
|
-
import json
|
|
321
|
-
|
|
322
|
-
# --- 1. Setup a persistent database for our discussion ---
|
|
323
|
-
db_manager = LollmsDataManager('sqlite:///my_assistant.db')
|
|
324
|
-
lc = LollmsClient(binding_name="ollama", model_name="llama3")
|
|
325
|
-
|
|
326
|
-
# Try to load an existing discussion or create a new one
|
|
327
|
-
discussion_id = "user_assistant_chat_1"
|
|
328
|
-
discussion = db_manager.get_discussion(lc, discussion_id)
|
|
329
|
-
if not discussion:
|
|
330
|
-
ASCIIColors.yellow("Creating a new discussion...")
|
|
331
|
-
discussion = LollmsDiscussion.create_new(
|
|
332
|
-
lollms_client=lc,
|
|
333
|
-
db_manager=db_manager,
|
|
334
|
-
id=discussion_id,
|
|
335
|
-
autosave=True # Important for persistence
|
|
336
|
-
)
|
|
337
|
-
# Let's preset some data in different zones
|
|
338
|
-
discussion.system_prompt = "You are a helpful Personal Assistant."
|
|
339
|
-
discussion.user_data_zone = "User's Name: Alex\nUser's Goal: Learn about AI development."
|
|
340
|
-
discussion.commit()
|
|
341
|
-
else:
|
|
342
|
-
ASCIIColors.green("Loaded existing discussion.")
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
def run_chat_turn(prompt: str):
|
|
346
|
-
"""Helper function to run a single chat turn and print details."""
|
|
347
|
-
ASCIIColors.cyan(f"\n> User: {prompt}")
|
|
348
|
-
|
|
349
|
-
# --- A. Check context status BEFORE the turn using get_context_status() ---
|
|
350
|
-
ASCIIColors.magenta("\n--- Context Status (Before Generation) ---")
|
|
351
|
-
status = discussion.get_context_status()
|
|
352
|
-
print(f"Max Tokens: {status.get('max_tokens')}, Current Tokens: {status.get('current_tokens')}")
|
|
353
|
-
|
|
354
|
-
# Print the system context details
|
|
355
|
-
if 'system_context' in status['zones']:
|
|
356
|
-
sys_ctx = status['zones']['system_context']
|
|
357
|
-
print(f" - System Context Tokens: {sys_ctx['tokens']}")
|
|
358
|
-
# The 'breakdown' shows the individual zones that were combined
|
|
359
|
-
for name, content in sys_ctx.get('breakdown', {}).items():
|
|
360
|
-
print(f" -> Contains '{name}': {content.split(chr(10))[0]}...")
|
|
361
|
-
|
|
362
|
-
# Print the message history details
|
|
363
|
-
if 'message_history' in status['zones']:
|
|
364
|
-
msg_hist = status['zones']['message_history']
|
|
365
|
-
print(f" - Message History Tokens: {msg_hist['tokens']} ({msg_hist['message_count']} messages)")
|
|
366
|
-
|
|
367
|
-
print("------------------------------------------")
|
|
368
|
-
|
|
369
|
-
# --- B. Run the chat ---
|
|
370
|
-
ASCIIColors.green("\n< Assistant:")
|
|
371
|
-
response = discussion.chat(
|
|
372
|
-
user_message=prompt,
|
|
373
|
-
streaming_callback=lambda chunk, type, **k: print(chunk, end="", flush=True) if type==MSG_TYPE.MSG_TYPE_CHUNK else None
|
|
374
|
-
)
|
|
375
|
-
print() # Newline after stream
|
|
376
|
-
|
|
377
|
-
# --- C. Trigger memorization to update the 'memory' zone ---
|
|
378
|
-
ASCIIColors.yellow("\nTriggering memorization process...")
|
|
379
|
-
discussion.memorize()
|
|
380
|
-
discussion.commit() # Save the new memory to the DB
|
|
381
|
-
ASCIIColors.yellow("Memorization complete.")
|
|
382
|
-
|
|
383
|
-
# --- Run a few turns ---
|
|
384
|
-
run_chat_turn("Hi there! Can you recommend a good Python library for building web APIs?")
|
|
385
|
-
run_chat_turn("That sounds great. By the way, my favorite programming language is Rust, I find its safety features amazing.")
|
|
386
|
-
run_chat_turn("What was my favorite programming language again?")
|
|
387
|
-
|
|
388
|
-
# --- Final Inspection of Memory ---
|
|
389
|
-
ASCIIColors.magenta("\n--- Final Context Status ---")
|
|
390
|
-
status = discussion.get_context_status()
|
|
391
|
-
print(f"Max Tokens: {status.get('max_tokens')}, Current Tokens: {status.get('current_tokens')}")
|
|
392
|
-
if 'system_context' in status['zones']:
|
|
393
|
-
sys_ctx = status['zones']['system_context']
|
|
394
|
-
print(f" - System Context Tokens: {sys_ctx['tokens']}")
|
|
395
|
-
for name, content in sys_ctx.get('breakdown', {}).items():
|
|
396
|
-
# Print the full content of the memory zone to verify it was updated
|
|
397
|
-
if name == 'memory':
|
|
398
|
-
ASCIIColors.yellow(f" -> Full '{name}' content:\n{content}")
|
|
399
|
-
else:
|
|
400
|
-
print(f" -> Contains '{name}': {content.split(chr(10))[0]}...")
|
|
401
|
-
print("------------------------------------------")
|
|
402
|
-
|
|
403
|
-
```
|
|
404
|
-
|
|
405
|
-
#### How it Works:
|
|
406
|
-
|
|
407
|
-
1. **Persistence & Initialization:** The `LollmsDataManager` saves and loads the discussion. We initialize the `system_prompt` and `user_data_zone` to provide initial context.
|
|
408
|
-
2. **`get_context_status()`:** Before each generation, we call this method. The output shows a `system_context` block with a token count for all combined zones and a `breakdown` field that lets us see the content of each individual zone that contributed to it.
|
|
409
|
-
3. **`memorize()`:** After the user mentions their favorite language, `memorize()` is called. The LLM analyzes the last turn, identifies this new, important fact, and appends it to the `discussion.memory` zone.
|
|
410
|
-
4. **Recall:** In the final turn, when asked to recall the favorite language, the AI has access to the updated `memory` content within its system context and can correctly answer "Rust". This demonstrates true long-term, stateful memory.
|
|
411
|
-
|
|
412
|
-
### Managing Multimodal Context: Activating and Deactivating Images
|
|
413
|
-
|
|
414
|
-
When working with multimodal models, you can now control which images in a message are active and sent to the model. This is useful for focusing the AI's attention, saving tokens on expensive vision models, or allowing a user to correct which images are relevant.
|
|
415
|
-
|
|
416
|
-
This is managed at the `LollmsMessage` level using the `toggle_image_activation()` method.
|
|
417
|
-
|
|
418
|
-
```python
|
|
419
|
-
from lollms_client import LollmsClient, LollmsDiscussion, LollmsDataManager
|
|
420
|
-
from ascii_colors import ASCIIColors
|
|
421
|
-
import base64
|
|
422
|
-
from pathlib import Path
|
|
423
|
-
|
|
424
|
-
# Helper to create a dummy image b64 string
|
|
425
|
-
def create_dummy_image(text):
|
|
426
|
-
from PIL import Image, ImageDraw
|
|
427
|
-
img = Image.new('RGB', (100, 30), color = (73, 109, 137))
|
|
428
|
-
d = ImageDraw.Draw(img)
|
|
429
|
-
d.text((10,10), text, fill=(255,255,0))
|
|
430
|
-
buffer = Path("temp_img.png")
|
|
431
|
-
img.save(buffer, "PNG")
|
|
432
|
-
b64 = base64.b64encode(buffer.read_bytes()).decode('utf-8')
|
|
433
|
-
buffer.unlink()
|
|
434
|
-
return b64
|
|
435
|
-
|
|
436
|
-
# --- 1. Setup ---
|
|
437
|
-
lc = LollmsClient(binding_name="ollama", model_name="llava")
|
|
438
|
-
discussion = LollmsDiscussion.create_new(lollms_client=lc)
|
|
439
|
-
|
|
440
|
-
# --- 2. Add a message with multiple images ---
|
|
441
|
-
img1_b64 = create_dummy_image("Image 1")
|
|
442
|
-
img2_b64 = create_dummy_image("Image 2: Cat")
|
|
443
|
-
img3_b64 = create_dummy_image("Image 3")
|
|
444
|
-
|
|
445
|
-
discussion.add_message(
|
|
446
|
-
sender="user",
|
|
447
|
-
content="What is in the second image?",
|
|
448
|
-
images=[img1_b64, img2_b64, img3_b64]
|
|
449
|
-
)
|
|
450
|
-
user_message = discussion.get_messages()[-1]
|
|
451
|
-
|
|
452
|
-
# --- 3. Check the initial state ---
|
|
453
|
-
ASCIIColors.magenta("--- Initial State (All 3 Images Active) ---")
|
|
454
|
-
status_before = discussion.get_context_status()
|
|
455
|
-
print(f"Message History Text:\n{status_before['zones']['message_history']['content']}")
|
|
456
|
-
|
|
457
|
-
# --- 4. Deactivate irrelevant images ---
|
|
458
|
-
ASCIIColors.magenta("\n--- Deactivating images 1 and 3 ---")
|
|
459
|
-
user_message.toggle_image_activation(index=0, active=False) # Deactivate first image
|
|
460
|
-
user_message.toggle_image_activation(index=2, active=False) # Deactivate third image
|
|
461
|
-
|
|
462
|
-
# --- 5. Check the new state ---
|
|
463
|
-
ASCIIColors.magenta("\n--- New State (Only Image 2 is Active) ---")
|
|
464
|
-
status_after = discussion.get_context_status()
|
|
465
|
-
print(f"Message History Text:\n{status_after['zones']['message_history']['content']}")
|
|
466
|
-
|
|
467
|
-
ASCIIColors.green("\nNotice the message now says '(1 image(s) attached)' instead of 3.")
|
|
468
|
-
ASCIIColors.green("Only the active image will be sent to the multimodal LLM.")
|
|
469
|
-
```
|
|
470
|
-
|
|
471
|
-
## Documentation
|
|
472
|
-
|
|
473
|
-
For more in-depth information, please refer to:
|
|
474
|
-
|
|
475
|
-
* **[Usage Guide (DOC_USE.md)](DOC_USE.md):** Learn how to use `LollmsClient`, different bindings, modality features, function calling with MCP, and high-level operations.
|
|
476
|
-
* **[Developer Guide (DOC_DEV.md)](DOC_DEV.md):** Understand the architecture, how to create new bindings (LLM, modality, MCP), and contribute to the library.
|
|
477
|
-
|
|
478
|
-
## Core Concepts
|
|
479
|
-
|
|
480
|
-
```mermaid
|
|
481
|
-
graph LR
|
|
482
|
-
A[Your Application] --> LC[LollmsClient];
|
|
483
|
-
|
|
484
|
-
subgraph LollmsClient_Core
|
|
485
|
-
LC -- Manages --> LLB[LLM Binding];
|
|
486
|
-
LC -- Manages --> MCPB[MCP Binding];
|
|
487
|
-
LC -- Orchestrates --> MCP_Interaction[generate_with_mcp];
|
|
488
|
-
LC -- Provides --> HighLevelOps["High-Level Ops(summarize, deep_analyze etc.)"];
|
|
489
|
-
LC -- Provides Access To --> DM[DiscussionManager];
|
|
490
|
-
LC -- Provides Access To --> ModalityBindings[TTS, TTI, STT etc.];
|
|
491
|
-
end
|
|
492
|
-
|
|
493
|
-
subgraph LLM_Backends
|
|
494
|
-
LLB --> LollmsServer[LoLLMs Server];
|
|
495
|
-
LLB --> OllamaServer[Ollama];
|
|
496
|
-
LLB --> OpenAPIServer[OpenAI API];
|
|
497
|
-
LLB --> LocalGGUF["Local GGUF<br>(pythonllamacpp / llamacpp server)"];
|
|
498
|
-
LLB --> LocalHF["Local HuggingFace<br>(transformers / vLLM)"];
|
|
499
|
-
end
|
|
500
|
-
|
|
501
|
-
MCP_Interaction --> MCPB;
|
|
502
|
-
MCPB --> LocalTools["Local Python Tools<br>(via local_mcp)"];
|
|
503
|
-
MCPB --> RemoteTools["Remote MCP Tool Servers<br>(Future Potential)"];
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
ModalityBindings --> ModalityServices["Modality Services<br>(e.g., LoLLMs Server TTS/TTI, local Bark/XTTS)"];
|
|
507
|
-
```
|
|
508
|
-
|
|
509
|
-
* **`LollmsClient`**: The central class for all interactions. It holds the currently active LLM binding, an optional MCP binding, and provides access to modality bindings and high-level operations.
|
|
510
|
-
* **LLM Bindings**: These are plugins that allow `LollmsClient` to communicate with different LLM backends. You choose a binding (e.g., `"ollama"`, `"lollms"`, `"pythonllamacpp"`) when you initialize `LollmsClient`.
|
|
511
|
-
* **🔧 MCP Bindings**: Enable tool use and function calling. `lollms-client` includes `local_mcp` for executing Python tools. It discovers tools from a specified folder (or uses its default set), each defined by a `.py` script and a `.mcp.json` metadata file.
|
|
512
|
-
* **Modality Bindings**: Similar to LLM bindings, but for services like Text-to-Speech (`tts`), Text-to-Image (`tti`), etc.
|
|
513
|
-
* **High-Level Operations**: Methods directly on `LollmsClient` (e.g., `sequential_summarize`, `summarize`, `deep_analyze`, `generate_code`, `yes_no`) for performing complex, multi-step AI tasks.
|
|
514
|
-
* **`LollmsDiscussion`**: Helps manage and format conversation histories. Now includes sophisticated context layering through multiple data zones (`user_data_zone`, `discussion_data_zone`, `personality_data_zone`) and a long-term `memory` field for stateful, multi-session interactions.
|
|
515
|
-
|
|
516
|
-
## Examples
|
|
517
|
-
|
|
518
|
-
The `examples/` directory in this repository contains a rich set of scripts demonstrating various features:
|
|
519
|
-
* Basic text generation with different bindings.
|
|
520
|
-
* Streaming and non-streaming examples.
|
|
521
|
-
* Multimodal generation (text with images).
|
|
522
|
-
* Using built-in methods for summarization and Q&A.
|
|
523
|
-
* Implementing and using function calls with **`generate_with_mcp`** and the `local_mcp` binding (see `examples/function_calling_with_local_custom_mcp.py` and `examples/local_mcp.py`).
|
|
524
|
-
* Text-to-Speech and Text-to-Image generation.
|
|
525
|
-
|
|
526
|
-
Explore these examples to see `lollms-client` in action!
|
|
527
|
-
|
|
528
|
-
## Using LoLLMs Client with Different Bindings
|
|
529
|
-
|
|
530
|
-
`lollms-client` supports a wide range of LLM backends through its binding system. This section provides practical examples of how to initialize `LollmsClient` for each of the major supported bindings.
|
|
531
|
-
|
|
532
|
-
### A Note on Configuration
|
|
533
|
-
|
|
534
|
-
The recommended way to provide credentials and other binding-specific settings is through the `llm_binding_config` dictionary during `LollmsClient` initialization. While many bindings can fall back to reading environment variables (e.g., `OPENAI_API_KEY`), passing them explicitly in the config is clearer and less error-prone.
|
|
535
|
-
|
|
536
|
-
```python
|
|
537
|
-
# General configuration pattern
|
|
538
|
-
lc = LollmsClient(
|
|
539
|
-
binding_name="your_binding_name",
|
|
540
|
-
model_name="a_model_name",
|
|
541
|
-
llm_binding_config={
|
|
542
|
-
"specific_api_key_param": "your_api_key_here",
|
|
543
|
-
"another_specific_param": "some_value"
|
|
544
|
-
}
|
|
545
|
-
)
|
|
546
|
-
```
|
|
547
|
-
|
|
548
|
-
---
|
|
549
|
-
|
|
550
|
-
### 1. Local Bindings
|
|
551
|
-
|
|
552
|
-
These bindings run models directly on your local machine, giving you full control and privacy.
|
|
553
|
-
|
|
554
|
-
#### **Ollama**
|
|
555
|
-
|
|
556
|
-
The `ollama` binding connects to a running Ollama server instance on your machine or network.
|
|
557
|
-
|
|
558
|
-
**Prerequisites:**
|
|
559
|
-
* [Ollama installed and running](https://ollama.com/).
|
|
560
|
-
* Models pulled, e.g., `ollama pull llama3`.
|
|
561
|
-
|
|
562
|
-
**Usage:**
|
|
563
|
-
|
|
564
|
-
```python
|
|
565
|
-
from lollms_client import LollmsClient
|
|
566
|
-
|
|
567
|
-
# Configuration for a local Ollama server
|
|
568
|
-
lc = LollmsClient(
|
|
569
|
-
binding_name="ollama",
|
|
570
|
-
model_name="llama3", # Or any other model you have pulled
|
|
571
|
-
host_address="http://localhost:11434" # Default Ollama address
|
|
572
|
-
)
|
|
573
|
-
|
|
574
|
-
# Now you can use lc.generate_text(), lc.chat(), etc.
|
|
575
|
-
response = lc.generate_text("Why is the sky blue?")
|
|
576
|
-
print(response)
|
|
577
|
-
```
|
|
578
|
-
|
|
579
|
-
#### **PythonLlamaCpp (Local GGUF Models)**
|
|
580
|
-
|
|
581
|
-
The `pythonllamacpp` binding loads and runs GGUF model files directly using the powerful `llama-cpp-python` library. This is ideal for high-performance, local inference on CPU or GPU.
|
|
582
|
-
|
|
583
|
-
**Prerequisites:**
|
|
584
|
-
* A GGUF model file downloaded to your machine.
|
|
585
|
-
* `llama-cpp-python` installed. For GPU support, it must be compiled with the correct flags (e.g., `CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python`).
|
|
586
|
-
|
|
587
|
-
**Usage:**
|
|
588
|
-
|
|
589
|
-
```python
|
|
590
|
-
from lollms_client import LollmsClient
|
|
591
|
-
|
|
592
|
-
# --- Configuration for Llama.cpp ---
|
|
593
|
-
# Path to your GGUF model file
|
|
594
|
-
MODEL_PATH = "/path/to/your/model.gguf"
|
|
595
|
-
|
|
596
|
-
# Binding-specific configuration
|
|
597
|
-
LLAMACPP_CONFIG = {
|
|
598
|
-
"n_gpu_layers": -1, # -1 for all layers to GPU, 0 for CPU
|
|
599
|
-
"n_ctx": 4096, # Context size
|
|
600
|
-
"seed": -1, # -1 for random seed
|
|
601
|
-
"chat_format": "chatml" # Or another format like 'llama-2'
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
try:
|
|
605
|
-
lc = LollmsClient(
|
|
606
|
-
binding_name="pythonllamacpp",
|
|
607
|
-
model_name=MODEL_PATH, # For this binding, model_name is the file path
|
|
608
|
-
llm_binding_config=LLAMACPP_CONFIG
|
|
609
|
-
)
|
|
610
|
-
|
|
611
|
-
response = lc.generate_text("Write a recipe for a great day.")
|
|
612
|
-
print(response)
|
|
613
|
-
|
|
614
|
-
except Exception as e:
|
|
615
|
-
print(f"Error initializing Llama.cpp binding: {e}")
|
|
616
|
-
print("Please ensure llama-cpp-python is installed and the model path is correct.")
|
|
617
|
-
|
|
618
|
-
```
|
|
619
|
-
|
|
620
|
-
---
|
|
621
|
-
|
|
622
|
-
### 2. Cloud Service Bindings
|
|
623
|
-
|
|
624
|
-
These bindings connect to hosted LLM APIs from major providers.
|
|
625
|
-
|
|
626
|
-
#### **OpenAI**
|
|
627
|
-
|
|
628
|
-
Connects to the official OpenAI API to use models like GPT-4o, GPT-4, and GPT-3.5.
|
|
629
|
-
|
|
630
|
-
**Prerequisites:**
|
|
631
|
-
* An OpenAI API key.
|
|
632
|
-
|
|
633
|
-
**Usage:**
|
|
634
|
-
|
|
635
|
-
```python
|
|
636
|
-
from lollms_client import LollmsClient
|
|
637
|
-
|
|
638
|
-
OPENAI_CONFIG = {
|
|
639
|
-
"service_key": "your_openai_api_key_here" # sk-...
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
lc = LollmsClient(
|
|
643
|
-
binding_name="openai",
|
|
644
|
-
model_name="gpt-4o",
|
|
645
|
-
llm_binding_config=OPENAI_CONFIG
|
|
646
|
-
)
|
|
647
|
-
|
|
648
|
-
response = lc.generate_text("What is the difference between AI and machine learning?")
|
|
649
|
-
print(response)
|
|
650
|
-
```
|
|
651
|
-
|
|
652
|
-
#### **Google Gemini**
|
|
653
|
-
|
|
654
|
-
Connects to Google's Gemini family of models via the Google AI Studio API.
|
|
655
|
-
|
|
656
|
-
**Prerequisites:**
|
|
657
|
-
* A Google AI Studio API key.
|
|
658
|
-
|
|
659
|
-
**Usage:**
|
|
660
|
-
|
|
661
|
-
```python
|
|
662
|
-
from lollms_client import LollmsClient
|
|
663
|
-
|
|
664
|
-
GEMINI_CONFIG = {
|
|
665
|
-
"service_key": "your_google_api_key_here"
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
lc = LollmsClient(
|
|
669
|
-
binding_name="gemini",
|
|
670
|
-
model_name="gemini-1.5-pro-latest",
|
|
671
|
-
llm_binding_config=GEMINI_CONFIG
|
|
672
|
-
)
|
|
673
|
-
|
|
674
|
-
response = lc.generate_text("Summarize the plot of 'Dune' in three sentences.")
|
|
675
|
-
print(response)
|
|
676
|
-
```
|
|
677
|
-
|
|
678
|
-
#### **Anthropic Claude**
|
|
679
|
-
|
|
680
|
-
Connects to Anthropic's API to use the Claude family of models, including Claude 3.5 Sonnet, Opus, and Haiku.
|
|
681
|
-
|
|
682
|
-
**Prerequisites:**
|
|
683
|
-
* An Anthropic API key.
|
|
684
|
-
|
|
685
|
-
**Usage:**
|
|
686
|
-
|
|
687
|
-
```python
|
|
688
|
-
from lollms_client import LollmsClient
|
|
689
|
-
|
|
690
|
-
CLAUDE_CONFIG = {
|
|
691
|
-
"service_key": "your_anthropic_api_key_here"
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
lc = LollmsClient(
|
|
695
|
-
binding_name="claude",
|
|
696
|
-
model_name="claude-3-5-sonnet-20240620",
|
|
697
|
-
llm_binding_config=CLAUDE_CONFIG
|
|
698
|
-
)
|
|
699
|
-
|
|
700
|
-
response = lc.generate_text("What are the core principles of constitutional AI?")
|
|
701
|
-
print(response)
|
|
702
|
-
```
|
|
703
|
-
|
|
704
|
-
---
|
|
705
|
-
|
|
706
|
-
### 3. API Aggregator Bindings
|
|
707
|
-
|
|
708
|
-
These bindings connect to services that provide access to many different models through a single API.
|
|
709
|
-
|
|
710
|
-
#### **OpenRouter**
|
|
711
|
-
|
|
712
|
-
OpenRouter provides a unified, OpenAI-compatible interface to access models from dozens of providers (Google, Anthropic, Mistral, Groq, etc.) with one API key.
|
|
713
|
-
|
|
714
|
-
**Prerequisites:**
|
|
715
|
-
* An OpenRouter API key (starts with `sk-or-...`).
|
|
716
|
-
|
|
717
|
-
**Usage:**
|
|
718
|
-
Model names must be specified in the format `provider/model-name`.
|
|
719
|
-
|
|
720
|
-
```python
|
|
721
|
-
from lollms_client import LollmsClient
|
|
722
|
-
|
|
723
|
-
OPENROUTER_CONFIG = {
|
|
724
|
-
"open_router_api_key": "your_openrouter_api_key_here"
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
# Example using a Claude model through OpenRouter
|
|
728
|
-
lc = LollmsClient(
|
|
729
|
-
binding_name="open_router",
|
|
730
|
-
model_name="anthropic/claude-3-haiku-20240307",
|
|
731
|
-
llm_binding_config=OPENROUTER_CONFIG
|
|
732
|
-
)
|
|
733
|
-
|
|
734
|
-
response = lc.generate_text("Explain what an API aggregator is, as if to a beginner.")
|
|
735
|
-
print(response)
|
|
736
|
-
```
|
|
737
|
-
|
|
738
|
-
#### **Groq**
|
|
739
|
-
|
|
740
|
-
While Groq is a direct provider, it's famous as an aggregator of speed. It runs open-source models on custom LPU hardware for exceptionally fast inference.
|
|
741
|
-
|
|
742
|
-
**Prerequisites:**
|
|
743
|
-
* A Groq API key.
|
|
744
|
-
|
|
745
|
-
**Usage:**
|
|
746
|
-
|
|
747
|
-
```python
|
|
748
|
-
from lollms_client import LollmsClient
|
|
749
|
-
|
|
750
|
-
GROQ_CONFIG = {
|
|
751
|
-
"groq_api_key": "your_groq_api_key_here"
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
lc = LollmsClient(
|
|
755
|
-
binding_name="groq",
|
|
756
|
-
model_name="llama3-8b-8192",
|
|
757
|
-
llm_binding_config=GROQ_CONFIG
|
|
758
|
-
)
|
|
759
|
-
|
|
760
|
-
response = lc.generate_text("Write a 3-line poem about incredible speed.")
|
|
761
|
-
print(response)
|
|
762
|
-
```
|
|
763
|
-
|
|
764
|
-
#### **Hugging Face Inference API**
|
|
765
|
-
|
|
766
|
-
This connects to the serverless Hugging Face Inference API, allowing experimentation with thousands of open-source models without local hardware.
|
|
767
|
-
|
|
768
|
-
**Note:** This API can have "cold starts," so the first request might be slow.
|
|
769
|
-
|
|
770
|
-
**Prerequisites:**
|
|
771
|
-
* A Hugging Face User Access Token (starts with `hf_...`).
|
|
772
|
-
|
|
773
|
-
**Usage:**
|
|
774
|
-
|
|
775
|
-
```python
|
|
776
|
-
from lollms_client import LollmsClient
|
|
777
|
-
|
|
778
|
-
HF_CONFIG = {
|
|
779
|
-
"hf_api_key": "your_hugging_face_token_here"
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
lc = LollmsClient(
|
|
783
|
-
binding_name="hugging_face_inference_api",
|
|
784
|
-
model_name="google/gemma-1.1-7b-it",
|
|
785
|
-
llm_binding_config=HF_CONFIG
|
|
786
|
-
)
|
|
787
|
-
|
|
788
|
-
response = lc.generate_text("Write a short story about a robot who discovers music.")
|
|
789
|
-
print(response)
|
|
790
|
-
```
|
|
791
|
-
|
|
792
|
-
### Sequential Summarization for Long Texts
|
|
793
|
-
|
|
794
|
-
When dealing with a document, article, or transcript that is too large to fit into a model's context window, the `summarize` method is the solution. It intelligently chunks the text, summarizes each piece, and then synthesizes those summaries into a final, coherent output.
|
|
795
|
-
|
|
796
|
-
```python
|
|
797
|
-
from lollms_client import LollmsClient, MSG_TYPE, LollmsPersonality
|
|
798
|
-
from ascii_colors import ASCIIColors
|
|
799
|
-
|
|
800
|
-
# --- A very long text (imagine this is 10,000+ tokens) ---
|
|
801
|
-
long_text = """
|
|
802
|
-
The history of computing is a fascinating journey from mechanical contraptions to the powerful devices we use today.
|
|
803
|
-
It began with devices like the abacus, used for arithmetic tasks. In the 19th century, Charles Babbage conceived
|
|
804
|
-
the Analytical Engine, a mechanical computer that was never fully built but laid the groundwork for modern computing.
|
|
805
|
-
...
|
|
806
|
-
(many, many paragraphs later)
|
|
807
|
-
...
|
|
808
|
-
Today, quantum computing promises to revolutionize the field once again, tackling problems currently intractable
|
|
809
|
-
for even the most powerful supercomputers. Researchers are exploring qubits and quantum entanglement to create
|
|
810
|
-
machines that will redefine what is computationally possible, impacting fields from medicine to materials science.
|
|
811
|
-
""" * 50 # Simulate a very long text
|
|
812
|
-
|
|
813
|
-
# --- Callback to see the process in action ---
|
|
814
|
-
def summary_callback(chunk: str, msg_type: MSG_TYPE, params: dict = None, **kwargs):
|
|
815
|
-
if msg_type in [MSG_TYPE.MSG_TYPE_STEP_START, MSG_TYPE.MSG_TYPE_STEP_END]:
|
|
816
|
-
ASCIIColors.yellow(f">> {chunk}")
|
|
817
|
-
elif msg_type == MSG_TYPE.MSG_TYPE_STEP:
|
|
818
|
-
ASCIIColors.cyan(f" {chunk}")
|
|
819
|
-
return True
|
|
820
|
-
|
|
821
|
-
try:
|
|
822
|
-
lc = LollmsClient(binding_name="ollama", model_name="llama3")
|
|
823
|
-
|
|
824
|
-
# The contextual prompt guides the focus of the summary
|
|
825
|
-
context_prompt = "Summarize the text, focusing on the key technological milestones and their inventors."
|
|
826
|
-
|
|
827
|
-
ASCIIColors.blue("--- Starting Sequential Summarization ---")
|
|
828
|
-
|
|
829
|
-
final_summary = lc.summarize(
|
|
830
|
-
text_to_summarize=long_text,
|
|
831
|
-
contextual_prompt=context_prompt,
|
|
832
|
-
chunk_size_tokens=1000, # Adjust based on your model's context size
|
|
833
|
-
overlap_tokens=200,
|
|
834
|
-
streaming_callback=summary_callback,
|
|
835
|
-
temperature=0.1 # Good for factual summarization
|
|
836
|
-
)
|
|
837
|
-
|
|
838
|
-
ASCIIColors.blue("\n--- Final Comprehensive Summary ---")
|
|
839
|
-
ASCIIColors.green(final_summary)
|
|
840
|
-
|
|
841
|
-
except Exception as e:
|
|
842
|
-
print(f"An error occurred: {e}")
|
|
843
|
-
```
|
|
844
|
-
## Contributing
|
|
845
|
-
|
|
846
|
-
Contributions are welcome! Whether it's bug reports, feature suggestions, documentation improvements, or new bindings, please feel free to open an issue or submit a pull request on our [GitHub repository](https://github.com/ParisNeo/lollms_client).
|
|
847
|
-
|
|
848
|
-
## License
|
|
849
|
-
|
|
850
|
-
This project is licensed under the **Apache 2.0 License**. See the [LICENSE](LICENSE) file for details.
|
|
851
|
-
|
|
852
|
-
## Changelog
|
|
853
|
-
|
|
854
|
-
For a list of changes and updates, please refer to the [CHANGELOG.md](CHANGELOG.md) file.
|