├── .env.text ├── .gitignore ├── LICENSE ├── README.md ├── assets └── callama.png ├── common ├── prompt.jinja2 └── utils.py ├── examples ├── function_call.py ├── llama3_tinyllama_function_call.ipynb └── ocallama.py ├── llms ├── __init__.py └── llama3.py ├── requirements.txt ├── requirements_with_deps.txt └── setup.py /.env.text: -------------------------------------------------------------------------------- 1 | HF_TOKEN=YOUT_HUGGING_FACE_TOKEN -------------------------------------------------------------------------------- /.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/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ -------------------------------------------------------------------------------- /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, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | You must cause any modified files to carry prominent notices stating that You changed the files; and 37 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 38 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 39 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 40 | 41 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 42 | 43 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 44 | 45 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 46 | 47 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 48 | 49 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 50 | 51 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📞🦙 CaLLama: Hola "Function" are you there? 2 | 3 | ![CaLLama](https://res.cloudinary.com/kidocode/image/upload/c_pad,w_300,h_300,ar_1:1/v1714302845/callama_3_ey59xu.png) 4 | 5 | This repository is dedicated to advancing the "function-call" features for open-source large language models (LLMs). We believe that the future of AI, specifically AI agents, depends on proper function-calling capabilities. While proprietary models like OpenAI's have these features, it is crucial for the open-source community to have access to high-quality function-calling abilities to democratize AI. 6 | 7 | Recently, Facebook released LLaMA3, perhaps the best open-source LLM available. We have fine-tuned and created a version of LLaMA3 that natively supports function calls. 8 | 9 | ## 🎯 Solutions 10 | We are focusing on two directions: 11 | 12 | 1. We are developing a cool library focused on function-call to build a uniform way of working with function calls (tool calls) for all LLMs. This library will be released in its first version soon. 13 | 2. Fine-tuning small models specifically for function calling, which has already been done for Llama 3 and Tiny Llama. 14 | 15 | 16 | ## Usage Methods 🛠️ 17 | 18 | [![Model in HuggingFace](https://huggingface.co/datasets/huggingface/badges/resolve/main/model-on-hf-md.svg)](https://huggingface.co/unclecode) 19 | 20 | 21 | ### 🖥️ Colab 22 | 23 | 1. To know how to run using helper class, check this colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1qyrNeAjURfWFAwEM0ozVEfRQeHUWK4Kq?usp=sharing) 24 | 2. For a more detailed experience, check out the [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://tinyurl.com/ucfllm) 25 | 3. To use GGFU version, check out the [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1EobHQ9fLkNvpWpXfegRUVDRpdd-Va5H_#scrollTo=rh3IlMxDduXw) 26 | 27 | ### 🛠️ Usage Locally 28 | 29 | To use the models in this repository, follow these steps: 30 | 31 | 1. Clone the repository: 32 | ``` 33 | git clone https://github.com/unclecode/fllm.git 34 | ``` 35 | 36 | 2. Create a virtual environment and activate it: 37 | ``` 38 | conda create --name env python=3.10 39 | conda activate env 40 | ``` 41 | 42 | 3. Install PyTorch if you haven't already: 43 | ``` 44 | conda install pytorch-cuda=<12.1/11.8> pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers 45 | ``` 46 | 47 | 4. Install the required dependencies: 48 | ``` 49 | python setup.py 50 | ``` 51 | 5. Add your HuggingFace token in ".env.text", and then rename the file to ".env". 52 | 53 | 6. Run the example code in the `examples` folder to see the models in action. 54 | 55 | You can also refer to the `callama.py` file in the `llms` folder to see the LLM chat template. 56 | 57 | ### 🦙 Using the ollama 58 | 59 | Steps to run the example: 60 | 61 | 1. Make sure Ollama is installed, and ollama server is running. 62 | 2. Pull the model from the ollaama hub. 63 | 64 | ``` 65 | ollama pull unclecode/llama3callama 66 | ollama pull unclecode/tinycallama 67 | ``` 68 | 69 | 3. Make sure to check the ollama example [here](https://github.com/unclecode/callama/blob/main/examples/ocallama.py) 70 | 71 | 72 | Link to models: 73 | - [llama3callama](https://ollama.com/unclecode/llama3callama) 74 | - [tinycallama](https://ollama.com/unclecode/tinycallama) 75 | 76 | 77 | ## ✅ Features TODO List 78 | 79 | - [x] Single function detection 80 | - [x] Support for various model sizes and quantization levels 81 | - [x] Available as a LoRA adapter that can be merged with many models 82 | - [ ] Multi-function detection 83 | - [ ] Function binding, allowing the model to detect the order of execution and bind the output of one function to another 84 | - [ ] Fine-tuning models with less than 1B parameters for efficient function calling 85 | 86 | ## 🤗 Models 87 | 88 | The following models are available on Hugging Face: 89 | 90 | - 🦙 [unclecode/llama3-function-call-lora-adapter-240424](https://huggingface.co/unclecode/llama3-function-call-lora-adapter-240424) 91 | - 🦙 [unclecode/llama3-function-call-Q4_K_M_GGFU-240424](https://huggingface.co/unclecode/llama3-function-call-Q4_K_M_GGFU-240424) 92 | - 🦙 [unclecode/tinyllama-function-call-lora-adapter-250424](https://huggingface.co/unclecode/tinyllama-function-call-lora-adapter-250424) 93 | - 🦙 [unclecode/tinyllama-function-call-Q4_K_M_GGFU-250424](https://huggingface.co/unclecode/tinyllama-function-call-Q4_K_M_GGFU-250424) 94 | 95 | ## 📊 Dataset 96 | 97 | The models were fine-tuned using a modified version of the `ilacai/glaive-function-calling-v2-sharegpt` dataset, which can be found at [unclecode/glaive-function-calling-llama3](https://huggingface.co/datasets/unclecode/glaive-function-calling-llama3). 98 | 99 | ## 🤝 Contributing 100 | 101 | We welcome contributions from the community. If you are interested in joining this project or have any questions, please open an issue in this repository. 102 | 103 | Twitter (X): https://x.com/unclecode 104 | 105 | ## 📜 License 106 | 107 | These models are released under the Apache 2.0 license. 108 | -------------------------------------------------------------------------------- /assets/callama.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/unclecode/callama/83189c72a06cfe94dfc7c96e852fe4f7fbf3acc5/assets/callama.png -------------------------------------------------------------------------------- /common/prompt.jinja2: -------------------------------------------------------------------------------- 1 | {% if messages[0]['role'] == 'system' %} 2 | <|start_header_id|>system<|end_header_id|> 3 | 4 | {{ messages[0]['content'] }} 5 | {{ tools }} 6 | {% endif %} 7 | {% for message in messages %} 8 | {% if message['role'] == 'user' %} 9 | <|start_header_id|>user<|end_header_id|> 10 | 11 | {{ message['content'] }} 12 | {% elif message['role'] == 'tool' %} 13 | <|start_header_id|>assistant<|end_header_id|> 14 | 15 | {{ message['content'] }}<|eot_id|> 16 | {% elif message['role'] == 'tool_response' %} 17 | <|start_header_id|>assistant<|end_header_id|> 18 | 19 | {{ message['content'] }} 20 | {% elif message['role'] == 'assistant' %} 21 | <|start_header_id|>assistant<|end_header_id|> 22 | 23 | {{ message['content'] }}<|eot_id|> 24 | {% endif %} 25 | {% endfor %} 26 | {% if tool_call %} 27 | <|start_header_id|>assistant<|end_header_id|> 28 | 29 | 30 | {% endif %} -------------------------------------------------------------------------------- /common/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | from jinja2 import Template 3 | from typing import List, Dict 4 | import os 5 | 6 | def render(messages: List[Dict[str, str]], tools: List[Dict[str, str]], tool_call=False) -> str: 7 | # Get the directory of the current file 8 | current_dir = os.path.dirname(os.path.abspath(__file__)) 9 | 10 | # Load the template from the "prompt.jinja2" file in the same directory 11 | with open(os.path.join(current_dir, "prompt.jinja2"), "r") as template_file: 12 | template_str = template_file.read() 13 | 14 | # Create a Jinja2 template from the loaded template string 15 | template = Template(template_str) 16 | 17 | # Ensure there is a system message at the beginning 18 | if messages[0]['role'] != 'system': 19 | messages.insert(0, {'role': 'system', 'content': ''}) 20 | 21 | # Convert tools to a JSON string 22 | tools_json = [] 23 | for tool in tools: 24 | tools_json.append(json.dumps(tool, indent=4)) 25 | 26 | tools_json = '\n'.join(tools_json) 27 | 28 | # Render the template with the provided messages, tools, and add_generation_prompt 29 | rendered_string = template.render(messages=messages, tools=tools_json, tool_call=tool_call) 30 | 31 | return rendered_string 32 | 33 | def extract_arguments(text: str, prompt: str, eos_token='<|eot_id|>') -> str: 34 | return text.split(prompt)[1].split(eos_token)[0] -------------------------------------------------------------------------------- /examples/function_call.py: -------------------------------------------------------------------------------- 1 | # test_examples.py 2 | try: 3 | from llms.llama3 import CaLLama 4 | except ImportError: 5 | import os 6 | import sys 7 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 8 | from llms.llama3 import CaLLama 9 | 10 | # Test messages 11 | arithmetic_messages = [ 12 | {'role': 'user', 'content': 'Calculate the 3 * 12 + 3?'}, 13 | {'role': 'tool', 'content': '{"name": "mul", "arguments": \'{"a": 3, "b": 12}\'} '}, 14 | {'role': 'tool_response', 'content': '{"result": 36}'}, 15 | ] 16 | 17 | email_messages = [ 18 | {"role": "system", "content": "You are a helpful assistant with access to the following functions. Use them if required -"}, 19 | {'role': 'user', 'content': "Hi, send an email to tom@kidocode.com and ask him to join our weekend party?"}, 20 | ] 21 | 22 | arithmetic_tools = [ 23 | { 24 | "name": "add", 25 | "description": "Calculate the sum of two numbers", 26 | "parameters": { 27 | "type": "object", 28 | "properties": { 29 | "a": { 30 | "type": "number", 31 | "description": "The first number to add" 32 | }, 33 | "b": { 34 | "type": "integer", 35 | "description": "The second number to add" 36 | } 37 | }, 38 | "required": [ 39 | "a", 40 | "b" 41 | ] 42 | } 43 | }, 44 | { 45 | "name": "mul", 46 | "description": "Calculate the product of two numbers", 47 | "parameters": { 48 | "type": "object", 49 | "properties": { 50 | "a": { 51 | "type": "number", 52 | "description": "The first number to multiply" 53 | }, 54 | "b": { 55 | "type": "integer", 56 | "description": "The second number to multiply" 57 | } 58 | }, 59 | "required": [ 60 | "a", 61 | "b" 62 | ] 63 | } 64 | } 65 | ] 66 | 67 | email_tools = [ 68 | { 69 | "name": "send_email", 70 | "description": "Send an email for the given recipient and message", 71 | "parameters": { 72 | "type": "object", 73 | "properties": { 74 | "recipient": { 75 | "type": "string", 76 | "description": "The email address of the recipient" 77 | }, 78 | "message": { 79 | "type": "string", 80 | "description": "The message to send" 81 | } 82 | }, 83 | "required": [ 84 | "recipient", 85 | "message" 86 | ] 87 | } 88 | } 89 | ] 90 | 91 | if __name__ == "__main__": 92 | # Current models 93 | llama_model_name="unclecode/llama3-function-call-lora-adapter-240424" 94 | tinyllama_model_name="unclecode/tinyllama-function-call-lora-adapter-250424" 95 | 96 | # Usage 97 | llama3 = CaLLama(model_name=llama_model_name) 98 | llama3.load_model() 99 | 100 | # Non-streaming completion for arithmetic 101 | arithmetic_result = llama3.completion(arithmetic_messages, arithmetic_tools, stream=False) 102 | print("Arithmetic Result:") 103 | print(arithmetic_result) 104 | 105 | # Streaming completion for email 106 | print("\nEmail Result (Streaming):") 107 | for token in llama3.completion(email_messages, email_tools, stream=True): 108 | print(token, end="", flush=True) -------------------------------------------------------------------------------- /examples/ocallama.py: -------------------------------------------------------------------------------- 1 | """ 2 | Steps to run the example: 3 | 1. Make sure Ollama is installed, and ollama server is running. 4 | 2. Pull the model from the ollaama hub. 5 | ``` 6 | ollama pull unclecode/llama3callama 7 | ollama pull unclecode/tinycallama 8 | ``` 9 | 10 | References: 11 | - [llama3callama](https://ollama.com/unclecode/llama3callama) 12 | - [tinycallama](https://ollama.com/unclecode/tinycallama) 13 | """ 14 | 15 | 16 | import ollama, os, sys 17 | try: 18 | from common.utils import render, extract_arguments 19 | except ImportError: 20 | # add the parent directory to the sys.path 21 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 22 | from common.utils import render, extract_arguments 23 | 24 | 25 | def use_with_helper(): 26 | messages = [ 27 | { 28 | "role": "system", 29 | "content": "You are a helpful assistant with access to the following functions. Use them if required -", 30 | }, 31 | { 32 | "role": "user", 33 | "content": "Hi, send an email to tom@kidocode.com and ask him to join our weekend party?", 34 | }, 35 | ] 36 | 37 | tools = [ 38 | { 39 | "name": "send_email", 40 | "description": "Send an email for the given recipient and message", 41 | "parameters": { 42 | "type": "object", 43 | "properties": { 44 | "recipient": { 45 | "type": "string", 46 | "description": "The email address of the recipient", 47 | }, 48 | "message": {"type": "string", "description": "The message to send"}, 49 | }, 50 | "required": ["recipient", "message"], 51 | }, 52 | } 53 | ] 54 | 55 | rendered_string = render(messages, tools, tool_call=True) 56 | 57 | response = ollama.chat( 58 | model="unclecode/tinycallama", 59 | messages=[ 60 | { 61 | "role": "user", 62 | "content": rendered_string, 63 | }, 64 | ], 65 | ) 66 | print(response["message"]["content"]) 67 | 68 | 69 | def use_with_prompt(): 70 | prompt = """<|begin_of_text|><|start_header_id|>system<|end_header_id|> 71 | 72 | You are a helpful assistant with access to the following functions. Use them if required - 73 | { 74 | "name": "send_email", 75 | "description": "Send an email for the given recipient and message", 76 | "parameters": { 77 | "type": "object", 78 | "properties": { 79 | "recipient": { 80 | "type": "string", 81 | "description": "The email address of the recipient" 82 | }, 83 | "message": { 84 | "type": "string", 85 | "description": "The message to send" 86 | } 87 | }, 88 | "required": [ 89 | "recipient", 90 | "message" 91 | ] 92 | } 93 | } 94 | <|start_header_id|>user<|end_header_id|> 95 | 96 | Hi, send an email to tom@kidocode.com and ask him to join our weekend party? 97 | <|start_header_id|>assistant<|end_header_id|> 98 | 99 | """ 100 | 101 | response = ollama.chat( 102 | model="unclecode/tinycallama", 103 | messages=[ 104 | { 105 | "role": "user", 106 | "content": prompt, 107 | }, 108 | ], 109 | ) 110 | print(response["message"]["content"]) 111 | 112 | 113 | if __name__ == "__main__": 114 | print("Using Ollama with helper") 115 | use_with_helper() 116 | 117 | print("Using Ollama with prompt") 118 | use_with_prompt() -------------------------------------------------------------------------------- /llms/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/unclecode/callama/83189c72a06cfe94dfc7c96e852fe4f7fbf3acc5/llms/__init__.py -------------------------------------------------------------------------------- /llms/llama3.py: -------------------------------------------------------------------------------- 1 | # llama3.py 2 | 3 | import json, os 4 | from jinja2 import Template 5 | from typing import List, Dict, Union, Generator 6 | from unsloth import FastLanguageModel 7 | from transformers import TextStreamer, TextIteratorStreamer 8 | from threading import Thread 9 | from dotenv import load_dotenv 10 | load_dotenv() 11 | from common.utils import render, extract_arguments 12 | 13 | class CaLLama: 14 | def __init__(self, model_name: str, max_seq_length: int = 4096 * 2, dtype=None, load_in_4bit: bool = True): 15 | self.model_name = model_name 16 | self.max_seq_length = max_seq_length 17 | self.dtype = dtype 18 | self.load_in_4bit = load_in_4bit 19 | self.model = None 20 | self.tokenizer = None 21 | self.text_streamer = None 22 | 23 | self.eos_token = '<|eot_id|>' 24 | 25 | def get_func_call(self, text: str, prompt: str) -> str: 26 | return text.split(prompt)[1].split(self.eos_token)[0] 27 | 28 | def load_model(self): 29 | self.model, self.tokenizer = FastLanguageModel.from_pretrained( 30 | model_name=self.model_name, 31 | max_seq_length=self.max_seq_length, 32 | dtype=self.dtype, 33 | load_in_4bit=self.load_in_4bit, 34 | token=os.environ['HF_TOKEN'] 35 | ) 36 | FastLanguageModel.for_inference(self.model) 37 | self.text_streamer = TextStreamer(self.tokenizer) 38 | 39 | def completion(self, messages: List[Dict[str, str]], tools: List[Dict[str, str]], stream: bool = False, 40 | max_tokens: int = 256, temperature: float = 1.0, top_p: float = 1.0) -> Union[str, Generator[str, None, None]]: 41 | prompt = render(messages, tools, tool_call=True) 42 | inputs = self.tokenizer([prompt], return_tensors="pt").to("cuda") 43 | 44 | if stream: 45 | return self._stream_tokens(prompt, inputs, max_tokens, temperature, top_p) 46 | else: 47 | outputs = self.model.generate(**inputs, max_new_tokens=max_tokens, pad_token_id=self.tokenizer.eos_token_id, 48 | temperature=temperature, top_p=top_p) 49 | response = self.tokenizer.batch_decode(outputs) 50 | return extract_arguments(response[0], prompt, self.eos_token) 51 | 52 | def _stream_tokens(self, prompt, inputs, max_tokens, temperature, top_p) -> Generator[str, None, None]: 53 | streamer = TextIteratorStreamer(self.tokenizer) 54 | generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p, pad_token_id=self.tokenizer.eos_token_id) 55 | thread = Thread(target=self.model.generate, kwargs=generation_kwargs) 56 | thread.start() 57 | is_first = True 58 | for new_text in streamer: 59 | if not is_first and new_text.strip() != self.eos_token: 60 | yield new_text 61 | is_first = False -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git 2 | packaging 3 | ninja 4 | einops 5 | flash-attn 6 | xformers 7 | trl 8 | peft 9 | accelerate 10 | bitsandbytes 11 | pydantic 12 | jinja2 13 | python-dotenv 14 | ollama -------------------------------------------------------------------------------- /requirements_with_deps.txt: -------------------------------------------------------------------------------- 1 | absl-py==2.1.0 2 | accelerate==0.29.3 3 | aiohttp==3.9.5 4 | aiosignal==1.3.1 5 | annotated-types==0.6.0 6 | anyio==4.3.0 7 | argon2-cffi==23.1.0 8 | argon2-cffi-bindings==21.2.0 9 | arrow==1.3.0 10 | asttokens==2.4.1 11 | async-lru==2.0.4 12 | async-timeout==4.0.3 13 | attrs==23.2.0 14 | awscrt==0.20.9 15 | Babel==2.14.0 16 | backoff==2.2.1 17 | beautifulsoup4==4.12.3 18 | bitsandbytes==0.43.1 19 | bleach==6.1.0 20 | boto3==1.34.90 21 | botocore==1.34.90 22 | cachetools==5.3.3 23 | certifi==2024.2.2 24 | cffi==1.16.0 25 | charset-normalizer==3.3.2 26 | click==8.1.7 27 | comm==0.2.2 28 | contourpy==1.2.1 29 | cycler==0.12.1 30 | datasets==2.19.0 31 | debugpy==1.8.1 32 | decorator==5.1.1 33 | defusedxml==0.7.1 34 | dill==0.3.8 35 | docstring_parser==0.16 36 | exceptiongroup==1.2.1 37 | executing==2.0.1 38 | fastapi==0.110.2 39 | fastjsonschema==2.19.1 40 | filelock==3.13.4 41 | fire==0.6.0 42 | fonttools==4.51.0 43 | fqdn==1.5.1 44 | frozenlist==1.4.1 45 | fsspec==2024.3.1 46 | google-auth==2.29.0 47 | google-auth-oauthlib==1.2.0 48 | grpcio==1.62.2 49 | h11==0.14.0 50 | huggingface-hub==0.22.2 51 | idna==3.7 52 | ipykernel==6.26.0 53 | ipython==8.17.2 54 | ipywidgets==8.1.1 55 | isoduration==20.11.0 56 | jedi==0.19.1 57 | Jinja2==3.1.3 58 | jmespath==1.0.1 59 | joblib==1.4.0 60 | json5==0.9.25 61 | jsonpointer==2.4 62 | jsonschema==4.21.1 63 | jsonschema-specifications==2023.12.1 64 | jupyter-events==0.10.0 65 | jupyter-lsp==2.2.5 66 | jupyter_client==8.6.1 67 | jupyter_core==5.7.2 68 | jupyter_server==2.14.0 69 | jupyter_server_terminals==0.5.3 70 | jupyterlab==4.0.6 71 | jupyterlab_pygments==0.3.0 72 | jupyterlab_server==2.27.1 73 | jupyterlab_widgets==3.0.10 74 | kiwisolver==1.4.5 75 | lightning==2.2.3 76 | lightning-cloud==0.5.64 77 | lightning-utilities==0.10.1 78 | lightning_sdk==0.1.4 79 | litdata==0.2.2 80 | Markdown==3.6 81 | markdown-it-py==3.0.0 82 | MarkupSafe==2.1.5 83 | matplotlib==3.8.2 84 | matplotlib-inline==0.1.7 85 | mdurl==0.1.2 86 | mistune==3.0.2 87 | mpmath==1.3.0 88 | multidict==6.0.5 89 | multiprocess==0.70.16 90 | nbclient==0.10.0 91 | nbconvert==7.16.3 92 | nbformat==5.10.4 93 | nest-asyncio==1.6.0 94 | networkx==3.3 95 | notebook_shim==0.2.4 96 | numpy==1.26.2 97 | nvidia-cublas-cu12==12.1.3.1 98 | nvidia-cuda-cupti-cu12==12.1.105 99 | nvidia-cuda-nvrtc-cu12==12.1.105 100 | nvidia-cuda-runtime-cu12==12.1.105 101 | nvidia-cudnn-cu12==8.9.2.26 102 | nvidia-cufft-cu12==11.0.2.54 103 | nvidia-curand-cu12==10.3.2.106 104 | nvidia-cusolver-cu12==11.4.5.107 105 | nvidia-cusparse-cu12==12.1.0.106 106 | nvidia-nccl-cu12==2.19.3 107 | nvidia-nvjitlink-cu12==12.4.127 108 | nvidia-nvtx-cu12==12.1.105 109 | oauthlib==3.2.2 110 | objprint==0.2.3 111 | overrides==7.7.0 112 | packaging==24.0 113 | pandas==2.1.4 114 | pandocfilters==1.5.1 115 | parso==0.8.4 116 | peft==0.10.0 117 | pexpect==4.9.0 118 | pillow==10.3.0 119 | platformdirs==4.2.1 120 | prometheus_client==0.20.0 121 | prompt-toolkit==3.0.43 122 | protobuf==3.20.3 123 | psutil==5.9.8 124 | ptyprocess==0.7.0 125 | pure-eval==0.2.2 126 | pyarrow==16.0.0 127 | pyarrow-hotfix==0.6 128 | pyasn1==0.6.0 129 | pyasn1_modules==0.4.0 130 | pycparser==2.22 131 | pydantic==2.7.1 132 | pydantic_core==2.18.2 133 | Pygments==2.17.2 134 | PyJWT==2.8.0 135 | pyparsing==3.1.2 136 | python-dateutil==2.9.0.post0 137 | python-dotenv==1.0.1 138 | python-json-logger==2.0.7 139 | python-multipart==0.0.9 140 | pytorch-lightning==2.2.3 141 | pytz==2024.1 142 | PyYAML==6.0.1 143 | pyzmq==26.0.2 144 | referencing==0.35.0 145 | regex==2024.4.16 146 | requests==2.31.0 147 | requests-oauthlib==2.0.0 148 | rfc3339-validator==0.1.4 149 | rfc3986-validator==0.1.1 150 | rich==13.7.1 151 | rpds-py==0.18.0 152 | rsa==4.9 153 | s3transfer==0.10.1 154 | safetensors==0.4.3 155 | scikit-learn==1.3.2 156 | scipy==1.11.4 157 | Send2Trash==1.8.3 158 | sentencepiece==0.2.0 159 | shtab==1.7.1 160 | simple-term-menu==1.6.4 161 | six==1.16.0 162 | sniffio==1.3.1 163 | soupsieve==2.5 164 | stack-data==0.6.3 165 | starlette==0.37.2 166 | sympy==1.12 167 | tensorboard==2.15.1 168 | tensorboard-data-server==0.7.2 169 | termcolor==2.4.0 170 | terminado==0.18.1 171 | threadpoolctl==3.4.0 172 | tinycss2==1.3.0 173 | tokenizers==0.19.1 174 | tomli==2.0.1 175 | torch==2.2.1+cu121 176 | torchmetrics==1.3.1 177 | torchvision==0.17.1+cu121 178 | tornado==6.4 179 | tqdm==4.66.2 180 | traitlets==5.14.3 181 | transformers==4.40.1 182 | triton==2.2.0 183 | trl==0.8.6 184 | types-python-dateutil==2.9.0.20240316 185 | typing_extensions==4.11.0 186 | tyro==0.8.3 187 | tzdata==2024.1 188 | unsloth @ git+https://github.com/unslothai/unsloth.git@ec19e61c854dcf9104386fa63fc6c4f2944d4f35 189 | uri-template==1.3.0 190 | urllib3==2.2.1 191 | uvicorn==0.29.0 192 | viztracer==0.16.2 193 | wcwidth==0.2.13 194 | webcolors==1.13 195 | webencodings==0.5.1 196 | websocket-client==1.8.0 197 | Werkzeug==3.0.2 198 | widgetsnbextension==4.0.10 199 | xformers==0.0.25.post1 200 | xxhash==3.4.1 201 | yarl==1.9.4 202 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import sys 3 | import torch 4 | 5 | def install(packages): 6 | for package in packages: 7 | subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-deps", package]) 8 | 9 | def main(): 10 | print("Retrieving CUDA device capability...") 11 | major_version, minor_version = torch.cuda.get_device_capability() 12 | 13 | print("Installing unsloth package...") 14 | subprocess.check_call([sys.executable, "-m", "pip", "install", "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"]) 15 | 16 | if major_version >= 8: 17 | print("Installing packages for newer NVIDIA GPUs (RTX 30xx, RTX 40xx, A100, H100, L40)...") 18 | install(["packaging", "ninja", "einops", "flash-attn", "xformers", "trl", "peft", "accelerate", "bitsandbytes", "pydantic", "jinja2", "python-dotenv", "ollama"]) 19 | else: 20 | print("Installing packages for older NVIDIA GPUs (V100, Tesla T4, RTX 20xx)...") 21 | install(["xformers", "trl", "peft", "accelerate", "bitsandbytes", "pydantic", "jinja2", "python-dotenv", "ollama"]) 22 | 23 | print("Installation complete.") 24 | 25 | if __name__ == "__main__": 26 | main() 27 | --------------------------------------------------------------------------------