├── .gitignore ├── LICENSE ├── README.md ├── llmtalkie.py ├── test_aisermon.py ├── test_llmupper.py ├── test_wikidig.py └── wikidig_utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # llmtalkie - LLM orchestration 2 | 3 | Version 0.1 - very much alpha. 4 | 5 | A micro LLM agent system for data analysis (or synthesis) pipelines. Currently for Ollama only. 6 | 7 | The LLMTalkie project currently provides two features: 8 | 9 | 1. A data processing pipeline where data can be processed by a sequence of prompts, possibly with a different LLM in each step. It's implemented by the `LLMTalkie` and `LLMStep` classes. 10 | 2. A "map" function that applies a prompt (in a single LLM) to a list of data, batching the data efficiently so the LLM can process many items at the same time. It's implemented by the `LLMMap` function. 11 | 12 | 13 | # The data processing pipeline 14 | 15 | You could also call it a "poor man's tool calling for random LLMs". 16 | 17 | The idea is to enable workflows like this: 18 | 19 | - Take input data 20 | - Adapt it for LLM processing 21 | - Pass it to the first prompt/LLM 22 | - Takt the first LLM's output, adapt the data for the second LLM 23 | - Pass it to the second prompt/LLM 24 | - etc. 25 | 26 | The main reason for using multiple prompts is that maybe the data is too complex to process in a single prompt. 27 | 28 | The reasons for using different LLMs could be: 29 | 30 | - A smaller LLM could be faster to use on a large chunk of data 31 | - A smaller LLM could have a larger context than a bigger one, and can process larger chunks of data 32 | - A bigger LLM could provide deeper insight because of expanded world knowlege, but applied to a distilled chunk of data. 33 | 34 | For example (as in the [wikidig](test_wikidig.py) demo script), a small LLM could perform simpler pre-processing and pass the results to a larger LLM to draw conclusions on. 35 | 36 | # The prompt map function 37 | 38 | The `LLMMap` function operates on a list of data, processing each element with a LLM. Instead of inserting each item separately into the prompt, it batches input data into chunks and passes it to a LLM as a list, increasing efficiency. See [test_llmupper](test_llmupper.py) for working code, but the core functionality is: 39 | 40 | ``` 41 | LLM_LOCAL_LLAMA32 = LLMConfig( 42 | url = "http://localhost:11434/api/chat", 43 | model_name = "llama3.2", 44 | system_message = "You process word lists, regardless of what language they are in. Output just a JSON list of results according to the instructions, without explanations or commentary.", 45 | temperature = 0, 46 | options = { 47 | "num_ctx": 1024, # We only need a small context for this. 48 | "num_predict": -2, 49 | } 50 | ) 51 | 52 | print(LLMMap(LLM_LOCAL_LLAMA32, """ 53 | Please study the list of words in the section called "Words". 54 | For each word in the list, convert the word to uppercase and output it in a JSON list in order of appearance. 55 | 56 | Example input: 57 | 58 | * eenie 59 | * meanie 60 | * Wii 61 | 62 | Example output: 63 | 64 | [ "EENIE", "MEANIE", "WII" ] 65 | 66 | # Words 67 | 68 | $LIST 69 | """.lstrip(), ["eenie", "meenie", "miney", "moe"])) 70 | ``` 71 | 72 | The result of the `LLMMap()` call will be a list of words (i.e. `"eenie", "meenie", "miney", "moe"`) in uppercase. 73 | 74 | In my experience, LLM's are about as good at uppercasing words as they are in doing math. 75 | -------------------------------------------------------------------------------- /llmtalkie.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | from collections.abc import Iterable, Mapping 3 | import pprint 4 | from dataclasses import dataclass, field 5 | import logging 6 | import json 7 | import re 8 | import sys, os 9 | from string import Template 10 | from typing import Any, Callable 11 | 12 | import requests 13 | 14 | RE_MD_JSON = re.compile("```(?:json)?\n(.+)```", re.DOTALL) 15 | 16 | DEFAULT_NUM_CTX = 8192 17 | 18 | @dataclass(kw_only=True, frozen=True) 19 | class LLMConfig: 20 | url: str 21 | model_name: str 22 | api_key: str = None 23 | api_style: str = "openai" 24 | system_message: str 25 | temperature: float 26 | options: dict[str, Any] = field(default_factory=dict) 27 | 28 | 29 | # Example config 30 | LLM_LOCAL_LLAMA32 = LLMConfig( 31 | url = "http://localhost:11434/api/chat", 32 | model_name = "llama3.2", 33 | api_style = "ollama", 34 | system_message = "You are a knowledgable assistant. You can answer questions and perform tasks.", 35 | temperature = 0.3, 36 | options = { 37 | "num_ctx": 2048, 38 | "num_predict": -2, 39 | } 40 | ) 41 | 42 | class LLMTalkieException(Exception): pass 43 | 44 | # Design requirements: 45 | # 46 | # Inputs are text prompts, outputs always JSON 47 | # Each conversation step could be done by a different LLM 48 | # 49 | # Example: 50 | # talkie = LLMTalkie(...defaults..., system_message="...") 51 | # step1 = LLMStep(...gemma:2b..., big text, extract some information from this text into JSON, callback to parse this json into dict) 52 | # step2 = LLMStep(...qwen2.5..., data step1 templated with some template, Python format_map from prompt, "Extract data from {title}") 53 | # 54 | # step3 = 55 | 56 | log = logging.getLogger("llmtalkie") 57 | 58 | 59 | def _count_words(llm_config: LLMConfig, text: str) -> int: 60 | # TODO: use proper token counts when OLLama implements the API. 61 | return text.count(" ") 62 | 63 | 64 | def _count_messages_tokens(llm_config: LLMConfig, messages: list[dict]) -> int: 65 | # TODO: use proper token counts when OLLama implements the API. 66 | count = 0 67 | for m in messages: 68 | count += m['content'].count(' ') 69 | return count 70 | 71 | 72 | def _trim_last_message(llm_config: LLMConfig, messages: list[dict], max_words: int): 73 | prev_messages_len = _count_messages_tokens(llm_config, messages[0:-1]) 74 | message = messages[-1] 75 | while prev_messages_len + message['content'].count(' ') > max_words: 76 | p = message['content'].rfind(' ') 77 | if p == -1: 78 | break 79 | message['content'] = message['content'][0:p] 80 | 81 | 82 | class LLMStep: 83 | """ 84 | One step in the LLM chat turn, consisting of a user step and its response (an assistent step). 85 | Construct one of these for every message in the chat history / plan. 86 | """ 87 | 88 | DEFAULT_LLM_CONFIG = LLM_LOCAL_LLAMA32 89 | 90 | def __init__(self, *, 91 | llm_config: LLMConfig, 92 | role: str = "user", 93 | input_callback: Callable[["LLMStep"], dict] = None, 94 | validation_callback: Callable[["LLMStep"], bool] = None, 95 | result_callback: Callable[["LLMStep"], dict] = None, 96 | previous_step: LLMStep = None, 97 | json_response: bool = True, 98 | include_history: bool = False, 99 | input_data: dict[str, Any] = None, 100 | prompt: str, 101 | trim_prompt: bool = False, 102 | ): 103 | self.llm_config = llm_config 104 | self.role = role 105 | self.prompt = prompt 106 | self.trim_prompt = trim_prompt 107 | self.input_callback = input_callback 108 | self.validation_callback = validation_callback 109 | self.result_callback = result_callback 110 | self.previous_step = previous_step 111 | self.json_response = json_response 112 | self.include_history = include_history 113 | self.input_data = input_data if input_data is not None else {} 114 | 115 | self.prompt_data: dict = {} # Data passed to the prompt template 116 | self.has_response: bool = False 117 | self.raw_response: str = None # Raw response from the LLM 118 | self.response: dict = None # Response as dict, parsed from raw_response. If json_response is false, set to {"response": raw_response} 119 | self.result: dict = None # Whatever the callback returns. If callback is None, set to {"response": response} 120 | 121 | 122 | class LLMTalkie: 123 | """ 124 | A LLM pipeline orchestrator. 125 | """ 126 | 127 | def __init__(self, *, llm_config: LLMConfig = None, llm_retry: int = 5, log_file: str = None): 128 | if llm_config is None: 129 | llm_config = LLM_LOCAL_LLAMA32 130 | self.llm_config = llm_config 131 | self.llm_retry = llm_retry 132 | self.log = open(log_file, 'wt') if log_file else None 133 | 134 | def new_step(self, *, 135 | llm_config: LLMConfig = None, 136 | result_callback: Callable[["LLMStep"], dict] = None, 137 | validation_callback: Callable[["LLMStep"], bool] = None, 138 | input_callback: Callable[["LLMStep"], dict] = None, 139 | previous_step: LLMStep = None, 140 | include_history: bool = True, 141 | json_response: bool = True, 142 | input_data: dict[str, Any] = None, 143 | prompt: str, 144 | trim_prompt: bool = False) -> LLMStep: 145 | if llm_config is None: 146 | llm_config = self.llm_config 147 | if input_data is None: 148 | input_data = {} 149 | return LLMStep(llm_config = llm_config, 150 | input_callback = input_callback, 151 | validation_callback = validation_callback, 152 | result_callback = result_callback, 153 | previous_step = previous_step, 154 | include_history = include_history, 155 | json_response = json_response, 156 | input_data = input_data, 157 | prompt = prompt, 158 | trim_prompt = trim_prompt) 159 | 160 | 161 | def execute_steps(self, steps: list[LLMStep]): 162 | log.debug(f"Executing {len(steps)} steps.") 163 | 164 | def _mk_empty_messages(step: LLMStep): 165 | if step.llm_config.system_message: 166 | return [{ 167 | "role": "system", 168 | "content": step.llm_config.system_message, 169 | }] 170 | else: 171 | return [] 172 | 173 | for i, step in enumerate(steps): 174 | if i == 0: 175 | messages = _mk_empty_messages(step) 176 | 177 | tpl = Template(step.prompt) 178 | if i > 0: 179 | step.previous_step = steps[i-1] 180 | prev_response = step.previous_step.result if step.previous_step.result else {} 181 | 182 | if step.input_callback: 183 | input_data = step.input_callback(step) 184 | elif step.input_data: 185 | input_data = step.input_data 186 | else: 187 | input_data = {} 188 | 189 | step.prompt_data = { **prev_response, **input_data } 190 | content = tpl.substitute(step.prompt_data) 191 | else: 192 | step.prompt_data = step.input_data 193 | if step.input_data: 194 | content = tpl.substitute(step.prompt_data) 195 | else: 196 | content = step.prompt 197 | 198 | if not step.include_history: 199 | messages = _mk_empty_messages(step) 200 | 201 | messages.append({ 202 | "role": step.role, 203 | "content": content, 204 | }) 205 | if self.log: self.log.write(json.dumps(messages, indent=2)) 206 | 207 | messages_word_count = _count_messages_tokens(step.llm_config, messages) 208 | log.info(f"*** Messages approx word count: {messages_word_count}") 209 | if int(messages_word_count * 1.5) > step.llm_config.options.get("num_ctx", DEFAULT_NUM_CTX) and step.trim_prompt: 210 | _trim_last_message(step.llm_config, messages, int(step.llm_config.options.get("num_ctx", DEFAULT_NUM_CTX) / 1.5)) 211 | messages_word_count = _count_messages_tokens(step.llm_config, messages) 212 | log.info(f" Trimmed to word count: {messages_word_count}") 213 | 214 | step.raw_response = None 215 | 216 | if step.json_response: 217 | for retry in range(self.llm_retry): 218 | if step.llm_config.api_style == "ollama": 219 | r = requests.post( 220 | step.llm_config.url, 221 | json={ 222 | "model": step.llm_config.model_name, 223 | "options": step.llm_config.options, 224 | "stream": False, 225 | "keep_alive": "30m", 226 | "messages": messages, 227 | "format": "json", 228 | } 229 | ) 230 | elif step.llm_config.api_style == "openai": 231 | r = requests.post( 232 | step.llm_config.url, 233 | headers={ 234 | "Authorization": f"Bearer {step.llm_config.api_key}", 235 | "Content-Type": "application/json", 236 | }, 237 | json={ 238 | "model": step.llm_config.model_name, 239 | "messages": messages, 240 | "response_format": { "type": "json_object" }, 241 | "temperature": step.llm_config.temperature, 242 | "max_tokens": step.llm_config.options.get("num_ctx", DEFAULT_NUM_CTX), 243 | } 244 | ) 245 | try: 246 | result = r.json() 247 | except requests.exceptions.JSONDecodeError: 248 | print(r.text) 249 | raise 250 | if 'error' in result: 251 | log.error(result) 252 | break 253 | assert result["model"] == step.llm_config.model_name 254 | if step.llm_config.api_style == 'ollama' and (not 'done' in result or not result['done']): 255 | log.error(f"No 'done' field in returned result: {result}") 256 | continue 257 | if step.llm_config.api_style == 'openai': 258 | message = result['choices'][0]['message'] 259 | elif step.llm_config.api_style == 'ollama': 260 | message = result["message"] 261 | else: 262 | raise LLMTalkieException(f"Unknown API style: {step.llm_config.api_style}") 263 | assert message["role"] == "assistant" 264 | step.raw_response = self.response = message["content"] 265 | if step.raw_response.find("```") != -1: 266 | step.raw_response = RE_MD_JSON.sub(r"\1", step.raw_response) 267 | try: 268 | step.response = json.loads(step.raw_response) 269 | if step.validation_callback: 270 | if step.validation_callback(step): 271 | break 272 | else: 273 | log.warning(f"Validation failure. Attempt #{retry}/{self.llm_retry} (response: {step.response})") 274 | continue 275 | else: 276 | break 277 | except json.JSONDecodeError as e: 278 | log.error(f"Error parsing LLM response: {e} ({result['message']['content']}). Attemp #{retry}/{self.llm_retry}") 279 | continue 280 | 281 | if step.raw_response is None: 282 | raise LLMTalkieException("Retry limit reached, LLM did not produce valid JSON") 283 | else: 284 | # No need to retry prose writing. 285 | if step.llm_config.api_style == "ollama": 286 | r = requests.post( 287 | step.llm_config.url, 288 | json={ 289 | "model": step.llm_config.model_name, 290 | "options": step.llm_config.options, 291 | "stream": False, 292 | "keep_alive": "30m", 293 | "messages": messages, 294 | } 295 | ) 296 | elif step.llm_config.api_style == "openai": 297 | r = requests.post( 298 | step.llm_config.url, 299 | headers={ 300 | "Authorization": f"Bearer {step.llm_config.api_key}", 301 | "Content-Type": "application/json", 302 | }, 303 | json={ 304 | "model": step.llm_config.model_name, 305 | "messages": messages, 306 | "temperature": step.llm_config.temperature, 307 | "max_tokens": step.llm_config.options.get("num_ctx", DEFAULT_NUM_CTX), 308 | } 309 | ) 310 | 311 | try: 312 | result = r.json() 313 | except requests.exceptions.JSONDecodeError: 314 | log.error(r.text) 315 | raise 316 | if 'error' in result: 317 | log.error(result) 318 | break 319 | 320 | assert result["model"] == step.llm_config.model_name 321 | 322 | if step.llm_config.api_style == 'openai': 323 | message = result['choices'][0]['message'] 324 | elif step.llm_config.api_style == 'ollama': 325 | message = result["message"] 326 | assert result["done"] 327 | else: 328 | raise LLMTalkieException(f"Unknown API style: {step.llm_config.api_style}") 329 | 330 | assert message["role"] == "assistant" 331 | step.raw_response = message["content"] 332 | step.response = step.result = {"response": step.raw_response} 333 | 334 | step.has_response = True 335 | if step.result_callback: 336 | step.result = step.result_callback(step) 337 | else: 338 | step.result = {"response": step.raw_response} 339 | 340 | 341 | def LLMMap(llm_config: LLMConfig, prompt: str, data: Iterable) -> list: 342 | """ 343 | LMMMap applies a LLM configuration and a prompt to a dict or other iterable types, 344 | in an efficient way. It will try to cram as many items into the prompt as possible, 345 | with regards to the LLM's num_ctx. 346 | 347 | The prompt must be constructed in a special way, so it can contain multiple items 348 | in a JSON list, and with proper instructions so that the LLM can process this 349 | list, and output a JSON list as a response. For best results, both the prompt and 350 | the llm_config.system_message should contain instructions to output a JSON document. 351 | 352 | The prompt must contain a special token $LIST where the list will be inserted. 353 | 354 | The result is a dict or a list, containing the LLM's results over the items. 355 | 356 | """ 357 | 358 | tpl = Template(prompt) 359 | 360 | results = [] 361 | batch_number = 0 362 | 363 | f = open('_prompt.json', 'at') 364 | 365 | def llm_process(prompt: str) -> list[str]: 366 | response = None 367 | 368 | messages = [ 369 | { 370 | "role": "system", 371 | "content": llm_config.system_message, 372 | }, 373 | { 374 | "role": "user", 375 | "content": prompt 376 | } 377 | ] 378 | f.write(json.dumps(messages, indent=2)) 379 | f.write("\n\n") 380 | f.flush() 381 | for retry in range(5): 382 | try: 383 | r = requests.post( 384 | llm_config.url, 385 | json={ 386 | "model": llm_config.model_name, 387 | "options": llm_config.options, 388 | "stream": False, 389 | "keep_alive": "30m", 390 | "messages": messages, 391 | } 392 | ) 393 | result = r.json() 394 | assert result["model"] == llm_config.model_name 395 | assert result["done"] 396 | assert result["message"]["role"] == "assistant" 397 | raw_response: str = result["message"]["content"] 398 | if raw_response.find("```") != -1: 399 | raw_response = RE_MD_JSON.sub(r"\1", raw_response) 400 | response: list[str] = json.loads(raw_response) 401 | except json.JSONDecodeError: 402 | log.error(f"(batch {batch_number}) LLM didn't return valid JSON: {raw_response}. Retry #{retry}") 403 | continue 404 | if type(response) != list: 405 | log.error(f"(batch {batch_number}) JSON response to the prompt isn't a list: {raw_response}. Retry #{retry}") 406 | continue 407 | break 408 | if response is None: 409 | raise LLMTalkieException(f"(batch {batch_number}) LLM didn't return a valid output even with {retry} retries") 410 | for x in response: 411 | if type(x) != str: 412 | log.error(f"(batch {batch_number}) JSON response is weird: {raw_response}") 413 | return [x.strip() for x in response] 414 | 415 | if type(data) is dict: 416 | raise Exception("dicts are not supported yet") 417 | elif type(data) is list: 418 | batch_inputs = [] 419 | 420 | for item in data: 421 | list_item = json.dumps(item) 422 | batch_prompt = tpl.substitute({"LIST": (",\n".join(batch_inputs + [list_item]))}) 423 | if _count_words(llm_config, batch_prompt) * 2 > llm_config.options.get("num_ctx", DEFAULT_NUM_CTX) or len(batch_inputs) >= 50: 424 | log.debug(f"Passing {len(batch_inputs)} items, {batch_prompt.count(' ')} words to LLM") 425 | batch_number += 1 426 | while True: 427 | batch_results = llm_process(tpl.substitute({"LIST": "\n".join(batch_inputs)})) 428 | if len(batch_results) == len(batch_inputs): 429 | break 430 | log.error(f"(batch {batch_number}) LLM didn't return all the required items. len(batch_inputs)={len(batch_inputs)}, len(batch_results)={len(batch_results)}. Retrying.") 431 | print(batch_inputs, "->", batch_results) 432 | results.extend(batch_results) 433 | batch_inputs = [list_item] 434 | else: 435 | batch_inputs.append(list_item) 436 | 437 | if len(batch_inputs) > 0: 438 | batch_number += 1 439 | while True: 440 | batch_results = llm_process(tpl.substitute({"LIST": "\n".join(batch_inputs)})) 441 | if len(batch_results) == len(batch_inputs): 442 | break 443 | log.error(f"(batch {batch_number}) LLM didn't return all the required items. len(batch_inputs)={len(batch_inputs)}, len(batch_results)={len(batch_results)}. Retrying.") 444 | #print(batch_inputs, "->", batch_results) 445 | results.extend(batch_results) 446 | else: 447 | raise TypeError(f"Expecting a Mapping or Iterable type: {type(data)}") 448 | 449 | return results 450 | -------------------------------------------------------------------------------- /test_aisermon.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import re 4 | from time import sleep 5 | import pprint 6 | 7 | from dotenv import load_dotenv 8 | import requests 9 | import feedparser 10 | 11 | from llmtalkie import LLMTalkie, LLMStep, LLMConfig 12 | 13 | load_dotenv() 14 | 15 | # Why 2 LLMs? The first one knows the Bible, the second one knows how to write good sermons ;) 16 | 17 | LLM_LOCAL_COMMAND_R = LLMConfig( 18 | url = "http://localhost:11434/api/chat", 19 | model_name = "mistral-small", #"qwen2.5:32b-instruct-q4_K_M", 20 | system_message = "You are a helpful research, religious assistent of the Roman Catholic faith, analyzing news topics. You output only JSON documents and nothing else. Do not output explanations or comments. Stop after outputting JSON.", 21 | temperature = 0.2, 22 | options = { 23 | "num_ctx": 2048, # Almost every time the LLM returns prose instead of JSON, the context size is too small 24 | "num_predict": -2, 25 | } 26 | ) 27 | 28 | LLM_LOCAL_DARKEST_PLANET = LLMConfig( 29 | url = "http://localhost:11434/api/chat", 30 | model_name = "darkest-planet", 31 | system_message = "You are a prophet of the Lord, of the Roman Catholic faith. You write sermons that inspire people to change their lives and participate in solving big world problems. Your sermons are long and sometimes reference Bible verses, your optimism and faith in the Lord and in the betterment of humanity are contagious.", 32 | temperature = 0.8, 33 | options = { 34 | "num_ctx": 4096, 35 | "num_predict": -2, 36 | } 37 | ) 38 | 39 | 40 | LLM_DEEPSEEK_RESEARCHER = LLMConfig( 41 | url = "https://api.deepseek.com/chat/completions", 42 | model_name = "deepseek-chat", 43 | system_message = "You are a helpful researcher, religious assistent of the Roman Catholic faith, analyzing news topics. You output only JSON documents and nothing else. Do not output explanations or comments. Stop after outputting JSON.", 44 | temperature = 0.2, 45 | api_key = os.getenv("DEEPSEEK_API_KEY", None), 46 | api_style = "openai", 47 | ) 48 | 49 | LLM_DEEPSEEK_PREACHER = LLMConfig( 50 | url = "https://api.deepseek.com/chat/completions", 51 | model_name = "deepseek-chat", 52 | system_message = "You are a prophet of the Lord, of the Roman Catholic faith. You write sermons that inspire people to change their lives and participate in solving big world problems. Your sermons are long and sometimes reference Bible verses, your optimism and faith in the Lord and in the betterment of humanity are contagious.", 53 | temperature = 0.8, 54 | api_key = os.getenv("DEEPSEEK_API_KEY", None), 55 | api_style = "openai", 56 | ) 57 | 58 | 59 | def main(): 60 | talkie = LLMTalkie() 61 | 62 | # Get World News 63 | d = feedparser.parse("https://feeds.bbci.co.uk/news/world/rss.xml") 64 | # Ask the LLM to generate Bible references relating to world news 65 | step1 = LLMStep( 66 | llm_config = LLM_DEEPSEEK_RESEARCHER, 67 | input_data = {"news_items": "\n".join(f"* {entry.title}. {entry.description}" for entry in d.entries) }, 68 | prompt = """ 69 | In the following news items, find 3 topics that are of greates concern to pious Catholics, having an impact on their duties, beliefs or institutions. For each of those topics, find a Bible reference that is most suitable for the topic. 70 | 71 | Output just a JSON document in the following format: 72 | 73 | { 74 | "topics": [ 75 | { 76 | "topic": "Topic name", 77 | "news_item": "The news item text", 78 | "bible_reference: "Bible reference, for example Ezekiel 25:17", 79 | "bible_quote": "Bible quote for the above reference." 80 | } 81 | ] 82 | } 83 | 84 | # News items 85 | 86 | $news_items 87 | """.lstrip() 88 | ) 89 | 90 | step2 = LLMStep( 91 | llm_config = LLM_DEEPSEEK_PREACHER, 92 | input_callback = lambda step: { "topic_sections": "\n".join([f"## {t['topic']}\n\n* Bible reference: {t['bible_reference']}\n* Bible quote: {t['bible_quote']}\n* Relation to the world events: {t['news_item']}\n" for t in step.previous_step.response['topics']]) }, 93 | prompt = """ 94 | Write a sermon worthy of the Pope on the impact of the topics described in the following sections on the modern world. 95 | 96 | Use Bible quotes sparingly. Envision a world when, with Jesus's help the described problems will be solved, through the workings of good men. Also mention one of the general problems of the Church in modern times and call on all the faithful to aid in solving it. The sermon should be long, and it should inspire listeners to act for the betterment of the global society. It should also contain dire apocalyptic warnings of what will happen if the poeople do not contribute to a better world. 97 | 98 | Do not reference Bible quotes that are not included in the sections below. Do not output commentary of the sermon, or instructions of what the faithful should do during the mass. Begin with "Blessings of peace to all of you, my brothers and sisters." Finish with "Amen." 99 | 100 | $topic_sections 101 | 102 | """.lstrip(), 103 | json_response = False, 104 | ) 105 | 106 | step3 = LLMStep( 107 | llm_config = LLM_DEEPSEEK_PREACHER, 108 | input_callback = lambda step: step.previous_step.prompt_data, 109 | include_history = False, 110 | prompt = """ 111 | Based on these world events in the following sections, write instructions how can individual faithful practically contribute in their daily lives towards making the world better. 112 | Do not reference any Bible quotes in this text, and write it as a practical, worldy text, not as a classical sermon. 113 | 114 | Start with "What can we do?" and end with "Amen." 115 | 116 | $topic_sections 117 | """.lstrip(), 118 | json_response = False, 119 | validation_callback = lambda step: len(step.raw_response) < 2000, 120 | ) 121 | 122 | talkie.execute_steps([step1, step2, step3]) 123 | 124 | pprint.pp(step1.response, width=120) 125 | pprint.pp(step2.response, width=120) 126 | pprint.pp(step3.response, width=120) 127 | 128 | 129 | 130 | 131 | 132 | 133 | if __name__ == '__main__': 134 | main() 135 | -------------------------------------------------------------------------------- /test_llmupper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from llmtalkie import LLMConfig, LLMMap 4 | 5 | # This test uppercases a list of words using the LLM - arguably the most inefficient 6 | # way to do it - but it's a test :) 7 | 8 | input_words = ["emanation's", "hilltop", "analgesia", "Carpentaria", "preshrunken", "Sumgait", "luridly", "horseplayer", "Strathclyde", "unjustifiable", "blastocoel", "sheering", "cheated", "smartened", "Ghanian's", "relaunch's", "Seaside", "overtaxation", "advertiser's", "mixology", "datasets", "cestode", "reenforces", "Kurtis's", "encoding", "Swaziland's", "replenisher", "magnetospheric", "gigabytes", "cosecants", "transonic", "gauffers", "eights", "circuit's", "repellingly", "Annetta", "ionospheres", "oozy", "ligature's", "dike's", "hotspots", "passionflower's", "highflier", "agio", "deposit's", "eolipile", "electric", "veinlet", "mummy's", "Bonner", "storyline", "Tanya", "cupcake", "Weber's", "legman", "trainable", "spectrographs", "schlepps", "uncharismatic", "pedophiles", "OAS", "reliabilities", "portage", "farthings", "sidesteps", "arriving", "liberalized", "bypass's", "disgracefulness's", "Robbins's", "dale", "despicablenesses", "hopped", "broadly", "northeastern", "formlessly", "Leighton", "beauties", "Essex's", "abuttals", "ascents", "statuses", "horselaughs", "geneticists", "haunt", "ablaut", "postmodernism", "melilots", "trochee's", "flopped", "whiling", "Sandinista", "swipe", "cutlers", "regretfulness", "temperateness's", "premieres", "waggle", "oenophiles", "societies", "parley", "homophobia", "csc", "crunchy", "thriver", "hussy", "braggart", "cocainized", "highlight's", "distressed", "cybercaf\u00e9s", "mudcat", "clarify", "becks", "barbell's", "Schulz's", "divesting", "graphology", "unchristened", "Tokharian", "interlanguage", "Falklands", "posture", "misanthropist", "tricrotic", "Balaton's", "Ariosto's", "Cr", "xor", "takeaway", "picklock", "doubts", "Scotchman's", "Algeria", "striae", "royal's", "speck's", "dingdong", "rhombohedron", "spiffily", "protestor", "hydrangeas", "integrates", "airtime", "Romagna", "snatch", "Brahmaputra's", "jinrikisha", "dolphins", "crosscurrent", "Marathas", "m\u00e9salliances", "yeshivoth", "universities", "MacArthur's", "gourd's", "pseudohermaphroditism", "petered", "amplifying", "FUD", "prizefighter", "launces", "scanter", "trademarks", "Nader's", "irresoluble", "hellgrammite", "Armageddon", "lethargy", "arrowroot", "Milagros", "converge", "archaeopteryxes", "husker", "Oder's", "delaying", "Quarter", "mysteriousness's", "resected", "satellited", "synthesize", "crosspieces", "uniformity's", "Madagascan", "stiffest", "Timbuktu's", "waisted", "abnegation's", "palliation", "Gail", "obstructing", "placidness", "gagged", "Callicrates", "acquiescent", "chattered", "tropeolin", "hinter's", "malamute's", "amalgamation's", "calumniator", "scenarists", "Roman's", "sprue", "repelled", "grizzling", "scrutineer", "autointoxication", "encouragements", "mandolin's", "affirmations", "taunters", "studying", "splatterpunk", "fatback", "moonlights", "calamitousness", "whoopla", "deportee's", "Levine's", "numerations", "conferrable", "Galvani's", "Criseyde", "contraindicated", "cobnut", "ogle's", "spill", "fickly", "Minimalist", "ritualistically", "constructing", "smokehouse", "helve's", "sightless", "Hangchou", "guessing", "supervision's", "oriel", "callow", "heaume", "Rabia", "paratyphoid's", "unusually", "alternated", "mockingbird's", "forefronts", "doodlebug's", "Avior's", "Messeigneurs", "Toronto", "ford", "acre", "Sucre", "verandas", "tattletale's", "HI", "voyage", "Lamont's", "pursuer's", "rendering's", "Sudoku's", "Studebaker", "yacking", "headreach", "Caesarea", "sedum", "chloride", "gentleness", "grenadiers", "Xamarin", "groundnut", "Horus", "Pontchartrain's", "Lindsey's", "anatomize", "begun", "brigs", "proffered", "sinister", "loggerhead's", "mirthful", "strafes", "money's", "inflammations", "protestation's", "damascenes", "expensively", "demoralizer", "doodle", "actress", "alpenstock", "exhibit", "shank", "Brahma", "Mandan", "nubilous", "basketwork", "theriomorphic", "delighting", "KKtP", "buggered", "Durrell", "entity", "Anselm's", "Faustian", "Raj", "bucketing", "scarabaeuses", "musing's", "disrupter", "nondelivery", "slacked", "leopardesses", "tower's", "aborigine's", "disdaining", "preregistering", "villeinage's", "unturned", "hypnotist", "spans", "Hertha", "indefatigabilities", "Matlock's", "mullet's", "recon", "Markov", "curator", "circularize", "staved", "hadji", "phenix", "Amman", "renegaded", "McNaughton's", "Lorre's", "monarchic", "mousiness's", "diode's", "Albania", "Highlander", "NBA's", "queued", "Walgreens", "Guinean", "endamage", "antipoverty", "pedigrees", "nominator's", "Cnidus", "eucalyptuses", "heteromorphic", "outlanders", "rheostat", "Christendom", "womenfolk's", "youthfully", "proscriptions", "spavin's", "Stanford's", "convict's", "backbench", "stodgily", "redintegrative", "sabotage's", "pawing", "dextralities", "excision's", "fireplaces", "Brasil's", "pennoned", "Angara", "anchorman's", "Rowling", "nonbasic", "quelling", "Goode's", "cortisone", "Marquez", "reproduction's", "disciple's", "titian's", "megaphoned", "barium's", "brunette's", "captious", "Valera's", "glutinosity", "meander", "superglue", "ashlars", "rah", "Lordship", "broiling", "yards", "Lysander", "disfavored", "tog's", "weaseled", "repast's", "armatures", "albacore's", "Trekkie", "regalement's", "supportive", "cachexia", "Sverdlovsk", "schmaltzier", "frith", "blurriness's", "allelic", "Dexamyl", "Hieronymus", "kilts", "coke", "buckler", "shortfall's", "metalworking", "simulating", "hideous", "draconian", "loused", "astuter", "rhapsody", "bearberries", "slackenings", "chignon's", "efficaciousnesses", "notable's", "phalanxes", "astronaut", "gtd", "greaser", "simoniacal", "scends", "weathervane", "agribusinesses", "bechanced", "garlic", "Sukkoth", "Haman's", "heats", "fuze", "careening", "birthstones", "ejects", "Vedda", "zedoary", "muscly", "cupule", "Popocatepetl's", "scratchily", "tanker's", "meshugga", "silva", "pentameters", "calla's", "automaton", "brave's", "hammock's", "Baidu", "Vicki", "hydrops", "warehouseman", "apoplectically", "dined", "nah", "cringe", "Rubik", "trough's", "luridness's", "melanic", "bridal", "hotheaded", "gestation", "palatial", "assertiveness", "coelacanth", "Louisianan's", "scrawniness's", "Willemstad", "Nathaniel", "maladminister", "surfperch", "centurial", "hundredth", "bipartisanship's", "centimes", "stammered", "keno's", "glasswort", "girasol", "murderer's", "underwrites", "hyperactivity's", "profusion's", "checked", "unteaching", "eclogue's", "Balboa", "tacked", "dendritic", "evasively", "speedup's", "snooping", "shriek's", "letterer's", "Cwmbran", "endarch", "Boer's", "aristocrat", "pustules", "tadpole's", "inunction", "chatter's", "tatterdemalions", "shrievalty", "solferino", "occasional", "prizefighters", "conglutinates", "yodeled", "Antoine", "Farouk", "teachers", "trains", "duplicitous", "alforja", "endlong", "midlines", "renovators", "estimate", "tenrecs", "formidabilities", "equivalent", "execrable", "trendy's", "cystectomy", "gossipping", "newsgroup's", "bavardage", "Wimsey's", "retitling", "geekier", "moonstone's", "warmups", "zestfully", "Brzezinski", "Lulu's", "Dorothea's", "Sedgemoor", "depict", "milliard", "besmearing", "beguiler's", "borderland", "restructuring's", "psychopathologic", "lizards", "pear", "containers", "dame's", "inciter", "Fonda", "podiatrists", "Nasik", "geologically", "paining", "floodgate's", "apparelled", "buckboard's", "interchangeable", "conglomeration", "asthmatic's", "photochemically", "overexpansion", "heliacal", "Wisdom's", "publican's", "overwintering", "flackery", "Orpingtons", "voiceful", "Volstead's", "microprogram", "grubber", "flanges", "jinrickshas", "dumbest", "Issac", "necroscopy", "uncooperatively", "stumper", "creation", "hydrating", "prentices", "syncopates", "harridans", "deliveryman's", "aridity", "ferule", "shiftiest", "goosy", "Gothically", "Karttikeya", "epigeal", "sebum", "conscious", "snowblowers", "hygiene's", "clonus", "urbanely", "calabooses", "Neptune", "Glenna's", "carnotite", "slip", "pangenesis", "archipelago", "blockier", "Waldo's", "bkcy", "Rydberg's", "exorcise", "diminutive", "earaches", "salaciousness's", "hops", "smuttiness's", "widowing", "regularize", "girlie", "Barnes's", "zirconias", "corduroys", "poison's", "constructors", "thinners", "sowens", "meritoriousness", "celestites", "ammoniacal", "methanol", "hosiery", "subtending", "subvocal", "refineries", "edging's", "clouded", "munching", "undersecretary", "acatalectic", "Fahrenheit's", "baronetage", "Wentworth", "act's", "stonewalled", "Phaedra's", "stroboscopes", "lithopone", "Ashmolean's", "McGee's", "trampers", "equalitarians", "disafforesting", "bibliog", "integral's", "dazzling", "Kay's", "protesters", "auctions", "amortization", "puttee", "analytics", "predestining", "pilgrimage", "walkabout", "ungotten", "sickbed", "actuarial", "Lab", "unimproved", "assignors", "triparted", "hullabaloo", "schoolboys", "uncluttered", "return", "woodcraft", "aggrades", "Apia", "spoiling", "flagrancy", "receptionist", "inception's", "overdecorates", "jeep's", "kayak", "fashionably", "splashes", "Amalia's", "tambours", "appose", "microparasite", "mementoes", "Nips", "Aboriginals", "microaggression", "conceives", "orthopaedists", "Decker's", "runway's", "osseous", "prestidigitation's", "crosshatched", "outsourced", "unsurfaced", "somniferous", "nape's", "handiwork's", "Heidi's", "overture", "escorted", "jimmied", "ambiguously", "darlings", "calculation's", "occidents", "chinquapins", "MacBride", "tenner", "confidant's", "zeros", "resiniferous", "tutorship's", "apex's", "chiseler", "infectiously", "festoon's", "recovered", "gryphons", "octennial", "novelizations", "arabesque", "sallied", "ingraining", "zingers", "stereography", "Jidda", "ensconcing", "densities", "interposing", "paramilitaries", "resettling", "molestations", "Adm", "lepidopterists", "agings", "mazy", "chains", "graving", "penetrates", "retirement's", "untunes", "gallfly", "Hank's", "selectiveness", "vacantly", "gigabits", "Porter", "graticule", "nonparticipants", "unimpressive", "jaywalk", "bordure", "aqueduct", "Gurkhas", "enlarger", "chattered", "garner", "agential", "equability", "proles", "statemented", "cruddier", "scraperboard", "fiat", "nitwit", "churner", "uninviting", "galvanism", "forecasted", "Hurd's", "leashes", "flecks", "lacing", "carrack", "shinnied", "requite", "hulas", "flora", "Copenhagen", "stupendous", "optics's", "chill's", "subdivision", "trinal", "suicides", "Home's", "backrooms", "pediatrics", "valuates", "motorcade", "postscript's", "rosiness's", "Farrow's", "unvoice", "seismography's", "retaliation's", "unequally", "sociol", "heteronym", "surmounter", "codpiece's", "immunize", "singing's", "paperer's", "hammerer", "Agnes's", "fallowing", "lumberer", "ecumenical", "agrimony", "saigas", "Daubigny", "jetliner's", "ventricular", "eastwards", "kino", "geochronology", "Boreal", "responsibly", "amphoteric", "penalties", "Wikileaks", "footrope", "Timon's", "Tai's", "prisage", "Yank's", "penetralia", "womb's", "narrates", "diagnostically", "plumpness", "diking", "inexorably", "aardvark's", "pulleys", "dialysis", "headbutts", "constitutions", "married's", "Doyle", "constellated", "Kimberly", "sweepstakes", "excoriation's", "aftertastes", "inaccurately", "subbranches", "effervesces", "Scheldt", "noncompetitive", "goober's", "meiotically", "cacophonies", "basing", "volcanologist", "suburbanization", "disallowing", "Newtonian", "hashish's", "vacuuming", "Berenice", "quantification", "Antwan", "fulminous", "Moore's", "reprising", "pacers", "Limousin", "mooch", "byelaw's", "venom", "stalkings", "Cambridgeshire", "washy", "biologically", "Mirach's", "singularities", "impurities", "southward's", "poperies", "attention's", "gallstones", "affenpinscher", "Weimaraner", "fomenting", "cesta", "addax", "Kaaba", "Hasidim's", "refueled", "beechnut's", "Duse", "shovelful's", "dreariest", "Shechem", "undershirt", "photons", "flittered", "syllabicities", "germinates", "piddled", "porkier", "gaslights", "Macintosh", "superimpose", "dredges", "Christology", "inconspicuousness", "lemmings", "hater's", "foyers", "forfeiter", "junta", "barnacled", "Korea", "HOV", "houseboat", "bos'n's", "dentists", "sphagnums", "lyric", "reminders", "literarily", "jointer", "indispensables", "dishcloth's", "alfalfa", "abodes", "fadeouts", "tortured", "yogurt's", "spermatophyte", "anamneses", "overfeed", "annalist's", "easel's", "opaquing", "dexterity's", "bereaving", "slapstick", "kicking", "nonparticipating", "thirteenths", "jonquil", "amplitude", "Soudan", "tungsten", "diddlysquat", "Winston's", "Ozenfant", "barricade", "patroness", "septs", "batterers", "outsiders", "wobbliness", "extinguishable", "vocalist's", "Hanukkah", "Elena", "draughtboards", "Tiberias", "shareware", "charge's", "desegregationist", "Ingram's", "meetly", "Kurd's", "lipoid", "Casper", "criminal's", "Snyder", "tailboard", "colorfastness's", "illegal's", "headland", "Reyna's", "mutative", "hypocrite", "Argentinean", "devise", "doddered", "honey's", "reanimation", "corrugates", "redressal", "mandarinism", "hemolysin", "frustum", "juvenile's", "licorices", "kilometer", "detainees", "tireder", "Brummell", "spagyric", "Shintoism's", "posy", "inflammably", "ruggers", "Podgorica's", "antirachitic", "obligations", "him", "Marla", "Cocytus", "Izanagi", "bullock", "Boccaccio's", "forebodingly", "sensuously", "towelings", "underactivity", "emotionally", "rationalist", "weekending", "xanthic", "cracked", "prettying", "shoulder", "mousier", "ruck", "hysterically", "douse", "stative", "masseuse's", "netbook's", "Cerberus", "autonomously", "angioplasties", "jaconet", "Qiqihar", "reboots", "sociologic", "Sisters", "bewrayed", "gadded", "proc", "interfluve", "mantelet", "reauthorizes", "unreformed", "mutt's", "blessings", "trivets", "Brabant", "Lutheran's", "remediated", "sloths", "rebus's", "intactness", "advisor's", "kilt's", "airfields", "gingerliness", "cropper", "mankind's", "resolve's", "allurement's", "peasantry's", "photocathodes", "vizir", "\u00e9migr\u00e9's", "diaphoretic", "Barlow", "braggart's", "bach", "ballot's", "sorry", "cadaverous", "johnnycake's", "liquidations", "punctilio's", "withdraws", "Muhammadanisms", "reis", "meliorable", "Pemba", "Eli's", "appraisees", "snowplowing", "damask's", "arousal's", "autobahn", "seabed's", "cornetcy", "suburban", "Shankar", "equable", "dona's", "Edson", "cert", "Gunther", "gear", "hatchels", "pullback", "halftone's", "Istria", "ithyphallic", "saccule", "recension", "jamb", "gluttonize", "disunion's", "cabana", "criticized", "beetroots", "storehouse", "rapports", "creationisms", "plated", "Sheryl", "cookie's", "packages", "illegal's", "responding", "reverter", "postdoctorate", "droop", "verdigrises", "bombsite", "oxbows", "phosphorous", "lodgements", "shilled", "eide", "MRI's", "stanza", "bloodstock", "mass's", "raid", "locknuts", "encircle", "Breslau's", "stereobate", "perchance", "butterball's", "Franklyn's", "penfriend", "Onsager's", "bend", "Isabela", "penne", "should've", "foin", "bantings", "primatology", "unquestioned", "sourer", "romantically", "mandrill", "dicky's", "customhouse", "hermaphrodite", "mobile's", "Bond's", "attainable", "arsenide", "leatherworker", "Chasity's", "fanlight's", "Territory", "overstimulating", "Solis", "philanthropical", "Nukualofa", "politicoes", "pennyweight's", "Golden", "Mamore's", "garnishment's", "byzantine", "Danville's", "rupture", "munchkin", "navigates", "rainbows", "catamounts", "antifeminisms", "laminitis", "revolter", "baron's", "premises", "courgette", "photothermic", "grout", "engined", "Scotswoman", "whaps", "layovers", "strikes", "rag", "Finney", "subordinating", "psychoactive", "feudist", "Field", "cornices", "topologists", "mezzanine", "stockiness", "flycatcher", "Gloria's", "Bisitun", "despoliation", "quatrain's", "tuneable", "anchorage", "mistakes", "inelegance's", "megastar", "Caslon", "sensitometer", "constructiveness's", "saleswoman", "goalkeeping", "baritone", "doubtfulness", "reminds", "ectomorphs", "Flatt's", "defensed", "nulls", "decimals", "hijacker", "Race's", "westerly's", "conifer's", "reclothe", "acerbate", "Danube's", "subtotals", "solderer's", "midfielder", "cagiest", "retroversion", "Glencoe", "defective's", "chickpeas", "stingrays", "mayn't", "artel", "satinwoods", "dinges", "flab", "abed", "insatiety", "Sharon's", "instants", "Ostyak's", "fudges", "Lynch's", "hegemony", "paperbark", "interlocutors", "suits", "sandwiched", "Massachuset", "epigeous", "illimitably", "spunk's", "sadists", "dedicator", "conspirators", "Sorb", "delightedly", "denaturalized", "vow's", "central", "garpike", "pissoirs", "items", "dachshund's", "refit", "collection", "misspend", "tithing", "lithometeor", "halleluiah", "Sextans", "lightweights", "Handy's", "Valerian's", "agminate", "Oxycontin's", "capt", "immateriality", "Ea", "accident", "psychotically", "foresightedly", "Tegucigalpa's", "entailing", "kinkier", "skoal's", "ensiling", "pygmean", "tropisms", "alpine", "blastogenesis", "incr", "dragonroot", "goldener", "toff", "UHF's", "bloodfin", "entraps", "I'll", "eyelash", "regolith", "superstates", "snug's", "crupper", "abl", "vindictively", "Dmitri's", "Akiva", "dozen's", "Instamatic", "Katie's", "fatherliness", "sterilization", "imparted", "ICU", "excels", "springlike", "corv\u00e9e", "mantelets", "nonorganic", "psid", "outlives", "moralization", "Bridalveil's", "allaying", "aciniform", "ageism", "officialdom", "philharmonics", "erupted", "glutting", "trivially", "gnu's", "dampeners", "shelters", "Cassidy's", "tanked", "solidus", "Ijssel", "guzzlers", "praise's", "interloped", "guffaws", "crematoria", "maid's", "incest's", "unesthetic", "unidentifiable", "shakeups", "tetrachord", "tooth", "remake's", "puerperal", "baldachino", "antivenin's", "amoebae", "raindrop's", "trillium's", "valuable's", "possibles", "roundelay", "collators", "doubler", "hits", "supporting", "meadowsweet", "Borneo's", "tabs", "hallucinator", "stupefies", "factotum", "hobnailing", "insensitive", "malfunction", "drowses", "Montpellier", "kitchenet", "shouters", "exorable", "footage's", "indisciplines", "buffers", "crayon's", "roadster", "phonics", "psychopathy's", "fanaticism's", "kingbolt", "Miguel's", "Cowell", "schoolman", "NIMBY", "winch's", "unsolder", "recuse", "Wartburg", "steeplechasers", "raggedness's", "toreador", "crabby", "reasons", "paracasein", "peatier", "salt", "sponging", "snub's", "diminutions", "grannies", "Nebo's", "blabbed", "doubt", "LXX's", "Exchequer", "butterball", "rugrat's", "moorfowl", "Magsaysay's", "casino", "paint", "puparium", "Chinaman", "steeliness", "orthoscope", "embus", "cottager's", "rummy", "anthracosilicosis", "ossification", "legionnaire's", "homosporous", "festiveness's", "discrete", "sphinx", "equivocators", "excitations", "lappet", "thornily", "binocular", "banking's", "watcher's", "anglicize", "Packard", "cored", "Gnosticisms", "wittol", "Salvadoreans", "scend", "pyxie", "meshworks", "guvs", "mulligrubs", "sourer", "confiscable", "Voldemort's", "jet's", "giber", "collusively", "drawees", "schoolchildren", "priorship", "uninstall", "unseen's", "configurative", "coequal's", "pilseners", "hemolysis", "premenstrually", "anything's", "arcading", "manducated", "cooker's", "thrush's", "domaine", "unclasp", "heterotrophic", "placekickers", "omentums", "Tyson's", "fairytale", "ticals", "overinfluential", "mockeries", "carbonates", "overturns", "shithead's", "arum", "showboating", "Father's", "gastrula", "Falange", "frisking", "ingrowing", "grottos", "orchestrate", "bioclimatologies", "striving", "cavicorn", "labellum", "snappishly", "simonizes", "snouts", "ceremonialism", "tasting's", "reenforce", "khoum", "robalo", "ideogrammatic", "dele", "nominee", "precalculation", "conservancy", "Janelle's", "fundamentally", "uncommonness", "Zubenelgenubi", "pities", "romancing", "chemiluminescent", "vulgarities", "foiled", "summerhouses", "littered", "backhanding", "Englishmen", "subvisible", "DynamoDB's", "coverings", "damply", "Sylvester", "Seward", "atonalist", "tenacious", "Ptah", "gad", "Canaan", "lolcats", "woollies", "gasped", "ecstasies", "Kirsten", "fustily", "slatings", "suckers", "gerunds", "Ryukyuan", "overdecorates", "evaded", "thermodynamically", "Bingham's", "envelopers", "astrogation", "newer", "Isolde", "twin's", "sambar", "Frenchwoman's", "seagirt", "lording", "terebene", "spangly", "fecundation", "crooners", "vendetta", "refection's", "curtly", "Franklin's", "lambkins", "mildness", "Mycenaean's", "sacker's", "undreamt", "Dunant's", "bunghole's", "ultraconservative's", "yen", "pleonastic", "revenging", "hyoids", "mustang's", "chipolatas", "sanctum's", "maturely", "unconventionality", "Barnett's", "Basilicata's", "frogmarch", "chances", "grisaille", "undersells", "Paleolithic's", "historic", "Amazon's", "premier's", "thievish", "greeted", "alterable", "witchery's", "qualifies", "Finn", "dorty", "crepitating", "midpoint", "certitude's", "Harlan", "repairing", "Gabriel's", "bitchier", "dictatorship", "Sandy", "unary", "requisitioning", "Pillsbury's", "Amtrak", "exams", "vibraculum", "apelike", "BlackBerry's", "psychological", "contract's", "Brenda's", "awes", "Chilin", "accord", "causeuse", "sweetbriar", "toxin", "dyne", "croissant", "schizogony", "threat", "untying", "wire", "uncomfortably", "Zanuck's", "brougham", "kelly", "pastimes", "Bolivia's", "svelter", "vinosity", "Urals's", "Baghdad", "sensationalistic", "overlook", "romanticizes", "scandalmonger's", "relabels", "subjugation", "antiphrases", "morrows", "Riel's", "Ashcroft", "Winnebago's", "mudpacks", "basketry's", "Reynold's", "today", "bawdier", "AstroTurf's", "hazel", "lacunose", "hagiographer", "norepinephrine", "unleaded's", "suet", "Patty's", "burglars", "lapful", "searcher's", "Leeuwarden", "ford's", "titrated", "cudgelling", "receipts", "accustom", "outsize", "deuces", "adermin", "unloosed", "intended", "riot's", "actinic", "Minuteman's", "pink's", "Sheraton", "reave", "escapees", "lightheadednesses", "waxier", "rescues", "biology's", "Catalina's", "temporariness", "sloganeer", "smell's", "Nero", "staging", "trouveur", "decongestant's", "demonstrably", "deprave", "Scrooge's", "harpoon", "gravesides", "footballer's", "featherbed", "carrageens", "Shaka", "Arturo", "seismometer", "backhoe's", "taxpayer", "arcuation", "shoemakers", "cheekiest", "mausoleum's", "sly", "Limavady's", "bailed", "venturous", "disappear", "uninitialized", "argyles", "surveillance's", "midnights", "disembody", "corrugation's", "transplantation's", "cardiovascular", "sickie's", "convenable", "jugular's", "jaywalked", "Bandung's", "malcontented", "Russianize", "harking", "muddied", "telecommuter's", "crutches", "postcoital", "dipstick", "dynamometry", "butte", "psychrometers", "offed", "exalts", "alerted", "gorgeously", "garb", "virtuous", "Selden's", "supersecret", "JPEG", "Bobbie's", "Pristina", "gibberish", "donating", "Patsy's", "Corregidor", "exostosis", "scissions", "grog's", "wheedler", "gum's", "hemotherapy", "Ruanda's", "adverseness", "backwardation", "tenth", "Oise", "vastitude", "clubbier", "forth", "signalment", "pub", "interstratify", "Gilroy's", "depleting", "modulations", "uncorroborated", "scrapyard's", "released", "heartstrings", "dived", "hepatitis", "Kagoshima", "allseed", "voraciousness", "deskill", "integumentary", "Vedantic", "modernizers", "mousetraps", "anaphylaxis", "hippocampus", "Mariehamn", "starworts", "Marylou's", "notched", "polymerism", "disinherited", "ovule's", "mirthfulness", "phantasmic", "disagrees", "hierarchs", "stamina's", "manganese's", "gunflint", "blandness", "lumbered", "ameliorates", "breastfeeds", "tortoiseshell", "vitaceous", "midi", "insignia", "hair", "skean", "scandalized", "bargain", "shirtwaist", "finds", "fungi", "underestimation's", "slanderously", "again", "brawniest", "flatfoot's", "apothegmatic", "nitrating", "Tammie", "fragrances", "revel's", "prepares", "Scotswomen", "psychedelically", "blowfish", "inoculate", "desisted", "Puseyisms", "disrespect", "ineligibility's", "characterizations", "condole", "gustation", "spams", "howling", "DP", "perennially", "imitations", "converters", "emblazoning", "paramnesias", "aureolin", "Vickie's", "lapboards", "lipreading's", "Yorkist", "deodorizing", "elephantine", "invulnerable", "tog", "barcarolle", "joinery", "alluvion", "pawnbroking's", "WTO", "doomed", "Hilda", "foreleg's", "vacillate", "realizations", "tyke", "malady's", "unrewarded", "tureens", "begetting", "appendicitis", "patsy's", "Delhi", "depositor", "blesses", "unfixing", "fusspots", "misplacement", "homogamy", "Wii", "substructures", "Motherwell", "Gastonia", "pleaders", "euphemistically", "yowled", "crawly's", "quadruplets", "insecure", "applicable", "palatable", "Russell's", "modernistic", "lotions", "inhabitants", "possess", "inbreeding's", "Colum", "upright", "grief", "credulousness's", "affettuoso", "hesitancy", "Kimberly's", "forcedly", "rout", "Martel's", "throughput's", "circumstantiating", "resinate", "outman", "encyclopedists", "rapids", "lock's", "authorship's", "wiverns", "stoppers", "mouthparts", "carangid", "Aztecs", "Benthamism", "Hildebrand", "heterism", "pint", "Wagnerian's", "jacking", "accursedness's", "deflections", "demoralized", "Marcy's", "sandblasted", "sacculi", "eavesdrops", "Creuse", "ranis", "Perot", "McDaniel's", "medlars", "waspishness's", "drawer's", "rarity", "extreme", "coulomb's", "a", "backdrop", "blindness", "awol", "pronunciation's", "hairiness's", "snowmobiler", "booklover", "dodges", "Bermudian's", "Moresque", "Ex", "Goldsmith", "Carolyn"] 9 | 10 | LLM_LOCAL_LLAMA32 = LLMConfig( 11 | url = "http://localhost:11434/api/chat", 12 | model_name = "llama3.2", 13 | system_message = """Follow the instructions, and write down the result as valid JSON array without explanations or commentary. Begin with "[" and end with "]".""", 14 | temperature = 0, 15 | options = { 16 | "num_ctx": 1024, # We only need a small context for this. 17 | "num_predict": -2, 18 | } 19 | ) 20 | 21 | 22 | def main(): 23 | result = LLMMap(LLM_LOCAL_LLAMA32, """ 24 | You are a student learning how to convert words to uppercase. Study the JSON list of strings in the section named "Strings" carefully. 25 | For each string in the list, convert the string to uppercase by uppercasing each character in the string individually. Output the resulting strings where every character is in uppercase in a JSON array in order of appearance. 26 | 27 | Example input: 28 | 29 | [ "eenie", "meanie", "Mc'Hilltop", "Conglutinates", "goldener" ] 30 | 31 | Example output: 32 | 33 | [ "EENIE", "MEANIE", "MC'HILLTOP", "CONGLUTINATES", "GOLDENER" ] 34 | 35 | # Strings 36 | 37 | [ $LIST ] 38 | 39 | """.lstrip(), input_words) 40 | 41 | assert len(result) == len(input_words) 42 | error_count = 0 43 | 44 | for i in range(len(input_words)): 45 | input_word = input_words[i] 46 | output_word = result[i] 47 | if input_word.upper() != output_word: 48 | print(f"ERROR: {input_word} -> {output_word} (should be {input_word.upper()})") 49 | error_count += 1 50 | 51 | print(f"{error_count} errors ({(error_count / len(input_words))*100:.1f} %)") 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /test_wikidig.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from collections import deque 3 | import json 4 | import logging 5 | import re 6 | import sys 7 | from time import sleep 8 | 9 | import pprint 10 | import requests 11 | 12 | from llmtalkie import LLMTalkie, LLMStep, LLMConfig 13 | from wikidig_utils import wikimedia2md 14 | 15 | log = logging.getLogger("llmtalkie") 16 | logging.basicConfig(stream=sys.stderr, level=logging.INFO) 17 | 18 | # This is a demo app for llmtalkie. 19 | # We'll scrape Wikipedia in search of political leaders, 20 | # but we'll start from scratch, the "History" page. This is of course 21 | # inefficient, but it will work as a demo. The efficient approach would be 22 | # to use Wikipedia's good old-fashioned search to get more useful starting pages. 23 | # and extract mechanical data like links with regexps instead of LLMs. 24 | # 25 | # This demo requires a system with at least 24 GB of VRAM (or RAM if you're patient) and 26 | # the following LLMs to be installed in ollama: 27 | # 28 | # * llama3.2 29 | # * qwen2.5:14b 30 | # 31 | # The idea is to use llama3.2, a small and fast model that allows us to have a bigger context, 32 | # for simpler tasks, and then defer to qwen2.5-14b, a much bigger model which only 33 | # allows us a smaller context, to draw conclusions. 34 | 35 | LLM_LOCAL_LLAMA32 = LLMConfig( 36 | url = "http://localhost:11434/api/chat", 37 | model_name = "llama3.2", 38 | system_message = "You are a helpful research assistent, analyzing topics in Wikipedia articles according to the instructions. You output only JSON documents and nothing else. Do not output explanations or comments. Stop after outputting JSON.", 39 | temperature = 0.3, 40 | options = { 41 | "num_ctx": 16384, # Almost every time the LLM returns prose instead of JSON, the context size is too small 42 | "num_predict": -2, 43 | } 44 | ) 45 | 46 | LLM_LOCAL_QWEN25_14B = LLMConfig( 47 | url = "http://localhost:11434/api/chat", 48 | model_name = "qwen2.5:14b", 49 | system_message = "You are a helpful research assistent, analyzing topics in Wikipedia articles according to the instructions. You output only JSON documents and nothing else. Do not output explanations or comments. Stop after outputting JSON.", 50 | temperature = 0.2, 51 | options = { 52 | "num_ctx": 6144, 53 | "num_predict": -2, 54 | } 55 | ) 56 | 57 | RE_WP_REDIRECT = re.compile(r"#REDIRECT\s*\[(.+?)[\n\]]") 58 | 59 | def get_page_text(title: str) -> str: 60 | """ 61 | Returns Markdown-like data for a Wikipedia page with the given title 62 | """ 63 | title = title.replace(" ", "_") 64 | url = f"https://en.wikipedia.org/w/index.php?action=raw&title={title}" 65 | r = requests.get(url) 66 | sleep(0.1) # take it easy on Wikipedia 67 | text = wikimedia2md(r.text) 68 | text = text.replace("'''", "") 69 | text = text.replace("''", "") 70 | return text 71 | 72 | 73 | def main(): 74 | pages_queue = deque() 75 | pages_queue.append("History") # Starting page 76 | seen_pages: set[str] = set(["history"]) 77 | 78 | result = {} # e.g. { "Person Name": "What they did" } 79 | 80 | talkie = LLMTalkie() 81 | 82 | def update_pages_queue(step: LLMStep): 83 | if type(step.response) != dict: 84 | print(type(step.response)) 85 | print(step.response) 86 | if not step.response: 87 | return 88 | for page in step.response["pages"]: 89 | if page.lower() in seen_pages: 90 | continue 91 | seen_pages.add(page.lower()) 92 | pages_queue.append(page) 93 | return step.response 94 | 95 | def fetch_people_descriptions(step: LLMStep): 96 | if type(step.response) != dict: 97 | print(type(step.response)) 98 | print(step.response) 99 | if not step.response: 100 | return {"people": "None", "people_descriptions": []} 101 | people_sections = [] 102 | people_descriptions = {} 103 | for name in step.response["people"]: 104 | if name in people_descriptions: 105 | continue 106 | text = get_page_text(name) 107 | 108 | while text.find("#REDIRECT") != -1: 109 | m = RE_WP_REDIRECT.search(text) 110 | if m: 111 | text = get_page_text(m.group(1)) 112 | else: 113 | text = "Wikimedia Error" 114 | break 115 | 116 | if text.find("Wikimedia Error") != -1: 117 | continue 118 | 119 | text: str = text[0:text.find("\n#")] # get the first section of the Wikipedia page, the one with the description 120 | text = text.replace("[", "") 121 | text = text.replace("]", "") 122 | people_sections.append(f"# {name}\n\n{text}\n") 123 | people_descriptions[name] = text 124 | 125 | return {"people": "\n\n".join(people_sections), "people_descriptions": people_descriptions} # gets into step2's prompt via template 126 | 127 | def update_result(step: LLMStep): 128 | if type(step.response) != dict: 129 | print(type(step.response)) 130 | print(step.response) 131 | if not step.response: 132 | return 133 | if not 'people' in step.response: 134 | print("ERROR: no people in:", step.response) 135 | return 136 | for name in step.response["people"]: 137 | if step.response["people"][name].upper() == "YES": 138 | try: 139 | description = step.previous_step.result["people_descriptions"][name] 140 | result[name] = description 141 | print("Found person:", name) 142 | except KeyError: 143 | print(f"Can't find person {name} in previous_step inputs: {step.previous_step.input_data}") 144 | 145 | while len(pages_queue) > 0 and len(result) < 50: # Find 50 people 146 | page_title = pages_queue.popleft() 147 | print("Processing page:", page_title) 148 | text = get_page_text(page_title) 149 | 150 | # Step 1 and 2 use a small and fast model 151 | step1 = talkie.new_step( 152 | llm_config=LLM_LOCAL_LLAMA32, 153 | input_data={"text": text}, 154 | trim_prompt=True, 155 | prompt=""" 156 | You are given a text from a Wikipedia article in the section titled "Text" and it has links to other pages formatted as "[Page title]". 157 | Please list page titles about political events or social movements. 158 | Please write the data formatted as a JSON document like in this example: 159 | 160 | { 161 | "pages": [ "Page title", "Another page title" ] 162 | } 163 | 164 | If not sure, make the "pages" list empty. 165 | 166 | # Text 167 | 168 | $text 169 | """.lstrip(), 170 | validation_callback=lambda step: type(step.response) == dict and 'pages' in step.response, 171 | # The LLM result is structured just the way we want it, we just want to fill the page_queue with this callback. 172 | result_callback=update_pages_queue, 173 | ) 174 | 175 | step2 = talkie.new_step( 176 | llm_config=LLM_LOCAL_LLAMA32, 177 | input_data={"text": text}, 178 | trim_prompt=True, 179 | prompt=""" 180 | List up to 30 people names appearing in section titled "Text", who might be involved in politics or social movements. 181 | Please write the data formatted as a JSON document like in this example: 182 | 183 | { 184 | "people": [ "John Doe", "Person Name" ] 185 | } 186 | 187 | If not sure, make the "people" list empty. 188 | 189 | # Text 190 | 191 | $text 192 | """.lstrip(), 193 | include_history=False, 194 | validation_callback=lambda step: type(step.response) == dict and 'people' in step.response, 195 | # Called when LLM generates the response from this step, prepares the result for the following step 196 | result_callback=fetch_people_descriptions, 197 | ) 198 | 199 | step3 = talkie.new_step( 200 | llm_config=LLM_LOCAL_QWEN25_14B, 201 | input_data={"text": text}, 202 | include_history=False, 203 | trim_prompt=True, 204 | prompt=""" 205 | Your task is to analyze the following sections containing texts about people. Each section is 206 | titled with a person's name. Analyze all the available sections and for each person, 207 | output "YES" if the text for the person indicates they were either a political leader, 208 | social movement leader, or a revolutionary, and otherwise wrie "NO". 209 | 210 | Please output the data formatted as JSON like in this example, without any commentary or explanations: 211 | 212 | { 213 | "people": { 214 | "Person name": "YES", 215 | "Another person name": "NO" 216 | } 217 | } 218 | 219 | The texts to analyze are: 220 | 221 | $people 222 | """.lstrip(), 223 | validation_callback=lambda step: type(step.response) == dict and 'people' in step.response, 224 | result_callback=update_result, 225 | ) 226 | 227 | talkie.execute_steps([step1, step2, step3]) 228 | 229 | #pprint.pp(step1.result, width=120) 230 | #pprint.pp(step2.result, width=120) 231 | #pprint.pp(step3.result, width=120) 232 | print("# Pages to process:", len(pages_queue)) 233 | 234 | print(json.dumps(result, indent=2)) 235 | 236 | if __name__ == '__main__': 237 | main() 238 | -------------------------------------------------------------------------------- /wikidig_utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | RE_REF_TAG = re.compile(r".+?", re.DOTALL) 4 | RE_XML_TAG = re.compile(r"<[^>]+?>") 5 | RE_FILE_LINK = re.compile(r"\[\[File:(.+?)(|.+?)]]") 6 | RE_LINKS = re.compile(r"\[\[(.+?)(\|.+?)?]]") 7 | RE_MACRO = re.compile(r"{{.+?}}") 8 | RE_H3 = re.compile(r"^===(.+)===$", re.MULTILINE) 9 | RE_H2 = re.compile(r"^==(.+)==$", re.MULTILINE) 10 | RE_H1 = re.compile(r"^=(.+)=$", re.MULTILINE) 11 | RE_EMPTY_LIST = re.compile(r"^\*\s*$", re.MULTILINE) 12 | 13 | 14 | def remove_nested_curlies(text: str): 15 | # Stack to track open curly braces 16 | nesting_level = 0 17 | result = [] 18 | i = 0 19 | while i < len(text): 20 | if text[i:i+2] == '{{': # Found an opening tag 21 | nesting_level += 1 22 | i += 2 # Skip the opening braces 23 | elif text[i:i+2] == '}}' and nesting_level > 0: # Found a closing tag 24 | nesting_level -= 1 25 | i += 2 # Skip the closing braces 26 | else: 27 | if nesting_level == 0: # Only append characters when not inside a tag 28 | result.append(text[i]) 29 | i += 1 30 | return ''.join(result) 31 | 32 | 33 | def remove_file_links(text: str): 34 | # Stack to track open curly braces 35 | result = [] 36 | nesting_level = 0 37 | start_first_level = None 38 | link_content = None 39 | i = 0 40 | while i < len(text): 41 | if text[i:i+2] == '[[': # Found an opening tag 42 | if nesting_level == 0: 43 | start_first_level = i+2 44 | nesting_level += 1 45 | i += 2 # Skip the opening braces 46 | elif text[i:i+2] == ']]' and nesting_level > 0: # Found a closing tag 47 | nesting_level -= 1 48 | if nesting_level == 0: 49 | link_content = text[start_first_level:i] 50 | start_first_level = None 51 | i += 2 # Skip the closing braces 52 | else: 53 | if nesting_level == 0: # Only append characters when not inside a tag 54 | result.append(text[i]) 55 | i += 1 56 | 57 | if link_content: 58 | # special case 59 | result = result[0:i-len(link_content)] 60 | if not link_content.lower().startswith("file:"): 61 | p = link_content.find("|") 62 | if p != -1: 63 | link_content = link_content[p+1:] 64 | result.extend(f"[{link_content}]") 65 | link_content = None 66 | 67 | return ''.join(result) 68 | 69 | 70 | def wikimedia2md(text: str) -> str: 71 | """ 72 | A simple regex-based conversion from the WikiMedia wiki format to the Markdown wiki format. 73 | """ 74 | text = remove_nested_curlies(text) 75 | text = remove_file_links(text) 76 | 77 | text = RE_XML_TAG.sub("", text) 78 | text = RE_H3.sub(r"### \1", text) 79 | text = RE_H2.sub(r"## \1", text) 80 | text = RE_H1.sub(r"# \1", text) 81 | text = RE_EMPTY_LIST.sub(r"", text) 82 | 83 | return text.strip() 84 | --------------------------------------------------------------------------------