quantalogic 0.50.29__py3-none-any.whl → 0.52.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.
@@ -0,0 +1,787 @@
1
+ Metadata-Version: 2.1
2
+ Name: quantalogic
3
+ Version: 0.52.0
4
+ Summary: QuantaLogic ReAct Agents
5
+ Author: Raphaël MANSUY
6
+ Author-email: raphael.mansuy@gmail.com
7
+ Requires-Python: >=3.12,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: beautifulsoup4 (>=4.12.3,<5.0.0)
12
+ Requires-Dist: click (>=8.1.8,<9.0.0)
13
+ Requires-Dist: duckduckgo-search (>=7.2.1,<8.0.0)
14
+ Requires-Dist: faker (>=36.1.1,<37.0.0)
15
+ Requires-Dist: fuzzywuzzy (>=0.18.0,<0.19.0)
16
+ Requires-Dist: google-search-results (>=2.4.2,<3.0.0)
17
+ Requires-Dist: html2text (>=2024.2.26,<2025.0.0)
18
+ Requires-Dist: instructor (>=1.7.2,<2.0.0)
19
+ Requires-Dist: jinja2 (>=3.1.5,<4.0.0)
20
+ Requires-Dist: litellm (>=1.56.4,<2.0.0)
21
+ Requires-Dist: loguru (>=0.7.3,<0.8.0)
22
+ Requires-Dist: markdownify (>=0.14.1,<0.15.0)
23
+ Requires-Dist: markitdown (>=0.0.1a3,<0.0.2)
24
+ Requires-Dist: networkx (>=3.2.1,<4.0.0)
25
+ Requires-Dist: pathspec (>=0.12.1,<0.13.0)
26
+ Requires-Dist: prompt-toolkit (>=3.0.48,<4.0.0)
27
+ Requires-Dist: pydantic (>=2.10.4,<3.0.0)
28
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
29
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
30
+ Requires-Dist: rich (>=13.9.4,<14.0.0)
31
+ Requires-Dist: serpapi (>=0.1.5,<0.2.0)
32
+ Requires-Dist: sqlalchemy (>=2.0.25,<3.0.0)
33
+ Requires-Dist: tenacity (>=9.0.0,<10.0.0)
34
+ Requires-Dist: tree-sitter (>=0.23.2,<0.24.0)
35
+ Requires-Dist: tree-sitter-c (>=0.23.4,<0.24.0)
36
+ Requires-Dist: tree-sitter-cpp (>=0.23.4,<0.24.0)
37
+ Requires-Dist: tree-sitter-go (>=0.23.4,<0.24.0)
38
+ Requires-Dist: tree-sitter-java (>=0.23.5,<0.24.0)
39
+ Requires-Dist: tree-sitter-javascript (>=0.23.1,<0.24.0)
40
+ Requires-Dist: tree-sitter-python (>=0.23.6,<0.24.0)
41
+ Requires-Dist: tree-sitter-rust (>=0.23.2,<0.24.0)
42
+ Requires-Dist: tree-sitter-scala (>=0.23.4,<0.24.0)
43
+ Requires-Dist: tree-sitter-typescript (>=0.23.2,<0.24.0)
44
+ Requires-Dist: types-pyyaml (>=6.0.12.20241230,<7.0.0.0)
45
+ Description-Content-Type: text/markdown
46
+
47
+ # QuantaLogic
48
+
49
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
50
+ [![Python](https://img.shields.io/badge/Python-3.12+-blue.svg)](https://www.python.org/downloads/)
51
+ [![Documentation](https://img.shields.io/badge/docs-latest-brightgreen.svg)](https://quantalogic.github.io/quantalogic/)
52
+
53
+ Hey there, welcome to **QuantaLogic**—your cosmic toolkit for crafting AI agents and workflows that shine! Whether you’re coding up a storm, automating a business process, or dreaming up something wild, QuantaLogic is here to make it happen. We’re talking **large language models (LLMs)** fused with a stellar toolset, featuring two powerhouse approaches: the **ReAct framework** for dynamic problem-solving and the dazzling new **Flow module** for structured brilliance.
54
+
55
+ Picture this: a CLI that’s as easy as a snap, a Python API that’s pure magic, and a framework that scales from quick hacks to galactic enterprises. Ready to launch? Let’s blast off!
56
+
57
+ [ Full Docs](https://quantalogic.github.io/quantalogic/) | [ How-To Guide](./docs/howto/howto.md)
58
+
59
+ ![Video Demo](./examples/generated_tutorials/python/quantalogic_8s.gif)
60
+
61
+ ---
62
+
63
+ ## Why QuantaLogic?
64
+
65
+ At [QuantaLogic](https://www.quantalogic.app), we spotted a black hole: amazing AI models from OpenAI, Anthropic, and DeepSeek weren’t fully lighting up real-world tasks. Our mission? Ignite that spark! We’re here to make generative AI a breeze for developers, businesses, and dreamers alike—turning ideas into action, one brilliant solution at a time.
66
+
67
+ > "AI should be your co-pilot, not a puzzle. QuantaLogic makes it happen—fast, fun, and fearless!"
68
+
69
+ ---
70
+
71
+ ## Key Features
72
+
73
+ - **ReAct Framework**: Reasoning + action = unstoppable agents!
74
+ - **Flow Module**: Structured workflows that flow like a river.
75
+ - **LLM Galaxy**: Tap into OpenAI, DeepSeek, and more via LiteLLM.
76
+ - **Secure Tools**: Docker-powered safety for code and files.
77
+ - **Live Monitoring**: Watch it unfold with a web interface and SSE.
78
+ - **Memory Magic**: Smart context keeps things snappy.
79
+ - **Enterprise-Ready**: Logs, error handling, and validation—rock solid.
80
+
81
+ ---
82
+
83
+ ## Table of Contents
84
+
85
+ - [Why QuantaLogic?](#why-quantalogic)
86
+ - [Key Features](#key-features)
87
+ - [Installation](#installation)
88
+ - [Quick Start](#quick-start)
89
+ - [ReAct Framework: Dynamic Agents](#react-framework-dynamic-agents)
90
+ - [Flow Module: Structured Workflows](#flow-module-structured-workflows)
91
+ - 📘 **[Workflow YAML DSL Specification](./quantalogic/flow/flow_yaml.md)**: Comprehensive guide to defining powerful, structured workflows using our Domain-Specific Language
92
+ - 📚 **[Flow YAML Documentation](https://quantalogic.github.io/quantalogic/flow/flow_yaml)**: Dive into the official documentation for a deeper understanding of Flow YAML and its applications
93
+ - [ReAct vs. Flow: Pick Your Power](#react-vs-flow-pick-your-power)
94
+ - [Using the CLI](#using-the-cli)
95
+ - [Examples That Spark Joy](#examples-that-spark-joy)
96
+ - [Core Components](#core-components)
97
+ - [Developing with QuantaLogic](#developing-with-quantalogic)
98
+ - [Contributing](#contributing)
99
+ - [License](#license)
100
+ - [Project Growth](#project-growth)
101
+ - [API Keys and Environment Configuration](#api-keys-and-environment-configuration)
102
+
103
+ ---
104
+
105
+ ## Installation
106
+
107
+ Let’s get QuantaLogic orbiting your system—it’s as easy as 1-2-3!
108
+
109
+ ### What You’ll Need
110
+ - **Python 3.12+**: The fuel for our rocket.
111
+ - **Docker** (optional): Locks down code execution in a safe pod.
112
+
113
+ ### Option 1: pip—Fast and Simple
114
+ ```bash
115
+ pip install quantalogic
116
+ ```
117
+
118
+ ### Option 2: pipx—Isolated Stardust
119
+ ```bash
120
+ pipx install quantalogic
121
+ ```
122
+
123
+ ### Option 3: Source—For Space Explorers
124
+ ```bash
125
+ git clone https://github.com/quantalogic/quantalogic.git
126
+ cd quantalogic
127
+ python -m venv .venv
128
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
129
+ poetry install
130
+ ```
131
+ > **Tip**: No Poetry? Grab it with `pip install poetry` and join the crew!
132
+
133
+ ---
134
+
135
+ ## Quick Start
136
+
137
+ Ready to see the magic? Here’s your launchpad:
138
+
139
+ ### CLI: Instant Action
140
+ ```bash
141
+ quantalogic task "Write a Python function for Fibonacci numbers"
142
+ ```
143
+ > Boom! ReAct whips up a solution in seconds.
144
+
145
+ ### Python: ReAct Agent
146
+ ```python
147
+ from quantalogic import Agent
148
+
149
+ agent = Agent(model_name="deepseek/deepseek-chat")
150
+ result = agent.solve_task("Code a Fibonacci function")
151
+ print(result)
152
+ # Output: "def fib(n): return [0, 1] if n <= 2 else fib(n-1) + [fib(n-1)[-1] + fib(n-1)[-2]]"
153
+ ```
154
+
155
+ ### Synchronous Agent Example
156
+
157
+ ```python
158
+ from quantalogic import Agent
159
+
160
+ # Create a synchronous agent
161
+ agent = Agent(model_name="gpt-4o")
162
+
163
+ # Solve a task synchronously
164
+ result = agent.solve_task(
165
+ task="Write a Python function to calculate Fibonacci numbers",
166
+ max_iterations=10 # Optional: limit iterations
167
+ )
168
+
169
+ print(result)
170
+ ```
171
+
172
+ ### Async Agent Example 🌊
173
+
174
+ ```python
175
+ import asyncio
176
+ from quantalogic import Agent
177
+
178
+ async def main():
179
+ # Create an async agent
180
+ agent = Agent(model_name="gpt-4o")
181
+
182
+ # Solve a task asynchronously with streaming
183
+ result = await agent.async_solve_task(
184
+ task="Write a Python script to scrape top GitHub repositories",
185
+ max_iterations=15, # Optional: limit iterations
186
+ streaming=True # Optional: stream the response
187
+ )
188
+
189
+ print(result)
190
+
191
+ # Run the async function
192
+ asyncio.run(main())
193
+ ```
194
+
195
+ ### Event Monitoring Examples 🔍
196
+
197
+ #### Synchronous Event Monitoring with Finance Tools
198
+ ```python
199
+ from quantalogic import Agent
200
+ from quantalogic.console_print_events import console_print_events
201
+ from quantalogic.console_print_token import console_print_token
202
+ from quantalogic.tools import (
203
+ DuckDuckGoSearchTool,
204
+ TechnicalAnalysisTool,
205
+ YFinanceTool
206
+ )
207
+
208
+ # Create an agent with finance-related tools
209
+ agent = Agent(
210
+ model_name="gpt-4o",
211
+ tools=[
212
+ DuckDuckGoSearchTool(), # Web search tool
213
+ TechnicalAnalysisTool(), # Stock technical analysis
214
+ YFinanceTool() # Stock data retrieval
215
+ ]
216
+ )
217
+
218
+ # Set up comprehensive event listeners
219
+ agent.event_emitter.on(
220
+ event=[
221
+ "task_complete",
222
+ "task_think_start",
223
+ "task_think_end",
224
+ "tool_execution_start",
225
+ "tool_execution_end",
226
+ "error_max_iterations_reached",
227
+ "memory_full",
228
+ "memory_compacted"
229
+ ],
230
+ listener=console_print_events
231
+ )
232
+
233
+ # Optional: Monitor streaming tokens
234
+ agent.event_emitter.on(
235
+ event=["stream_chunk"],
236
+ listener=console_print_token
237
+ )
238
+
239
+ # Execute a multi-step financial analysis task
240
+ result = agent.solve_task(
241
+ "1. Find the top 3 tech stocks for Q3 2024 "
242
+ "2. Retrieve historical stock data for each "
243
+ "3. Calculate 50-day and 200-day moving averages "
244
+ "4. Provide a brief investment recommendation",
245
+ streaming=True # Enable streaming for detailed output
246
+ )
247
+ print(result)
248
+ ```
249
+
250
+ #### Async Event Monitoring with Finance Tools
251
+ ```python
252
+ import asyncio
253
+ from quantalogic import Agent
254
+ from quantalogic.console_print_events import console_print_events
255
+ from quantalogic.console_print_token import console_print_token
256
+ from quantalogic.tools import (
257
+ DuckDuckGoSearchTool,
258
+ TechnicalAnalysisTool,
259
+ YFinanceTool
260
+ )
261
+
262
+ async def main():
263
+ # Create an async agent with finance-related tools
264
+ agent = Agent(
265
+ model_name="gpt-4o",
266
+ tools=[
267
+ DuckDuckGoSearchTool(), # Web search tool
268
+ TechnicalAnalysisTool(), # Stock technical analysis
269
+ YFinanceTool() # Stock data retrieval
270
+ ]
271
+ )
272
+
273
+ # Set up comprehensive event listeners
274
+ agent.event_emitter.on(
275
+ event=[
276
+ "task_complete",
277
+ "task_think_start",
278
+ "task_think_end",
279
+ "tool_execution_start",
280
+ "tool_execution_end",
281
+ "error_max_iterations_reached",
282
+ "memory_full",
283
+ "memory_compacted"
284
+ ],
285
+ listener=console_print_events
286
+ )
287
+
288
+ # Optional: Monitor streaming tokens
289
+ agent.event_emitter.on(
290
+ event=["stream_chunk"],
291
+ listener=console_print_token
292
+ )
293
+
294
+ # Execute a multi-step financial analysis task asynchronously
295
+ result = await agent.async_solve_task(
296
+ "1. Find emerging AI technology startups "
297
+ "2. Analyze their recent funding rounds "
298
+ "3. Compare market potential and growth indicators "
299
+ "4. Provide an investment trend report",
300
+ streaming=True # Enable streaming for detailed output
301
+ )
302
+ print(result)
303
+
304
+ # Run the async function
305
+ asyncio.run(main())
306
+ ```
307
+
308
+ ### Python: Flow Workflow
309
+ ```python
310
+ from quantalogic.flow import Workflow, Nodes
311
+
312
+ @Nodes.define(output="greeting")
313
+ def greet(name: str) -> str:
314
+ return f"Hello, {name}!"
315
+
316
+ workflow = Workflow("greet").build()
317
+ result = await workflow.run({"name": "Luna"})
318
+ print(result["greeting"]) # "Hello, Luna!"
319
+ ```
320
+
321
+ ---
322
+
323
+ ## ReAct Framework: Dynamic Agents
324
+
325
+ The **ReAct** framework is your AI sidekick—think fast, act smart. It pairs LLM reasoning with tool-powered action, perfect for tasks that need a bit of improvisation.
326
+
327
+ ### How It Rolls
328
+ 1. **You Say**: "Write me a script."
329
+ 2. **It Thinks**: LLM plots the course.
330
+ 3. **It Acts**: Tools like `PythonTool` get to work.
331
+ 4. **It Loops**: Keeps going until it’s done.
332
+
333
+ Check this out:
334
+
335
+ ```mermaid
336
+ graph TD
337
+ A[You: 'Write a script'] --> B[ReAct Agent]
338
+ B --> C{Reason with LLM}
339
+ C --> D[Call Tools]
340
+ D --> E[Get Results]
341
+ E --> F{Task Done?}
342
+ F -->|No| C
343
+ F -->|Yes| G[Deliver Answer]
344
+ G --> H[You: Happy!]
345
+ style A fill:#f9f,stroke:#333
346
+ style H fill:#bbf,stroke:#333
347
+ ```
348
+
349
+ ### Example: Code Generator
350
+ ```bash
351
+ quantalogic task "Create a Python script to sort a list"
352
+ ```
353
+ > ReAct figures it out, writes the code, and hands it over—smooth as silk!
354
+
355
+ ### Why It’s Cool
356
+ Perfect for coding, debugging, or answering wild questions on the fly.
357
+
358
+ ---
359
+
360
+ ## Flow Module: Structured Workflows
361
+
362
+ The **Flow module** is your architect—building workflows that hum with precision. It's all about nodes, transitions, and a steady rhythm, ideal for repeatable missions.
363
+
364
+ 🔍 **Want to dive deeper?** Check out our comprehensive [Workflow YAML DSL Specification](./quantalogic/flow/flow_yaml.md), a detailed guide that walks you through defining powerful, structured workflows. From basic node configurations to complex transition logic, this documentation is your roadmap to mastering workflow design with QuantaLogic.
365
+
366
+ 📚 **For a deeper understanding of Flow YAML and its applications, please refer to the official [Flow YAML Documentation](https://quantalogic.github.io/quantalogic/flow/flow_yaml).**
367
+
368
+ The Flow YAML documentation provides a comprehensive overview of the Flow YAML language, including its syntax, features, and best practices. It's a valuable resource for anyone looking to create complex workflows with QuantaLogic.
369
+
370
+ Additionally, the Flow YAML documentation includes a number of examples and tutorials to help you get started with creating your own workflows. These examples cover a range of topics, from simple workflows to more complex scenarios, and are designed to help you understand how to use Flow YAML to create powerful and flexible workflows.
371
+
372
+ ### The Building Blocks
373
+ - **Nodes**: Tasks like functions or LLM calls.
374
+ - **Transitions**: Paths with optional conditions.
375
+ - **Engine**: Runs the show with flair.
376
+ - **Observers**: Peek at progress with events.
377
+
378
+ ### Example: Story Weaver
379
+ ```python
380
+ from quantalogic.flow import Workflow, Nodes
381
+
382
+ @Nodes.llm_node(model="openai/gpt-4o-mini", output="chapter")
383
+ async def write_chapter(ctx: dict) -> str:
384
+ return f"Chapter 1: {ctx['theme']}"
385
+
386
+ workflow = (
387
+ Workflow("write_chapter")
388
+ .then("end", condition="lambda ctx: True")
389
+ .add_observer(lambda e: print(f" {e.event_type}"))
390
+ )
391
+ engine = workflow.build()
392
+ result = await engine.run({"theme": "Cosmic Quest"})
393
+ print(result["chapter"])
394
+ ```
395
+
396
+ ### Example: Story Generator Agent
397
+
398
+ Here's a more complex example showing a complete story generation workflow using the Flow module:
399
+
400
+ ```python
401
+ from typing import List
402
+ import anyio
403
+ from loguru import logger
404
+ from quantalogic.flow import Nodes, Workflow
405
+
406
+ # Define node functions with decorators
407
+ @Nodes.validate_node(output="validation_result")
408
+ async def validate_input(genre: str, num_chapters: int) -> str:
409
+ """Validate input parameters."""
410
+ if not (1 <= num_chapters <= 20 and genre.lower() in ["science fiction", "fantasy", "mystery", "romance"]):
411
+ raise ValueError("Invalid input: genre must be one of science fiction, fantasy, mystery, romance")
412
+ return "Input validated"
413
+
414
+ @Nodes.llm_node(
415
+ model="gemini/gemini-2.0-flash",
416
+ system_prompt="You are a creative writer specializing in story titles.",
417
+ prompt_template="Generate a creative title for a {{ genre }} story. Output only the title.",
418
+ output="title",
419
+ )
420
+ async def generate_title(genre: str) -> str:
421
+ """Generate a title based on the genre (handled by llm_node)."""
422
+ pass # Logic handled by llm_node decorator
423
+
424
+ @Nodes.define(output="manuscript")
425
+ async def compile_book(title: str, outline: str, chapters: List[str]) -> str:
426
+ """Compile the full manuscript from title, outline, and chapters."""
427
+ return f"Title: {title}\n\nOutline:\n{outline}\n\n" + "\n\n".join(
428
+ f"Chapter {i}:\n{chap}" for i, chap in enumerate(chapters, 1)
429
+ )
430
+
431
+ # Define the workflow with conditional branching
432
+ workflow = (
433
+ Workflow("validate_input")
434
+ .then("generate_title")
435
+ .then("generate_outline")
436
+ .then("generate_chapter")
437
+ .then("update_chapter_progress")
438
+ .then("generate_chapter", condition=lambda ctx: ctx["completed_chapters"] < ctx["num_chapters"])
439
+ .then("compile_book", condition=lambda ctx: ctx["completed_chapters"] >= ctx["num_chapters"])
440
+ .then("quality_check")
441
+ .then("end")
442
+ )
443
+
444
+ # Run the workflow
445
+ async def main():
446
+ initial_context = {
447
+ "genre": "science fiction",
448
+ "num_chapters": 3,
449
+ "chapters": [],
450
+ "completed_chapters": 0,
451
+ }
452
+ engine = workflow.build()
453
+ result = await engine.run(initial_context)
454
+ ```
455
+
456
+ This example demonstrates:
457
+ - Input validation with `@Nodes.validate_node`
458
+ - LLM integration with `@Nodes.llm_node`
459
+ - Custom processing with `@Nodes.define`
460
+ - Conditional branching for iterative chapter generation
461
+ - Context management for tracking progress
462
+
463
+ The full example is available at [examples/flow/story_generator_agent.py](./examples/flow/story_generator_agent.py).
464
+
465
+ ### Flow Visualized
466
+ ```mermaid
467
+ graph LR
468
+ A[Start] --> B[WriteChapter]
469
+ B -->|Condition: True| C[End]
470
+ subgraph WriteChapter
471
+ D[Call LLM] --> E[Save Chapter]
472
+ end
473
+ A -->|Observer| F[Log: NODE_STARTED]
474
+ B -->|Observer| G[Log: NODE_COMPLETED]
475
+ style A fill:#dfd,stroke:#333
476
+ style C fill:#dfd,stroke:#333
477
+ style B fill:#ffb,stroke:#333
478
+ ```
479
+
480
+ ### Example: Data Pipeline
481
+ ```python
482
+ @Nodes.define(output="processed")
483
+ def clean_data(data: str) -> str:
484
+ return data.strip().upper()
485
+
486
+ workflow = Workflow("clean_data").build()
487
+ result = await workflow.run({"data": " hello "})
488
+ print(result["processed"]) # "HELLO"
489
+ ```
490
+
491
+ ### Why It Rocks
492
+ Think content pipelines, automation flows, or any multi-step task that needs order.
493
+
494
+ ---
495
+
496
+ ## ReAct vs. Flow: Pick Your Power
497
+
498
+ Both are stellar, but here’s the scoop:
499
+
500
+ | Feature | ReAct Framework | Flow Module |
501
+ |---------------------|--------------------------------|--------------------------------|
502
+ | **Vibe** | Free-spirited, adaptive | Organized, predictable |
503
+ | **Flow** | Loops ‘til it’s solved | Follows a roadmap |
504
+ | **Sweet Spot** | Creative chaos (coding, Q&A) | Steady workflows (pipelines) |
505
+ | **State** | Memory keeps it loose | Nodes lock it down |
506
+ | **Tools** | Grabbed as needed | Baked into nodes |
507
+ | **Watch It** | Events like `task_complete` | Observers like `NODE_STARTED` |
508
+
509
+ ### When to Choose
510
+ - **ReAct**: Code on-the-fly, explore answers, debug like a pro.
511
+ - **Flow**: Build a pipeline, automate a process, keep it tight.
512
+
513
+ ---
514
+
515
+ ## Using the CLI
516
+
517
+ The CLI is your command center—fast, flexible, and fun!
518
+
519
+ ### Syntax
520
+ ```bash
521
+ quantalogic [OPTIONS] COMMAND [ARGS]...
522
+ ```
523
+
524
+ ### Description
525
+ QuantaLogic AI Assistant - A powerful AI tool for various tasks.
526
+
527
+ ### Environment Variables
528
+ - **OpenAI**: Set `OPENAI_API_KEY` to your OpenAI API key
529
+ - **Anthropic**: Set `ANTHROPIC_API_KEY` to your Anthropic API key
530
+ - **DeepSeek**: Set `DEEPSEEK_API_KEY` to your DeepSeek API key
531
+
532
+ Use a `.env` file or export these variables in your shell for seamless integration.
533
+
534
+ ### Commands
535
+ - **`task`**: Kick off a mission.
536
+ ```bash
537
+ quantalogic task "Summarize this file" --file notes.txt
538
+ ```
539
+ - **`list-models`**: List supported LiteLLM models with optional fuzzy search.
540
+ ```bash
541
+ quantalogic list-models --search "gpt"
542
+ ```
543
+
544
+ ### Options
545
+ - **`--model-name TEXT`**: Specify the model to use (litellm format). Examples:
546
+ - `openai/gpt-4o-mini`
547
+ - `openai/gpt-4o`
548
+ - `anthropic/claude-3.5-sonnet`
549
+ - `deepseek/deepseek-chat`
550
+ - `deepseek/deepseek-reasoner`
551
+ - `openrouter/deepseek/deepseek-r1`
552
+ - `openrouter/openai/gpt-4o`
553
+ - **`--mode [code|basic|interpreter|full|code-basic|search|search-full]`**: Agent mode
554
+ - **`--vision-model-name TEXT`**: Specify the vision model to use (litellm format)
555
+ - **`--log [info|debug|warning]`**: Set logging level
556
+ - **`--verbose`**: Enable verbose output
557
+ - **`--max-iterations INTEGER`**: Maximum number of iterations (default: 30)
558
+ - **`--max-tokens-working-memory INTEGER`**: Set the maximum tokens allowed in working memory
559
+ - **`--compact-every-n-iteration INTEGER`**: Set the frequency of memory compaction
560
+ - **`--thinking-model TEXT`**: The thinking model to use
561
+ - **`--version`**: Show version information
562
+
563
+ > **Tip**: Run `quantalogic --help` for the complete command reference!
564
+
565
+ ---
566
+
567
+ ## Examples That Spark Joy
568
+
569
+ Let’s light up your imagination with these gems:
570
+
571
+ ### Video Magic
572
+ [![Tutorial Demo](./examples/generated_tutorials/python/quantalogic_long.mp4)](./examples/generated_tutorials/python/quantalogic_long.mp4)
573
+
574
+ ### Hands-On Examples
575
+ | Name | What’s It Do? | File |
576
+ |-------------------|------------------------------------|--------------------------------------------|
577
+ | Simple Agent | Basic ReAct agent demo | [01-simple-agent.py](./examples/01-simple-agent.py) |
578
+ | Event Monitoring | Agent with event tracking | [02-agent-with-event-monitoring.py](./examples/02-agent-with-event-monitoring.py) |
579
+ | Interpreter Mode | Agent with interpreter | [03-agent-with-interpreter.py](./examples/03-agent-with-interpreter.py) |
580
+ | Agent Summary | Task summary generation | [04-agent-summary-task.py](./examples/04-agent-summary-task.py) |
581
+ | Code Generation | Basic code generation | [05-code.py](./examples/05-code.py) |
582
+ | Code Screen | Advanced code generation | [06-code-screen.py](./examples/06-code-screen.py) |
583
+ | Tutorial Writer | Write technical tutorials | [07-write-tutorial.py](./examples/07-write-tutorial.py) |
584
+ | PRD Writer | Product Requirements Document | [08-prd-writer.py](./examples/08-prd-writer.py) |
585
+ | Story Generator | Flow-based story creation | [story_generator_agent.py](./examples/flow/story_generator_agent.py) |
586
+ | SQL Query | Database query generation | [09-sql-query.py](./examples/09-sql-query.py) |
587
+ | Finance Agent | Financial analysis and tasks | [10-finance-agent.py](./examples/10-finance-agent.py) |
588
+ | Textual Interface | Agent with textual UI | [11-textual-agent-interface.py](./examples/11-textual-agent-interface.py) |
589
+ | Composio Test | Composio integration demo | [12-composio-test.py](./examples/12-composio-test.py) |
590
+ | Synchronous Agent | Synchronous agent demo | [13-synchronous-agent.py](./examples/13-synchronous-agent.py) |
591
+ | Async Agent | Async agent demo | [14-async-agent.py](./examples/14-async-agent.py) |
592
+
593
+ ### Bonus: Math Whiz
594
+ ```bash
595
+ quantalogic task "Solve 2x + 5 = 15"
596
+ ```
597
+ > Output: "Let’s solve it! 2x + 5 = 15 → 2x = 10 → x = 5. Done!"
598
+
599
+ ---
600
+
601
+ ## Core Components
602
+
603
+ ### ReAct Agents
604
+ - **Brain**: LLMs power the thinking.
605
+ - **Hands**: Tools like `PythonTool` do the work.
606
+ - **Memory**: Ties it all together.
607
+
608
+ ### Flow Workflows
609
+ - **Nodes**: Your task blocks.
610
+ - **Engine**: The maestro of execution.
611
+
612
+ ### Tools Arsenal
613
+ - **Code**: `PythonTool`, `NodeJsTool`.
614
+ - **Files**: `ReadFileTool`, `WriteFileTool`.
615
+ - More in [REFERENCE_TOOLS.md](./REFERENCE_TOOLS.md).
616
+
617
+ ---
618
+
619
+ ## Developing with QuantaLogic
620
+
621
+ ### Setup Your Lab
622
+ ```bash
623
+ git clone https://github.com/quantalogic/quantalogic.git
624
+ cd quantalogic
625
+ python -m venv venv
626
+ source venv/bin/activate
627
+ poetry install
628
+ ```
629
+
630
+ ### Test the Cosmos
631
+ ```bash
632
+ pytest --cov=quantalogic
633
+ ```
634
+
635
+ ### Polish It Up
636
+ ```bash
637
+ ruff format # Shine that code
638
+ mypy quantalogic # Check types
639
+ ruff check quantalogic # Lint it
640
+ ```
641
+
642
+ ### Create Custom Tools
643
+ The `create_tool()` function transforms any Python function into a reusable Tool:
644
+
645
+ ```python
646
+ from quantalogic.tools import create_tool
647
+
648
+ def weather_lookup(city: str, country: str = "US") -> dict:
649
+ """Retrieve current weather for a given location.
650
+
651
+ Args:
652
+ city: Name of the city to look up
653
+ country: Two-letter country code (default: US)
654
+
655
+ Returns:
656
+ Dictionary with weather information
657
+ """
658
+ # Implement weather lookup logic here
659
+ return {"temperature": 22, "condition": "Sunny"}
660
+
661
+ # Convert the function to a Tool
662
+ weather_tool = create_tool(weather_lookup)
663
+
664
+ # Now you can use it as a Tool
665
+ print(weather_tool.to_markdown()) # Generate tool documentation
666
+ result = weather_tool.execute(city="New York") # Execute as a tool
667
+ ```
668
+
669
+ #### Using Custom Tools with ReAct Agent
670
+
671
+ Here's how to integrate custom tools with a ReAct Agent:
672
+
673
+ ```python
674
+ from quantalogic import Agent
675
+ from quantalogic.tools import create_tool, PythonTool
676
+
677
+ # Create a custom stock price lookup tool
678
+ def get_stock_price(symbol: str) -> str:
679
+ """Get the current price of a stock by its ticker symbol.
680
+
681
+ Args:
682
+ symbol: Stock ticker symbol (e.g., AAPL, MSFT)
683
+
684
+ Returns:
685
+ Current stock price information
686
+ """
687
+ # In a real implementation, you would fetch from an API
688
+ prices = {"AAPL": 185.92, "MSFT": 425.27, "GOOGL": 175.43}
689
+ if symbol in prices:
690
+ return f"{symbol} is currently trading at ${prices[symbol]}"
691
+ return f"Could not find price for {symbol}"
692
+
693
+ # Create an agent with standard and custom tools
694
+ agent = Agent(
695
+ model_name="gpt-4o",
696
+ tools=[
697
+ PythonTool(), # Standard Python execution tool
698
+ create_tool(get_stock_price) # Custom stock price tool
699
+ ]
700
+ )
701
+
702
+ # The agent can now use both tools to solve tasks
703
+ result = agent.solve_task(
704
+ "Write a Python function to calculate investment growth, "
705
+ "then analyze Apple stock's current price"
706
+ )
707
+
708
+ print(result)
709
+ ```
710
+
711
+ In this example, the agent can seamlessly use both the standard `PythonTool` and your custom stock price lookup tool to complete the task.
712
+
713
+ Key features of `create_tool()`:
714
+ - 🔧 Automatically converts functions to Tools
715
+ - 📝 Extracts metadata from function signature and docstring
716
+ - 🔍 Supports both synchronous and asynchronous functions
717
+ - 🛠️ Generates tool documentation and validation
718
+
719
+ ---
720
+
721
+ ## Contributing
722
+
723
+ Join the QuantaLogic galaxy!
724
+ 1. Fork it.
725
+ 2. Branch: `git checkout -b feature/epic-thing`.
726
+ 3. Code + test.
727
+ 4. PR it!
728
+
729
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full scoop.
730
+
731
+ ---
732
+
733
+ ## License
734
+
735
+ 2024 QuantaLogic Contributors. **Apache 2.0**—free and open. Check [LICENSE](./LICENSE).
736
+
737
+ Dreamed up by Raphaël MANSUY, founder of [QuantaLogic](https://www.quantalogic.app).
738
+
739
+ ---
740
+
741
+ ## Project Growth
742
+ [![Star History Chart](https://api.star-history.com/svg?repos=quantalogic/quantalogic&type=Date)](https://star-history.com/#quantalogic/quantalogic&Date)
743
+
744
+ ---
745
+
746
+ ## API Keys and Environment Configuration
747
+
748
+ QuantaLogic links to LLMs via API keys—here’s your guide to unlocking the universe!
749
+
750
+ ### Setting Up Keys
751
+ Store keys in a `.env` file or export them:
752
+ ```bash
753
+ echo "OPENAI_API_KEY=sk-your-openai-key" > .env
754
+ echo "DEEPSEEK_API_KEY=ds-your-deepseek-key" >> .env
755
+ source .env
756
+ ```
757
+
758
+ ### The Key Vault: Supported Models
759
+ | Model Name | Key Variable | What’s It Good For? |
760
+ |-----------------------------------------|--------------------------|-----------------------------------------------|
761
+ | `openai/gpt-4o-mini` | `OPENAI_API_KEY` | Speedy, budget-friendly tasks |
762
+ | `openai/gpt-4o` | `OPENAI_API_KEY` | Heavy-duty reasoning |
763
+ | `anthropic/claude-3.5-sonnet` | `ANTHROPIC_API_KEY` | Balanced brilliance |
764
+ | `deepseek/deepseek-chat` | `DEEPSEEK_API_KEY` | Chatty and versatile |
765
+ | `deepseek/deepseek-reasoner` | `DEEPSEEK_API_KEY` | Deep problem-solving |
766
+ | `openrouter/deepseek/deepseek-r1` | `OPENROUTER_API_KEY` | Research-grade via OpenRouter |
767
+ | `mistral/mistral-large-2407` | `MISTRAL_API_KEY` | Multilingual mastery |
768
+ | `dashscope/qwen-max` | `DASHSCOPE_API_KEY` | Alibaba’s power player |
769
+ | `lm_studio/mistral-small-24b-instruct-2501` | `LM_STUDIO_API_KEY` | Local LLM action |
770
+
771
+ ### Local Setup (e.g., LM Studio)
772
+ ```bash
773
+ export LM_STUDIO_API_BASE="http://localhost:1234/v1"
774
+ export LM_STUDIO_API_KEY="lm-your-key"
775
+ ```
776
+
777
+ ### Pro Tips
778
+ - **Security**: Keep keys in `.env`, not code!
779
+ - **Extras**: Add `OPENROUTER_REFERRER` for OpenRouter flair.
780
+ - **More**: Dig into [LiteLLM Docs](https://docs.litellm.ai/docs/).
781
+
782
+ ---
783
+
784
+ ## Final Boost
785
+
786
+ QuantaLogic is your ticket to AI awesomeness. Install it, play with it, and let’s build something unforgettable together!
787
+