├── .github └── workflows │ ├── deploy.yaml │ └── test.yaml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── langfree ├── __init__.py ├── _modidx.py ├── chatrecord.py ├── runs.py ├── shiny.py └── transform.py ├── nbs ├── 01_runs.ipynb ├── 02_transform.ipynb ├── 03_chatrecord.ipynb ├── 04_shiny.ipynb ├── CNAME ├── _quarto.yml ├── favicon.png ├── index.ipynb ├── langfree.png ├── logo.png ├── nbdev.yml ├── sidebar.yml ├── styles.css └── tutorials │ ├── _data │ └── sample_data.pkl │ ├── app.py │ ├── screenshot.png │ └── shiny.ipynb ├── settings.ini └── setup.py /.github/workflows/deploy.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy to GitHub Pages 2 | 3 | permissions: 4 | contents: write 5 | pages: write 6 | 7 | env: 8 | LANGCHAIN_API_KEY: ${{ secrets.LANGCHAIN_API_KEY }} 9 | LANGCHAIN_API_KEY_PUB: ${{ secrets.LANGCHAIN_API_KEY_PUB }} 10 | LANGCHAIN_HUB_API_KEY: ${{ secrets.LANGCHAIN_HUB_API_KEY }} 11 | LANGSMITH_PROJECT_ID: ${{ secrets.LANGSMITH_PROJECT_ID }} 12 | LANGCHAIN_PROJECT_ID_PUB: ${{ secrets.LANGCHAIN_PROJECT_ID_PUB }} 13 | LANGCHAIN_ENDPOINT: "https://api.smith.langchain.com" 14 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} 15 | 16 | on: 17 | push: 18 | branches: [ "main", "master" ] 19 | workflow_dispatch: 20 | jobs: 21 | deploy: 22 | runs-on: ubuntu-latest 23 | steps: [uses: fastai/workflows/quarto-ghp@master] 24 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [workflow_dispatch, pull_request, push] 3 | 4 | env: 5 | LANGCHAIN_API_KEY: ${{ secrets.LANGCHAIN_API_KEY }} 6 | LANGCHAIN_API_KEY_PUB: ${{ secrets.LANGCHAIN_API_KEY_PUB }} 7 | LANGCHAIN_HUB_API_KEY: ${{ secrets.LANGCHAIN_HUB_API_KEY }} 8 | LANGSMITH_PROJECT_ID: ${{ secrets.LANGSMITH_PROJECT_ID }} 9 | LANGCHAIN_PROJECT_ID_PUB: ${{ secrets.LANGCHAIN_PROJECT_ID_PUB }} 10 | LANGCHAIN_ENDPOINT: "https://api.smith.langchain.com" 11 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} 12 | 13 | jobs: 14 | test: 15 | runs-on: ubuntu-latest 16 | steps: [uses: fastai/workflows/nbdev-ci@master] 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _docs/ 2 | _proc/ 3 | nbs/_data/ 4 | !nbs/shiny_example/_data/sample_data.pkl 5 | _data/ 6 | 7 | *.bak 8 | .gitattributes 9 | .last_checked 10 | .gitconfig 11 | *.bak 12 | *.log 13 | *~ 14 | ~* 15 | _tmp* 16 | tmp* 17 | tags 18 | *.pkg 19 | 20 | # Byte-compiled / optimized / DLL files 21 | __pycache__/ 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | env/ 31 | build/ 32 | develop-eggs/ 33 | dist/ 34 | downloads/ 35 | eggs/ 36 | .eggs/ 37 | lib/ 38 | lib64/ 39 | parts/ 40 | sdist/ 41 | var/ 42 | wheels/ 43 | *.egg-info/ 44 | .installed.cfg 45 | *.egg 46 | 47 | # PyInstaller 48 | # Usually these files are written by a python script from a template 49 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 50 | *.manifest 51 | *.spec 52 | 53 | # Installer logs 54 | pip-log.txt 55 | pip-delete-this-directory.txt 56 | 57 | # Unit test / coverage reports 58 | htmlcov/ 59 | .tox/ 60 | .coverage 61 | .coverage.* 62 | .cache 63 | nosetests.xml 64 | coverage.xml 65 | *.cover 66 | .hypothesis/ 67 | 68 | # Translations 69 | *.mo 70 | *.pot 71 | 72 | # Django stuff: 73 | *.log 74 | local_settings.py 75 | 76 | # Flask stuff: 77 | instance/ 78 | .webassets-cache 79 | 80 | # Scrapy stuff: 81 | .scrapy 82 | 83 | # Sphinx documentation 84 | docs/_build/ 85 | 86 | # PyBuilder 87 | target/ 88 | 89 | # Jupyter Notebook 90 | .ipynb_checkpoints 91 | 92 | # pyenv 93 | .python-version 94 | 95 | # celery beat schedule file 96 | celerybeat-schedule 97 | 98 | # SageMath parsed files 99 | *.sage.py 100 | 101 | # dotenv 102 | .env 103 | 104 | # virtualenv 105 | .venv 106 | venv/ 107 | ENV/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyproject 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | 122 | .vscode 123 | *.swp 124 | 125 | # osx generated files 126 | .DS_Store 127 | .DS_Store? 128 | .Trashes 129 | ehthumbs.db 130 | Thumbs.db 131 | .idea 132 | 133 | # pytest 134 | .pytest_cache 135 | 136 | # tools/trust-doc-nbs 137 | docs_src/.last_checked 138 | 139 | # symlinks to fastai 140 | docs_src/fastai 141 | tools/fastai 142 | 143 | # link checker 144 | checklink/cookies.txt 145 | 146 | # .gitconfig is now autogenerated 147 | .gitconfig 148 | 149 | # Quarto installer 150 | .deb 151 | .pkg 152 | 153 | # Quarto 154 | .quarto 155 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ## How to get started 4 | 5 | Before anything else, please install the git hooks that run automatic scripts during each commit and merge to strip the notebooks of superfluous metadata (and avoid merge conflicts). After cloning the repository, run the following command inside it: 6 | ``` 7 | nbdev_install_hooks 8 | ``` 9 | 10 | ## Did you find a bug? 11 | 12 | * Ensure the bug was not already reported by searching on GitHub under Issues. 13 | * If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring. 14 | * Be sure to add the complete error messages. 15 | 16 | #### Did you write a patch that fixes a bug? 17 | 18 | * Open a new GitHub pull request with the patch. 19 | * Ensure that your PR includes a test that fails without your patch, and pass with it. 20 | * Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. 21 | 22 | ## PR submission guidelines 23 | 24 | * Keep each PR focused. While it's more convenient, do not combine several unrelated fixes together. Create as many branches as needing to keep each PR focused. 25 | * Do not mix style changes/fixes with "functional" changes. It's very difficult to review such PRs and it most likely get rejected. 26 | * Do not add/remove vertical whitespace. Preserve the original style of the file you edit as much as you can. 27 | * Do not turn an already submitted PR into your development playground. If after you submitted PR, you discovered that more work is needed - close the PR, do the required work and then submit a new PR. Otherwise each of your commits requires attention from maintainers of the project. 28 | * If, however, you submitted a PR and received a request for changes, you should proceed with commits inside that PR, so that the maintainer can see the incremental fixes and won't need to review the whole PR again. In the exception case where you realize it'll take many many commits to complete the requests, then it's probably best to close the PR, do the work and then submit it again. Use common sense where you'd choose one way over another. 29 | 30 | ## Do you want to contribute to the documentation? 31 | 32 | * Docs are automatically created from the notebooks in the nbs folder. 33 | 34 | -------------------------------------------------------------------------------- /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 2022, fastai 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include settings.ini 2 | include LICENSE 3 | include CONTRIBUTING.md 4 | include README.md 5 | recursive-exclude * __pycache__ 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # langfree 2 | 3 | 4 | 5 | 6 | [![](https://github.com/parlance-labs/langfree/actions/workflows/test.yaml/badge.svg)](https://github.com/parlance-labs/langfree/actions/workflows/test.yaml) 7 | [![Deploy to GitHub 8 | Pages](https://github.com/parlance-labs/langfree/actions/workflows/deploy.yaml/badge.svg)](https://github.com/parlance-labs/langfree/actions/workflows/deploy.yaml) 9 | 10 | `langfree` helps you extract, transform and curate 11 | [ChatOpenAI](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) 12 | runs from 13 | [traces](https://js.langchain.com/docs/modules/agents/how_to/logging_and_tracing) 14 | stored in [LangSmith](https://www.langchain.com/langsmith), which can be 15 | used for fine-tuning and evaluation. 16 | 17 | ![](https://github.com/parlance-labs/langfree/assets/1483922/0e37d5a4-1ffb-4661-85ba-7c9eb80dd06b.png) 18 | 19 | ### Motivation 20 | 21 | Langchain has native [tracing 22 | support](https://blog.langchain.dev/tracing/) that allows you to log 23 | runs. This data is a valuable resource for fine-tuning and evaluation. 24 | [LangSmith](https://docs.smith.langchain.com/) is a commercial 25 | application that facilitates some of these tasks. 26 | 27 | However, LangSmith may not suit everyone’s needs. It is often desirable 28 | to buid your own data inspection and curation infrastructure: 29 | 30 | > One pattern I noticed is that great AI researchers are willing to 31 | > manually inspect lots of data. And more than that, **they build 32 | > infrastructure that allows them to manually inspect data quickly.** 33 | > Though not glamorous, manually examining data gives valuable 34 | > intuitions about the problem. The canonical example here is Andrej 35 | > Karpathy doing the ImageNet 2000-way classification task himself. 36 | > 37 | > – [Jason Wei, AI Researcher at 38 | > OpenAI](https://x.com/_jasonwei/status/1708921475829481683?s=20) 39 | 40 | `langfree` helps you export data from LangSmith and build data curation 41 | tools. By building you own data curation tools, so you can add features 42 | you need like: 43 | 44 | - connectivity to data sources beyond LangSmith. 45 | - customized data transformations of runs. 46 | - ability to route, tag and annotate data in special ways. 47 | - … etc. 48 | 49 | Furthermore,`langfree` provides a handful of [Shiny for 50 | Python](04_shiny.ipynb) components ease the process of creating data 51 | curation applications. 52 | 53 | ## Install 54 | 55 | ``` sh 56 | pip install langfree 57 | ``` 58 | 59 | ## How to use 60 | 61 | See the [docs site](http://langfree.parlance-labs.com/). 62 | 63 | ### Get runs from LangSmith 64 | 65 | The [runs](01_runs.ipynb) module contains some utilities to quickly get 66 | runs. We can get the recent runs from langsmith like so: 67 | 68 | ``` python 69 | from langfree.runs import get_recent_runs 70 | runs = get_recent_runs(last_n_days=3, limit=5) 71 | ``` 72 | 73 | Fetching runs with this filter: and(eq(status, "success"), gte(start_time, "11/03/2023"), lte(start_time, "11/07/2023")) 74 | 75 | ``` python 76 | print(f'Fetched {len(list(runs))} runs') 77 | ``` 78 | 79 | Fetched 5 runs 80 | 81 | There are other utlities like 82 | [`get_runs_by_commit`](https://parlance-labs.github.io/langfree/runs.html#get_runs_by_commit) 83 | if you are tagging runs by commit SHA. You can also use the [langsmith 84 | sdk](https://docs.smith.langchain.com/) to get runs. 85 | 86 | ### Parse The Data 87 | 88 | [`ChatRecordSet`](https://parlance-labs.github.io/langfree/chatrecord.html#chatrecordset) 89 | parses the LangChain run in the following ways: 90 | 91 | - finds the last child run that calls the language model (`ChatOpenAI`) 92 | in the chain where the run resides. You are often interested in the 93 | last call to the language model in the chain when curating data for 94 | fine tuning. 95 | - extracts the inputs, outputs and function definitions that are sent to 96 | the language model. 97 | - extracts other metadata that influences the run, such as the model 98 | version and parameters. 99 | 100 | ``` python 101 | from langfree.chatrecord import ChatRecordSet 102 | llm_data = ChatRecordSet.from_runs(runs) 103 | ``` 104 | 105 | Inspect Data 106 | 107 | ``` python 108 | llm_data[0].child_run.inputs[0] 109 | ``` 110 | 111 | {'role': 'system', 112 | 'content': "You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\nThe current time is 2023-09-05 16:49:07.308007.\n\nRelevant documents will be retrieved in the following messages."} 113 | 114 | ``` python 115 | llm_data[0].child_run.output 116 | ``` 117 | 118 | {'role': 'assistant', 119 | 'content': "Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\n\n1. Read the runs from the source organization using the SDK.\n2. Write the runs to the destination organization using the SDK.\n\nBy following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\n\nIf you have any further questions or need assistance, please reach out to us at support@langchain.dev."} 120 | 121 | You can also see a flattened version of the input and the output 122 | 123 | ``` python 124 | print(llm_data[0].flat_input[:200]) 125 | ``` 126 | 127 | ### System 128 | 129 | You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models. 130 | T 131 | 132 | ``` python 133 | print(llm_data[0].flat_output[:200]) 134 | ``` 135 | 136 | ### Assistant 137 | 138 | Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Her 139 | 140 | ### Transform The Data 141 | 142 | Perform data augmentation by rephrasing the first human input. Here is 143 | the first human input before data augmentation: 144 | 145 | ``` python 146 | run = llm_data[0].child_run 147 | [x for x in run.inputs if x['role'] == 'user'] 148 | ``` 149 | 150 | [{'role': 'user', 151 | 'content': 'How do I move my project between organizations?'}] 152 | 153 | Update the inputs: 154 | 155 | ``` python 156 | from langfree.transform import reword_input 157 | run.inputs = reword_input(run.inputs) 158 | ``` 159 | 160 | rephrased input as: How can I transfer my project from one organization to another? 161 | 162 | Check that the inputs are updated correctly: 163 | 164 | ``` python 165 | [x for x in run.inputs if x['role'] == 'user'] 166 | ``` 167 | 168 | [{'role': 'user', 169 | 'content': 'How can I transfer my project from one organization to another?'}] 170 | 171 | You can also call `.to_dicts()` to convert `llm_data` to a list of dicts 172 | that can be converted to jsonl for fine-tuning OpenAI models. 173 | 174 | ``` python 175 | llm_dicts = llm_data.to_dicts() 176 | print(llm_dicts[0].keys(), len(llm_dicts)) 177 | ``` 178 | 179 | dict_keys(['functions', 'messages']) 5 180 | 181 | You can use 182 | [`write_to_jsonl`](https://parlance-labs.github.io/langfree/transform.html#write_to_jsonl) 183 | and 184 | [`validate_jsonl`](https://parlance-labs.github.io/langfree/transform.html#validate_jsonl) 185 | to help write this data to `.jsonl` and validate it. 186 | 187 | ## Build & Customize Tools For Curating LLM Data 188 | 189 | The previous steps showed you how to collect and transform your data 190 | from LangChain runs. Next, you can feed this data into a tool to help 191 | you curate this data for fine tuning. 192 | 193 | To learn how to run and customize this kind of tool, [read the 194 | tutorial](tutorials/shiny.ipynb). `langfree` can help you quickly build 195 | something that looks like this: 196 | 197 | ![](https://github.com/parlance-labs/langfree/assets/1483922/57d98336-d43f-432b-a730-e41261168cb2.png) 198 | 199 | ## Documentation 200 | 201 | See the [docs site](http://langfree.parlance-labs.com/). 202 | 203 | ## FAQ 204 | 205 | 1. **We don’t use LangChain. Can we still use something from this 206 | library?** No, not directly. However, we recommend looking at how 207 | the [Shiny for Python App works](tutorials/shiny.ipynb) so you can 208 | adapt it towards your own use cases. 209 | 210 | 2. **Why did you use [Shiny For Python](https://shiny.posit.co/py/)?** 211 | Python has many great front-end libraries like Gradio, Streamlit, 212 | Panel and others. However, we liked Shiny For Python the best, 213 | because of its reactive model, modularity, strong integration with 214 | [Quarto](https://quarto.org/), and [WASM 215 | support](https://shiny.posit.co/py/docs/shinylive.html). You can 216 | read more about it 217 | [here](https://shiny.posit.co/py/docs/overview.html). 218 | 219 | 3. **Does this only work with runs from LangChain/LangSmith?** Yes, 220 | `langfree` has only been tested with `LangChain` runs that have been 221 | logged to`LangSmith`, however we suspect that you could log your 222 | traces elsewhere and pull them in a similar manner. 223 | 224 | 4. **Does this only work with 225 | [`ChatOpenAI`](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) 226 | runs?** A: Yes, `langfree` is opinionated and only works with runs 227 | that use chat models from OpenAI (which use 228 | [`ChatOpenAI`](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) 229 | in LangChain). We didn’t want to over-generalize this tool too 230 | quickly and started with the most popular combination of things. 231 | 232 | 5. **Do you offer support?**: These tools are free and licensed under 233 | [Apache 234 | 2.0](https://github.com/parlance-labs/langfree/blob/main/LICENSE). 235 | If you want support or customization, feel free to [reach out to 236 | us](https://parlance-labs.com/). 237 | 238 | ## Contributing 239 | 240 | This library was created with [nbdev](https://nbdev.fast.ai/). See 241 | [Contributing.md](https://github.com/parlance-labs/langfree/blob/main/CONTRIBUTING.md) 242 | for further guidelines. 243 | -------------------------------------------------------------------------------- /langfree/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.32" 2 | -------------------------------------------------------------------------------- /langfree/_modidx.py: -------------------------------------------------------------------------------- 1 | # Autogenerated by nbdev 2 | 3 | d = { 'settings': { 'branch': 'main', 4 | 'doc_baseurl': '/langfree', 5 | 'doc_host': 'https://parlance-labs.github.io', 6 | 'git_url': 'https://github.com/parlance-labs/langfree', 7 | 'lib_path': 'langfree'}, 8 | 'syms': { 'langfree.chatrecord': { 'langfree.chatrecord.ChatRecord': ('chatrecord.html#chatrecord', 'langfree/chatrecord.py'), 9 | 'langfree.chatrecord.ChatRecord.flat_input': ( 'chatrecord.html#chatrecord.flat_input', 10 | 'langfree/chatrecord.py'), 11 | 'langfree.chatrecord.ChatRecord.flat_output': ( 'chatrecord.html#chatrecord.flat_output', 12 | 'langfree/chatrecord.py'), 13 | 'langfree.chatrecord.ChatRecord.from_run': ( 'chatrecord.html#chatrecord.from_run', 14 | 'langfree/chatrecord.py'), 15 | 'langfree.chatrecord.ChatRecord.from_run_id': ( 'chatrecord.html#chatrecord.from_run_id', 16 | 'langfree/chatrecord.py'), 17 | 'langfree.chatrecord.ChatRecordSet': ('chatrecord.html#chatrecordset', 'langfree/chatrecord.py'), 18 | 'langfree.chatrecord.ChatRecordSet.__getitem__': ( 'chatrecord.html#chatrecordset.__getitem__', 19 | 'langfree/chatrecord.py'), 20 | 'langfree.chatrecord.ChatRecordSet.__iter__': ( 'chatrecord.html#chatrecordset.__iter__', 21 | 'langfree/chatrecord.py'), 22 | 'langfree.chatrecord.ChatRecordSet.__len__': ( 'chatrecord.html#chatrecordset.__len__', 23 | 'langfree/chatrecord.py'), 24 | 'langfree.chatrecord.ChatRecordSet.__repr__': ( 'chatrecord.html#chatrecordset.__repr__', 25 | 'langfree/chatrecord.py'), 26 | 'langfree.chatrecord.ChatRecordSet.from_commit': ( 'chatrecord.html#chatrecordset.from_commit', 27 | 'langfree/chatrecord.py'), 28 | 'langfree.chatrecord.ChatRecordSet.from_run_ids': ( 'chatrecord.html#chatrecordset.from_run_ids', 29 | 'langfree/chatrecord.py'), 30 | 'langfree.chatrecord.ChatRecordSet.from_runs': ( 'chatrecord.html#chatrecordset.from_runs', 31 | 'langfree/chatrecord.py'), 32 | 'langfree.chatrecord.ChatRecordSet.load': ( 'chatrecord.html#chatrecordset.load', 33 | 'langfree/chatrecord.py'), 34 | 'langfree.chatrecord.ChatRecordSet.save': ( 'chatrecord.html#chatrecordset.save', 35 | 'langfree/chatrecord.py'), 36 | 'langfree.chatrecord.ChatRecordSet.to_dicts': ( 'chatrecord.html#chatrecordset.to_dicts', 37 | 'langfree/chatrecord.py'), 38 | 'langfree.chatrecord.ChatRecordSet.to_pandas': ( 'chatrecord.html#chatrecordset.to_pandas', 39 | 'langfree/chatrecord.py'), 40 | 'langfree.chatrecord.NoChatOpenAI': ('chatrecord.html#nochatopenai', 'langfree/chatrecord.py'), 41 | 'langfree.chatrecord.NoChatOpenAI.__init__': ( 'chatrecord.html#nochatopenai.__init__', 42 | 'langfree/chatrecord.py'), 43 | 'langfree.chatrecord.get_child_chat_run': ( 'chatrecord.html#get_child_chat_run', 44 | 'langfree/chatrecord.py'), 45 | 'langfree.chatrecord.get_nested_child_run': ( 'chatrecord.html#get_nested_child_run', 46 | 'langfree/chatrecord.py')}, 47 | 'langfree.runs': { 'langfree.runs._ischatopenai': ('runs.html#_ischatopenai', 'langfree/runs.py'), 48 | 'langfree.runs._temp_env_var': ('runs.html#_temp_env_var', 'langfree/runs.py'), 49 | 'langfree.runs.check_api_key': ('runs.html#check_api_key', 'langfree/runs.py'), 50 | 'langfree.runs.get_feedback': ('runs.html#get_feedback', 'langfree/runs.py'), 51 | 'langfree.runs.get_functions': ('runs.html#get_functions', 'langfree/runs.py'), 52 | 'langfree.runs.get_last_child': ('runs.html#get_last_child', 'langfree/runs.py'), 53 | 'langfree.runs.get_params': ('runs.html#get_params', 'langfree/runs.py'), 54 | 'langfree.runs.get_recent_commit_tags': ('runs.html#get_recent_commit_tags', 'langfree/runs.py'), 55 | 'langfree.runs.get_recent_runs': ('runs.html#get_recent_runs', 'langfree/runs.py'), 56 | 'langfree.runs.get_runs_by_commit': ('runs.html#get_runs_by_commit', 'langfree/runs.py'), 57 | 'langfree.runs.reformat_date': ('runs.html#reformat_date', 'langfree/runs.py'), 58 | 'langfree.runs.take': ('runs.html#take', 'langfree/runs.py')}, 59 | 'langfree.shiny': { 'langfree.shiny._get_content': ('shiny.html#_get_content', 'langfree/shiny.py'), 60 | 'langfree.shiny._get_role': ('shiny.html#_get_role', 'langfree/shiny.py'), 61 | 'langfree.shiny.invoke_later': ('shiny.html#invoke_later', 'langfree/shiny.py'), 62 | 'langfree.shiny.render_funcs': ('shiny.html#render_funcs', 'langfree/shiny.py'), 63 | 'langfree.shiny.render_input_chat': ('shiny.html#render_input_chat', 'langfree/shiny.py'), 64 | 'langfree.shiny.render_llm_output': ('shiny.html#render_llm_output', 'langfree/shiny.py')}, 65 | 'langfree.transform': { 'langfree.transform.RunData': ('transform.html#rundata', 'langfree/transform.py'), 66 | 'langfree.transform.RunData._flatten_data': ( 'transform.html#rundata._flatten_data', 67 | 'langfree/transform.py'), 68 | 'langfree.transform.RunData.flat_input': ('transform.html#rundata.flat_input', 'langfree/transform.py'), 69 | 'langfree.transform.RunData.flat_output': ( 'transform.html#rundata.flat_output', 70 | 'langfree/transform.py'), 71 | 'langfree.transform.RunData.from_run_id': ( 'transform.html#rundata.from_run_id', 72 | 'langfree/transform.py'), 73 | 'langfree.transform.RunData.outputs': ('transform.html#rundata.outputs', 'langfree/transform.py'), 74 | 'langfree.transform.RunData.to_json': ('transform.html#rundata.to_json', 'langfree/transform.py'), 75 | 'langfree.transform.RunData.to_msg_dict': ( 'transform.html#rundata.to_msg_dict', 76 | 'langfree/transform.py'), 77 | 'langfree.transform.chat': ('transform.html#chat', 'langfree/transform.py'), 78 | 'langfree.transform.fetch_run_componets': ( 'transform.html#fetch_run_componets', 79 | 'langfree/transform.py'), 80 | 'langfree.transform.validate_jsonl': ('transform.html#validate_jsonl', 'langfree/transform.py'), 81 | 'langfree.transform.write_to_jsonl': ('transform.html#write_to_jsonl', 'langfree/transform.py')}}} 82 | -------------------------------------------------------------------------------- /langfree/chatrecord.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_chatrecord.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['NoChatOpenAI', 'get_nested_child_run', 'get_child_chat_run', 'ChatRecord', 'ChatRecordSet'] 5 | 6 | # %% ../nbs/03_chatrecord.ipynb 3 7 | from typing import List, Iterable, Union 8 | from collections import Counter 9 | from pathlib import Path 10 | import pickle 11 | 12 | import pandas as pd 13 | from pydantic import BaseModel 14 | import langsmith 15 | from fastcore.foundation import first, L 16 | from fastcore.test import test_eq 17 | from .runs import (get_runs_by_commit, 18 | get_params, get_functions, 19 | get_feedback) 20 | from .transform import RunData 21 | from langsmith import Client 22 | 23 | # %% ../nbs/03_chatrecord.ipynb 5 24 | class NoChatOpenAI(Exception): 25 | def __init__(self, message, extra_data=None): 26 | super().__init__(message) 27 | 28 | # %% ../nbs/03_chatrecord.ipynb 6 29 | def get_nested_child_run(run): 30 | "Get the last nested `ChatOpenAI` run inside a Runnable Agent." 31 | client = Client() 32 | run = client.read_run(run_id=run.id, load_child_runs=True) 33 | oai_children = [] 34 | for r in run.child_runs: 35 | if r.name == 'RunnableAgent': 36 | for c in r.child_runs: 37 | if c.name == 'ChatOpenAI': 38 | oai_children.append(c) 39 | if r.name == 'ChatOpenAI': 40 | oai_children.append(r) 41 | if not oai_children: 42 | raise NoChatOpenAI(f'Not able to find ChatOpenAI child run from root run {run.id}') 43 | return oai_children[-1] 44 | 45 | def get_child_chat_run(run): 46 | "Get the last child `ChatOpenAI` run." 47 | client = Client() 48 | if run.parent_run_id is not None: 49 | # if run.execution_order != 1: # this is a child run, get the parent 50 | run = client.read_run(run.parent_run_id) 51 | 52 | crun = get_nested_child_run(run) 53 | return run, crun 54 | 55 | # %% ../nbs/03_chatrecord.ipynb 9 56 | class ChatRecord(BaseModel): 57 | "A parsed run from LangSmith, focused on the `ChatOpenAI` run type." 58 | child_run_id:str 59 | child_run:RunData 60 | child_url:Union[str,None] = None 61 | parent_run_id:Union[str,None] = None 62 | parent_url: Union[str,None] = None 63 | total_tokens:Union[int, None] 64 | prompt_tokens:Union[int, None] 65 | completion_tokens:Union[int, None] 66 | feedback: Union[List,None] = None 67 | feedback_keys: Union[List,None] = None 68 | tags: Union[List,None] = [] 69 | start_dt: Union[str, None] = None 70 | function_defs: Union[List,None] = None 71 | param_model_name: Union[str,None]= None 72 | param_n: Union[int, None] = None 73 | param_top_p: Union[int, None] = None 74 | param_temp: Union[int, None] = None 75 | param_presence_penalty: Union[int, None] = None 76 | param_freq_penalty: Union[int, None] = None 77 | 78 | @property 79 | def flat_input(self): return self.child_run.flat_input 80 | 81 | @property 82 | def flat_output(self): return self.child_run.flat_output 83 | 84 | @classmethod 85 | def from_run_id(cls, 86 | run_id:str # the run id to fetch and parse. 87 | ): 88 | "Collect information About A Run into a `ChatRecord`." 89 | client = Client() 90 | return cls.from_run(client.read_run(run_id=run_id)) 91 | 92 | @classmethod 93 | def from_run(cls, 94 | run:langsmith.schemas.Run # the run object to parse. 95 | ): 96 | "Collect information About A Run into a `ChatRecord`." 97 | run, crun = get_child_chat_run(run) 98 | 99 | if crun: 100 | params = get_params(crun) 101 | _feedback = get_feedback(run) # you must get feedback from the root 102 | 103 | return cls(child_run_id=str(crun.id), 104 | child_run=RunData.from_run_id(str(crun.id)), 105 | child_url=crun.url, 106 | parent_run_id=str(run.id) if run else None, 107 | parent_url=run.url if run else None, 108 | total_tokens=crun.total_tokens, 109 | prompt_tokens=crun.prompt_tokens, 110 | completion_tokens=crun.completion_tokens, 111 | feedback=_feedback, 112 | feedback_keys=list(L(_feedback).attrgot('key').filter()), 113 | tags=run.tags, 114 | start_dt=run.start_time.strftime('%m/%d/%Y'), 115 | function_defs=get_functions(crun), 116 | **params) 117 | 118 | # %% ../nbs/03_chatrecord.ipynb 19 119 | class ChatRecordSet(BaseModel): 120 | "A List of `ChatRecord`." 121 | records: List[ChatRecord] 122 | 123 | @classmethod 124 | def from_commit(cls, commit_id:str, limit:int=None): 125 | "Create a `ChatRecordSet` from a commit id" 126 | _runs = get_runs_by_commit(commit_id=commit_id, limit=limit) 127 | return cls.from_runs(_runs) 128 | 129 | @classmethod 130 | def from_runs(cls, runs:List[langsmith.schemas.Run]): 131 | "Load ChatRecordSet from runs." 132 | _records = [] 133 | for r in runs: 134 | try: _records.append(ChatRecord.from_run(r)) 135 | except NoChatOpenAI as e: print(e) 136 | return cls(records=_records) 137 | 138 | @classmethod 139 | def from_run_ids(cls, runs:List[str]): 140 | "Load ChatRecordSet from run ids." 141 | _records = [] 142 | for r in runs: 143 | try: _records.append(ChatRecord.from_run_id(r)) 144 | except NoChatOpenAI as e: print(e) 145 | return cls(records=_records) 146 | 147 | def __len__(self): return len(self.records) 148 | 149 | def __getitem__(self, index: int) -> ChatRecord: 150 | return self.records[index] 151 | 152 | def __repr__(self): 153 | return f'`List[ChatRecord]` of size {len(self.records)}.' 154 | 155 | def save(self, path:str): 156 | "Save data to disk." 157 | dest_path = Path(path) 158 | if not dest_path.parent.exists(): dest_path.parent.mkdir(exist_ok=True) 159 | with open(dest_path, 'wb') as f: 160 | pickle.dump(self, f) 161 | return dest_path 162 | 163 | def __iter__(self): 164 | for r in self.records: 165 | yield r 166 | 167 | @classmethod 168 | def load(cls, path:str): 169 | "Load data from disk." 170 | src_path = Path(path) 171 | with open(src_path, 'rb') as f: 172 | obj = pickle.load(f) 173 | if isinstance(obj, cls): 174 | return obj 175 | else: 176 | raise TypeError(f"The loaded object is not of type {cls.__name__}") 177 | 178 | def to_pandas(self): 179 | "Convert the `ChatRecordSet` to a pandas.DataFrame." 180 | records = L(self.records).map(dict) 181 | return pd.DataFrame(records) 182 | 183 | def to_dicts(self): 184 | "Convert the ChatRecordSet to a list of dicts, which you can convert to jsonl." 185 | return list(L(self.records).map(lambda x: x.child_run.to_msg_dict())) 186 | -------------------------------------------------------------------------------- /langfree/runs.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_runs.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['client', 'check_api_key', 'reformat_date', 'take', 'get_runs_by_commit', 'get_last_child', 'get_recent_runs', 5 | 'get_recent_commit_tags', 'get_params', 'get_functions', 'get_feedback'] 6 | 7 | # %% ../nbs/01_runs.ipynb 3 8 | from collections import defaultdict 9 | import os 10 | from datetime import date, timedelta, datetime 11 | from itertools import islice 12 | from typing import List, Iterable 13 | from pprint import pformat 14 | from contextlib import contextmanager 15 | 16 | import pandas as pd 17 | from langchain.load import load 18 | import langsmith 19 | from langsmith import Client 20 | from fastcore.foundation import L, first 21 | 22 | # %% ../nbs/01_runs.ipynb 4 23 | @contextmanager 24 | def _temp_env_var(vars_dict): 25 | "Temporarily set environment variables (for testing)" 26 | original_values = {name: os.environ.get(name) for name in vars_dict.keys()} 27 | 28 | # Set temporary values 29 | for name, value in vars_dict.items(): 30 | os.environ[name] = value 31 | 32 | try: 33 | yield 34 | finally: 35 | # Revert changes after block execution 36 | for name, original_value in original_values.items(): 37 | if original_value is None: 38 | del os.environ[name] 39 | else: 40 | os.environ[name] = original_value 41 | 42 | # %% ../nbs/01_runs.ipynb 5 43 | def check_api_key(nm="LANGCHAIN_HUB_API_KEY"): 44 | val = os.getenv(nm) 45 | if not val: raise Exception(f"You must set the environment variable {nm}") 46 | return val 47 | 48 | # %% ../nbs/01_runs.ipynb 6 49 | check_api_key("LANGCHAIN_API_KEY") 50 | check_api_key("LANGCHAIN_ENDPOINT") 51 | check_api_key("LANGSMITH_PROJECT_ID") 52 | client = Client() 53 | 54 | # %% ../nbs/01_runs.ipynb 8 55 | def reformat_date(date_str): 56 | "Reformat m/d/y to YYYY-MM-DD." 57 | date_obj = datetime.strptime(date_str, '%m/%d/%Y') # Parsing the date 58 | formatted_date = date_obj.strftime('%Y-%m-%d') # Formatting to YYYY-MM-DD 59 | return formatted_date 60 | 61 | # %% ../nbs/01_runs.ipynb 10 62 | def take(l:Iterable, n:int): 63 | "Take first n entries from a generator" 64 | return L(islice(l, n)) 65 | 66 | # %% ../nbs/01_runs.ipynb 11 67 | def get_runs_by_commit(commit_id:str=None, # The commit ID to filter by 68 | proj_id:str=None, # Langsmith Project ID 69 | only_success=True, # Only include runs that are successfull 70 | run_type='chain', # The run type 71 | start_dt:str=None, # The start date to filter by 72 | end_dt:str=None, # the end date to filter by 73 | limit:int=None # The maximum number of runs to return 74 | ): 75 | "Get all runs tagged with a particular commit id (the short version of the SHA) in LangSmith." 76 | 77 | if start_dt: start_dt=reformat_date(start_dt) 78 | if end_dt: end_dt=reformat_date(end_dt) 79 | 80 | success_query='eq(status, "success")' if only_success else '' 81 | commit_query = f'has(tags, "commit:{commit_id}")' if commit_id else '' 82 | proj_id = check_api_key("LANGSMITH_PROJECT_ID") if not proj_id else proj_id 83 | time_query='' 84 | 85 | if start_dt: 86 | time_query=f'gte(start_time, "{start_dt}")' 87 | if end_dt: 88 | time_query = f'{time_query}, lte(start_time, "{end_dt}")' 89 | 90 | queries = ', '.join(L([success_query, commit_query, time_query]).filter()) 91 | query_string = None if not queries else f'and({queries})' 92 | if query_string: print(f'Fetching runs with this filter: {query_string}') 93 | 94 | client = Client() 95 | runs = client.list_runs( 96 | filter=query_string, 97 | project_id=proj_id, 98 | execution_order=1, # this gets the root runs 99 | error=False, 100 | run_type=run_type, 101 | ) 102 | return list(runs) if limit is None else take(runs, limit) 103 | 104 | # %% ../nbs/01_runs.ipynb 15 105 | def get_last_child(runs: List[langsmith.schemas.Run]): 106 | "Get the child runs for a list of runs." 107 | return [client.read_run(r.child_run_ids[-1]) for r in runs if r.child_run_ids] 108 | 109 | # %% ../nbs/01_runs.ipynb 18 110 | def get_recent_runs(start_dt=None, end_dt=None, last_n_days=2, limit=None): 111 | "Get recent runs from Langsmith. If `start_dt` is None gets the `last_n_days`." 112 | client = Client() 113 | if start_dt is None: 114 | _runs = client.list_runs(project_id=check_api_key("LANGSMITH_PROJECT_ID"), limit=1) 115 | latest_run_dt = first(_runs).start_time 116 | start_dt_obj = latest_run_dt - timedelta(days=last_n_days) 117 | else: 118 | start_dt_obj = datetime.strptime(start_dt, '%m/%d/%Y') 119 | 120 | if end_dt is None: 121 | if start_dt is None: 122 | end_dt_obj = start_dt_obj + timedelta(days=last_n_days+1) # their logic is off lte is really lt 123 | else: 124 | end_dt_obj = datetime.strptime(start_dt, '%m/%d/%Y') + timedelta(days=last_n_days+1) # their logic is off lte is really lt 125 | else: 126 | if start_dt is None: 127 | raise ValueError("end_dt should only be provided if start_dt is provided.") 128 | end_dt_obj = datetime.strptime(end_dt, '%m/%d/%Y') 129 | 130 | 131 | runs = get_runs_by_commit(start_dt=start_dt_obj.strftime('%m/%d/%Y'), 132 | end_dt=end_dt_obj.strftime('%m/%d/%Y')) 133 | return list(runs) if limit is None else take(runs, limit) 134 | 135 | # %% ../nbs/01_runs.ipynb 21 136 | def get_recent_commit_tags(start_dt=None, end_dt=None, last_n_days=2, return_df=False): 137 | "Print a table of recent commit SHAs from Langsmith along with their counts that you can filter on" 138 | runs = L(get_recent_runs(start_dt=start_dt, end_dt=end_dt, last_n_days=last_n_days)) 139 | data = runs.map(lambda x: {'start_dt': x.start_time.strftime('%m/%d/%Y'), 140 | 'commit': first([t.split('commit:')[-1] for t in x.tags if t.startswith('commit:')]) 141 | } 142 | ) 143 | if data: 144 | df = pd.DataFrame(data) 145 | agg = df.groupby(['start_dt']).value_counts().reset_index() 146 | agg = agg.rename(columns={0: 'count'}).sort_values(by=['start_dt', 'count'], ascending=False) 147 | if not return_df: 148 | print(agg.to_markdown(index=False)) 149 | else: 150 | return agg 151 | 152 | else: 153 | print(f'No commits found for {start_dt} - {end_dt}') 154 | return None 155 | 156 | # %% ../nbs/01_runs.ipynb 29 157 | def _ischatopenai(run): 158 | if run.name != 'ChatOpenAI': 159 | raise TypeError(f'Run: {run.id} is of type `{run.name}`, but can only parse `ChatOpenAI` runs.') 160 | 161 | # %% ../nbs/01_runs.ipynb 30 162 | def get_params(run:langsmith.schemas.Run) -> dict: 163 | "Get important parameters from a run logged in LangSmith" 164 | if 'invocation_params' in run.extra: 165 | p = run.extra['invocation_params'] 166 | return dict(param_model_name=p.get('model'), 167 | param_n=p.get('n'), 168 | param_top_p=p.get('top_p'), 169 | param_temp=p.get('temperature'), 170 | param_presence_penalty=p.get('presence_penalty'), 171 | param_freq_penalty=p.get('frequency_penalty') 172 | ) 173 | else: return {} 174 | 175 | # %% ../nbs/01_runs.ipynb 32 176 | def get_functions(run:langsmith.schemas.Run) -> List[dict]: 177 | "Get function definitions from a LangSmith run." 178 | if 'invocation_params' in run.extra: 179 | p = run.extra['invocation_params'] 180 | return p.get('functions', []) 181 | else: return [] 182 | 183 | # %% ../nbs/01_runs.ipynb 35 184 | def get_feedback(run:langsmith.schemas.Run) -> list: 185 | "Get feedback from a run if exists." 186 | raw = L(client.list_feedback(run_ids=[run.id])) 187 | return list(raw.map(lambda x: dict(key=x.key, 188 | score=x.score, 189 | value=x.value, 190 | comment=x.comment, 191 | correction=x.correction) 192 | ) 193 | ) 194 | -------------------------------------------------------------------------------- /langfree/shiny.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_shiny.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['render_input_chat', 'render_funcs', 'render_llm_output', 'invoke_later'] 5 | 6 | # %% ../nbs/04_shiny.ipynb 3 7 | import os, json 8 | from pprint import pformat 9 | from .transform import RunData 10 | from shiny import module, ui, render, reactive 11 | import shiny.experimental as x 12 | import asyncio 13 | 14 | # %% ../nbs/04_shiny.ipynb 5 15 | def _get_role(m): 16 | role = m['role'].upper() 17 | if 'function_call' in m: return f"{role} - Function Call" 18 | if role == 'FUNCTION': return 'FUNCTION RESULTS' 19 | else: return role 20 | 21 | def _get_content(m): 22 | if 'function_call' in m: 23 | func = m['function_call'] 24 | return f"{func['name']}({func['arguments']})" 25 | else: return m['content'] 26 | 27 | def render_input_chat(run:RunData, markdown=True): 28 | "Render the chat history, except for the last output as a group of cards." 29 | cards = [] 30 | num_inputs = len(run.inputs) 31 | for i,m in enumerate(run.inputs): 32 | content = str(_get_content(m)) 33 | if _get_role(m) == 'FUNCTION RESULTS': 34 | try: content = '```json\n' + pformat(json.loads(content)) + '\n```' 35 | except: pass 36 | cards.append( 37 | ui.card( 38 | ui.card_header(ui.div({"style": "display: flex; justify-content: space-between;"}, 39 | ui.span( 40 | {"style": "font-weight: bold;"}, 41 | _get_role(m), 42 | ), 43 | ui.span(f'({i+1}/{num_inputs})'), 44 | ) 45 | ), 46 | x.ui.card_body(ui.markdown(content) if markdown else content), 47 | class_= "card border-dark mb-3" 48 | ) 49 | ) 50 | return ui.div(*cards) 51 | 52 | # %% ../nbs/04_shiny.ipynb 17 53 | def render_funcs(run:RunData, markdown=True): 54 | "Render functions as a group of cards." 55 | cards = [] 56 | if run.funcs: 57 | num_inputs = len(run.funcs) 58 | for i,m in enumerate(run.funcs): 59 | nm = m.get('name', '') 60 | desc = m.get('description', '') 61 | content = json.dumps(m.get('parameters', ''), indent=4) 62 | cards.append( 63 | ui.card( 64 | ui.card_header(ui.div({"style": "display: flex; justify-content: space-between;"}, 65 | ui.span( 66 | {"style": "font-weight: bold;"}, 67 | nm, 68 | ), 69 | ui.span(f'({i+1}/{num_inputs})'), 70 | ) 71 | ), 72 | x.ui.card_body( 73 | ui.strong(f'Description: {desc}'), 74 | ui.markdown(content) if markdown else content 75 | ), 76 | class_= "card border-dark mb-3" 77 | ) 78 | ) 79 | return ui.div(*cards) 80 | 81 | # %% ../nbs/04_shiny.ipynb 24 82 | def render_llm_output(run, width="100%", height="250px"): 83 | "Render the LLM output as an editable text box." 84 | o = run.output 85 | return ui.input_text_area('llm_output', label=ui.h3('LLM Output (Editable)'), 86 | value=o['content'], width=width, height=height) 87 | 88 | # %% ../nbs/04_shiny.ipynb 28 89 | def invoke_later(delaySecs:int, callback:callable): 90 | "Execute code in a shiny app with a time delay of `delaySecs` asynchronously." 91 | async def delay_task(): 92 | await asyncio.sleep(delaySecs) 93 | async with reactive.lock(): 94 | callback() 95 | await reactive.flush() 96 | asyncio.create_task(delay_task()) 97 | -------------------------------------------------------------------------------- /langfree/transform.py: -------------------------------------------------------------------------------- 1 | # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_transform.ipynb. 2 | 3 | # %% auto 0 4 | __all__ = ['client', 'chat', 'fetch_run_componets', 'RunData', 'write_to_jsonl', 'validate_jsonl'] 5 | 6 | # %% ../nbs/02_transform.ipynb 3 7 | import os, copy, json 8 | import openai, langsmith 9 | from typing import List, Callable 10 | from random import shuffle 11 | from collections import defaultdict 12 | 13 | from .runs import _temp_env_var, Client, _ischatopenai 14 | from pydantic import BaseModel 15 | from langchain.adapters import openai as adapt 16 | from langchain.load import load 17 | from fastcore.foundation import L 18 | from tenacity import ( 19 | retry, 20 | stop_after_attempt, 21 | wait_random_exponential, 22 | ) # for exponential backoff 23 | 24 | 25 | # %% ../nbs/02_transform.ipynb 5 26 | client = openai.OpenAI() 27 | 28 | # %% ../nbs/02_transform.ipynb 6 29 | @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6)) 30 | def chat(**kwargs): 31 | "A wrapper around `openai.ChatCompletion` that has automatic retries." 32 | client.api_key = os.environ['OPENAI_API_KEY'] 33 | return client.chat.completions.create(**kwargs) 34 | 35 | # %% ../nbs/02_transform.ipynb 9 36 | def fetch_run_componets(run_id:str): 37 | "Return the `inputs`, `output` and `funcs` for a run of type `ChatOpenAI`." 38 | client = langsmith.Client() 39 | run = client.read_run(run_id) 40 | _ischatopenai(run) 41 | output = adapt.convert_message_to_dict(load(run.outputs['generations'][0]['message'])) 42 | inputs = [adapt.convert_message_to_dict(load(m)) for m in run.inputs['messages']] 43 | params = run.extra['invocation_params'] 44 | 45 | for inp in inputs: 46 | if 'function_call' in inp and inp.get('content', None) is None: 47 | del inp['content'] 48 | funcs = params.get("functions", []) 49 | return inputs, output, funcs 50 | 51 | # %% ../nbs/02_transform.ipynb 12 52 | class RunData(BaseModel): 53 | "Key components of a run from LangSmith" 54 | inputs:List[dict] 55 | output:dict 56 | funcs:List[dict] 57 | run_id:str 58 | 59 | @classmethod 60 | def from_run_id(cls, run_id:str): 61 | "Create a `RunData` object from a run id." 62 | inputs, output, funcs = fetch_run_componets(run_id) 63 | return cls(inputs=inputs, output=output, funcs=funcs, run_id=run_id) 64 | 65 | def to_msg_dict(self): 66 | "Transform the instance into a dict in the format that can be used for OpenAI fine-tuning." 67 | msgs = self.inputs + [self.output] 68 | return {"functions": self.funcs, 69 | "messages": msgs} 70 | 71 | def to_json(self): 72 | "The json version of `to_msg_dict`." 73 | return json.dumps(self.to_msg_dict()) 74 | 75 | @property 76 | def outputs(self): 77 | "Return outputs for langsmith Datasets compatibility." 78 | return self.output 79 | 80 | @property 81 | def flat_input(self): 82 | "The input to the LLM in markdown." 83 | return self._flatten_data(self.inputs) 84 | 85 | @property 86 | def flat_output(self): 87 | "The output of the LLM in markdown." 88 | return self._flatten_data([self.output]) 89 | 90 | @classmethod 91 | def _flatten_data(cls, data): 92 | "Produce a flattened view of the data as human readable Markdown." 93 | md_str = "" 94 | for item in data: 95 | # Heading 96 | role = item['role'] 97 | if role == 'assistant' and 'function_call' in item: 98 | role += ' - function call' 99 | if role == 'function': 100 | role += ' - results' 101 | 102 | md_str += f"### {role.title()}\n\n" 103 | 104 | content = item.get('content', '') 105 | if content: md_str += content + "\n" 106 | 107 | elif 'function_call' in item: 108 | func_name = item['function_call']['name'] 109 | args = json.loads(item['function_call']['arguments']) 110 | formatted_args = ', '.join([f"{k}={v}" for k, v in args.items()]) 111 | md_str += f"{func_name}({formatted_args})\n" 112 | md_str += "\n" 113 | return md_str 114 | 115 | # %% ../nbs/02_transform.ipynb 25 116 | def write_to_jsonl(data_list:List[RunData], filename:str): 117 | """ 118 | Writes a list of dictionaries to a .jsonl file. 119 | 120 | Parameters: 121 | - data_list (list of `RunData`): The data to be written. 122 | - filename (str): The name of the output file. 123 | """ 124 | shuffle(data_list) 125 | with open(filename, 'w') as f: 126 | for entry in data_list: 127 | f.write(f"{entry.to_json()}\n") 128 | 129 | # %% ../nbs/02_transform.ipynb 28 130 | def validate_jsonl(fname): 131 | "Code is modified from https://cookbook.openai.com/examples/chat_finetuning_data_prep, but updated for function calling." 132 | # Load the dataset 133 | with open(fname, 'r', encoding='utf-8') as f: 134 | dataset = [json.loads(line) for line in f] 135 | 136 | # Initial dataset stats 137 | print("Num examples:", len(dataset)) 138 | 139 | # Format error checks 140 | format_errors = defaultdict(int) 141 | 142 | for i, ex in enumerate(dataset): 143 | if not isinstance(ex, dict): 144 | format_errors["data_type"] += 1 145 | continue 146 | 147 | messages = ex.get("messages", None) 148 | if not messages: 149 | format_errors["missing_messages_list"] += 1 150 | continue 151 | 152 | for im, message in enumerate(messages): 153 | if "role" not in message or ("content" not in message and 'function_call' not in message): 154 | format_errors["message_missing_key"] += 1 155 | 156 | if any(k not in ("role", "content", "name", "function_call") for k in message): 157 | format_errors["message_unrecognized_key"] += 1 158 | print(f'message_unrecognized_key {[k for k in message.keys() if k not in ["role", "content", "name"]]} in row:{i} message {im}') 159 | 160 | if message.get("role", None) not in ("system", "user", "assistant", "function"): 161 | format_errors["unrecognized_role"] += 1 162 | print(f'unrecognized_role {message.get("role", None)} in row:{i} message {im}') 163 | 164 | content = message.get("content", None) 165 | if (not content or not isinstance(content, str)) and 'function_call' not in message: 166 | format_errors["missing_content"] += 1 167 | print(f'missing_content in row:{i} message {im}') 168 | 169 | if not any(message.get("role", None) == "assistant" for message in messages): 170 | format_errors["example_missing_assistant_message"] += 1 171 | 172 | if format_errors: 173 | print("Found errors:") 174 | for k, v in format_errors.items(): 175 | print(f"{k}: {v}") 176 | else: 177 | print("No errors found") 178 | -------------------------------------------------------------------------------- /nbs/01_runs.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "metadata": {}, 6 | "source": [ 7 | "---\n", 8 | "skip_showdoc: true\n", 9 | "skip_exec: true\n", 10 | "---" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "# runs\n", 18 | "\n", 19 | "> Get lang model runs from langsmith" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "#| default_exp runs" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "#|export\n", 38 | "from collections import defaultdict\n", 39 | "import os\n", 40 | "from datetime import date, timedelta, datetime\n", 41 | "from itertools import islice\n", 42 | "from typing import List, Iterable\n", 43 | "from pprint import pformat\n", 44 | "from contextlib import contextmanager\n", 45 | "\n", 46 | "import pandas as pd\n", 47 | "from langchain.load import load\n", 48 | "import langsmith\n", 49 | "from langsmith import Client\n", 50 | "from fastcore.foundation import L, first" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "#|export\n", 60 | "@contextmanager\n", 61 | "def _temp_env_var(vars_dict):\n", 62 | " \"Temporarily set environment variables (for testing)\"\n", 63 | " original_values = {name: os.environ.get(name) for name in vars_dict.keys()}\n", 64 | " \n", 65 | " # Set temporary values\n", 66 | " for name, value in vars_dict.items():\n", 67 | " os.environ[name] = value\n", 68 | " \n", 69 | " try:\n", 70 | " yield\n", 71 | " finally:\n", 72 | " # Revert changes after block execution\n", 73 | " for name, original_value in original_values.items():\n", 74 | " if original_value is None:\n", 75 | " del os.environ[name]\n", 76 | " else:\n", 77 | " os.environ[name] = original_value" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "#|export\n", 87 | "def check_api_key(nm=\"LANGCHAIN_HUB_API_KEY\"):\n", 88 | " val = os.getenv(nm)\n", 89 | " if not val: raise Exception(f\"You must set the environment variable {nm}\")\n", 90 | " return val" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "#|export\n", 100 | "#|hide\n", 101 | "check_api_key(\"LANGCHAIN_API_KEY\")\n", 102 | "check_api_key(\"LANGCHAIN_ENDPOINT\")\n", 103 | "check_api_key(\"LANGSMITH_PROJECT_ID\")\n", 104 | "client = Client()" 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "## Get Runs\n", 112 | "\n", 113 | "### Background \n", 114 | "\n", 115 | "Langsmith offers a convenient [python client](https://github.com/langchain-ai/langsmith-sdk) for retrieving runs. [The docs](https://docs.smith.langchain.com/tracing/use-cases/export-runs/local) go into further detail about the various options available. Some useful patterns to know are:\n", 116 | "\n", 117 | "Getting a list of runs:\n", 118 | "\n", 119 | "```python\n", 120 | "from langsmith import Client\n", 121 | "client = Client()\n", 122 | "project_runs = client.list_runs(project_name=\"\")\n", 123 | "```\n", 124 | "\n", 125 | "Getting a specific run:\n", 126 | "\n", 127 | "```python\n", 128 | "from langsmith import Client\n", 129 | "client = Client()\n", 130 | "run = client.client.read_run(\"\")\n", 131 | "```\n", 132 | "\n", 133 | "Furthermore, there are various ways to filter and search runs which are described in [the documentation](https://docs.smith.langchain.com/tracing/use-cases/export-runs). If these suit your needs, you may not need the utilities in this module. This module offers opinionated wrappers around the Langsmith client that retrieve runs using common patterns we have seen.\n", 134 | "\n", 135 | "### Utilities\n", 136 | "\n", 137 | "The following functions help retrieve runs by a very specific kind of [tag](https://docs.smith.langchain.com/tracing/tracing-faq#how-do-i-add-tags-to-runs), as well as recent runs." 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "#|export\n", 147 | "def reformat_date(date_str):\n", 148 | " \"Reformat m/d/y to YYYY-MM-DD.\"\n", 149 | " date_obj = datetime.strptime(date_str, '%m/%d/%Y') # Parsing the date\n", 150 | " formatted_date = date_obj.strftime('%Y-%m-%d') # Formatting to YYYY-MM-DD\n", 151 | " return formatted_date" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "assert reformat_date('9/22/2023') == '2023-09-22'\n", 161 | "assert reformat_date('9/2/2023') == '2023-09-02'" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "#|export\n", 171 | "def take(l:Iterable, n:int):\n", 172 | " \"Take first n entries from a generator\"\n", 173 | " return L(islice(l, n))" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "#|export\n", 183 | "def get_runs_by_commit(commit_id:str=None, # The commit ID to filter by \n", 184 | " proj_id:str=None, # Langsmith Project ID\n", 185 | " only_success=True, # Only include runs that are successfull\n", 186 | " run_type='chain', # The run type\n", 187 | " start_dt:str=None, # The start date to filter by\n", 188 | " end_dt:str=None, # the end date to filter by\n", 189 | " limit:int=None # The maximum number of runs to return\n", 190 | " ):\n", 191 | " \"Get all runs tagged with a particular commit id (the short version of the SHA) in LangSmith.\"\n", 192 | "\n", 193 | " if start_dt: start_dt=reformat_date(start_dt)\n", 194 | " if end_dt: end_dt=reformat_date(end_dt)\n", 195 | " \n", 196 | " success_query='eq(status, \"success\")' if only_success else ''\n", 197 | " commit_query = f'has(tags, \"commit:{commit_id}\")' if commit_id else ''\n", 198 | " proj_id = check_api_key(\"LANGSMITH_PROJECT_ID\") if not proj_id else proj_id\n", 199 | " time_query=''\n", 200 | " \n", 201 | " if start_dt:\n", 202 | " time_query=f'gte(start_time, \"{start_dt}\")'\n", 203 | " if end_dt:\n", 204 | " time_query = f'{time_query}, lte(start_time, \"{end_dt}\")'\n", 205 | " \n", 206 | " queries = ', '.join(L([success_query, commit_query, time_query]).filter())\n", 207 | " query_string = None if not queries else f'and({queries})'\n", 208 | " if query_string: print(f'Fetching runs with this filter: {query_string}')\n", 209 | "\n", 210 | " client = Client()\n", 211 | " runs = client.list_runs(\n", 212 | " filter=query_string,\n", 213 | " project_id=proj_id,\n", 214 | " execution_order=1, # this gets the root runs\n", 215 | " error=False,\n", 216 | " run_type=run_type,\n", 217 | " )\n", 218 | " return list(runs) if limit is None else take(runs, limit)" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": {}, 224 | "source": [ 225 | "The idea behind `get_runs_by_commit` is to quickly retrieve runs that are being logged to langsmith in CI, for example if you are running offline tests automatically against your language models. For example, let's get runs with the tag `commit:4f59dcec` in LangSmith (this is specific to my project)." 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [ 233 | { 234 | "name": "stdout", 235 | "output_type": "stream", 236 | "text": [ 237 | "Fetching runs with this filter: and(eq(status, \"success\"), has(tags, \"commit:4f59dcec\"))\n" 238 | ] 239 | } 240 | ], 241 | "source": [ 242 | "#|hide\n", 243 | "_runs = get_runs_by_commit('4f59dcec', limit=5)\n", 244 | "assert set(_runs.map(lambda x: x.tags[0])) == {'commit:4f59dcec'} # check that all runs have this tag\n", 245 | "assert set(_runs.map(lambda x: x.status)) == {'success'} # check that these runs are successfull" 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": null, 251 | "metadata": {}, 252 | "outputs": [ 253 | { 254 | "name": "stdout", 255 | "output_type": "stream", 256 | "text": [ 257 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2023-10-04\"), lte(start_time, \"2023-10-05\"))\n" 258 | ] 259 | } 260 | ], 261 | "source": [ 262 | "#|hide\n", 263 | "_runs = L(get_runs_by_commit(start_dt='10/4/2023', end_dt='10/5/2023'))\n", 264 | "n_runs = len(_runs)\n", 265 | "assert n_runs > 100" 266 | ] 267 | }, 268 | { 269 | "cell_type": "code", 270 | "execution_count": null, 271 | "metadata": {}, 272 | "outputs": [], 273 | "source": [ 274 | "#|export\n", 275 | "def get_last_child(runs: List[langsmith.schemas.Run]):\n", 276 | " \"Get the child runs for a list of runs.\"\n", 277 | " return [client.read_run(r.child_run_ids[-1]) for r in runs if r.child_run_ids]" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "In LangSmith, the last child is often useful to view the final call to the language model." 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": null, 290 | "metadata": {}, 291 | "outputs": [], 292 | "source": [ 293 | "_child_runs = get_last_child(take(_runs, 3))\n", 294 | "assert _child_runs[0].child_run_ids is None # the child doesn't have other children" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [ 303 | "#|export\n", 304 | "def get_recent_runs(start_dt=None, end_dt=None, last_n_days=2, limit=None):\n", 305 | " \"Get recent runs from Langsmith. If `start_dt` is None gets the `last_n_days`.\"\n", 306 | " client = Client()\n", 307 | " if start_dt is None:\n", 308 | " _runs = client.list_runs(project_id=check_api_key(\"LANGSMITH_PROJECT_ID\"), limit=1)\n", 309 | " latest_run_dt = first(_runs).start_time\n", 310 | " start_dt_obj = latest_run_dt - timedelta(days=last_n_days)\n", 311 | " else:\n", 312 | " start_dt_obj = datetime.strptime(start_dt, '%m/%d/%Y')\n", 313 | " \n", 314 | " if end_dt is None:\n", 315 | " if start_dt is None:\n", 316 | " end_dt_obj = start_dt_obj + timedelta(days=last_n_days+1) # their logic is off lte is really lt\n", 317 | " else:\n", 318 | " end_dt_obj = datetime.strptime(start_dt, '%m/%d/%Y') + timedelta(days=last_n_days+1) # their logic is off lte is really lt \n", 319 | " else:\n", 320 | " if start_dt is None:\n", 321 | " raise ValueError(\"end_dt should only be provided if start_dt is provided.\")\n", 322 | " end_dt_obj = datetime.strptime(end_dt, '%m/%d/%Y')\n", 323 | " \n", 324 | " \n", 325 | " runs = get_runs_by_commit(start_dt=start_dt_obj.strftime('%m/%d/%Y'),\n", 326 | " end_dt=end_dt_obj.strftime('%m/%d/%Y'))\n", 327 | " return list(runs) if limit is None else take(runs, limit)" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "metadata": {}, 333 | "source": [ 334 | "It is often helpful to get runs in a batch in a date range:" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": null, 340 | "metadata": {}, 341 | "outputs": [ 342 | { 343 | "name": "stdout", 344 | "output_type": "stream", 345 | "text": [ 346 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2023-10-04\"), lte(start_time, \"2023-10-05\"))\n", 347 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2023-10-03\"), lte(start_time, \"2023-10-06\"))\n", 348 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2024-02-22\"), lte(start_time, \"2024-02-25\"))\n" 349 | ] 350 | } 351 | ], 352 | "source": [ 353 | "_runs1 = get_recent_runs(start_dt='10/4/2023', end_dt='10/5/2023', limit=10)\n", 354 | "assert len(_runs1) == 10\n", 355 | "\n", 356 | "_runs2 = get_recent_runs(start_dt='10/3/2023', limit=10)\n", 357 | "assert len(_runs2) == 10\n", 358 | "\n", 359 | "_runs3 = get_recent_runs(limit=10)\n", 360 | "assert len(_runs3) == 10" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "#|export\n", 370 | "def get_recent_commit_tags(start_dt=None, end_dt=None, last_n_days=2, return_df=False):\n", 371 | " \"Print a table of recent commit SHAs from Langsmith along with their counts that you can filter on\"\n", 372 | " runs = L(get_recent_runs(start_dt=start_dt, end_dt=end_dt, last_n_days=last_n_days))\n", 373 | " data = runs.map(lambda x: {'start_dt': x.start_time.strftime('%m/%d/%Y'),\n", 374 | " 'commit': first([t.split('commit:')[-1] for t in x.tags if t.startswith('commit:')])\n", 375 | " }\n", 376 | " )\n", 377 | " if data:\n", 378 | " df = pd.DataFrame(data)\n", 379 | " agg = df.groupby(['start_dt']).value_counts().reset_index()\n", 380 | " agg = agg.rename(columns={0: 'count'}).sort_values(by=['start_dt', 'count'], ascending=False)\n", 381 | " if not return_df:\n", 382 | " print(agg.to_markdown(index=False))\n", 383 | " else:\n", 384 | " return agg\n", 385 | " \n", 386 | " else:\n", 387 | " print(f'No commits found for {start_dt} - {end_dt}')\n", 388 | " return None" 389 | ] 390 | }, 391 | { 392 | "cell_type": "markdown", 393 | "metadata": {}, 394 | "source": [ 395 | "Because I like to tag my LangSmith runs with commit SHA (see `get_runs_by_commit`), I also want to see the most recent commit SHAs so I know what to query!" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": null, 401 | "metadata": {}, 402 | "outputs": [ 403 | { 404 | "name": "stdout", 405 | "output_type": "stream", 406 | "text": [ 407 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2024-02-22\"), lte(start_time, \"2024-02-25\"))\n", 408 | "| start_dt | commit | count |\n", 409 | "|:-----------|:---------|--------:|\n", 410 | "| 02/24/2024 | ca2232cc | 490 |\n" 411 | ] 412 | } 413 | ], 414 | "source": [ 415 | "#|eval:false\n", 416 | "get_recent_commit_tags()" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "`get_recent_commit_tags` can also return a Pandas dataframe:" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": null, 429 | "metadata": {}, 430 | "outputs": [ 431 | { 432 | "name": "stdout", 433 | "output_type": "stream", 434 | "text": [ 435 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"2024-02-22\"), lte(start_time, \"2024-02-25\"))\n" 436 | ] 437 | } 438 | ], 439 | "source": [ 440 | "#|eval:false\n", 441 | "_df = get_recent_commit_tags(return_df=True)\n", 442 | "assert _df.shape[0] >= 1" 443 | ] 444 | }, 445 | { 446 | "cell_type": "markdown", 447 | "metadata": {}, 448 | "source": [ 449 | "### Other Ways Of Getting Runs" 450 | ] 451 | }, 452 | { 453 | "cell_type": "markdown", 454 | "metadata": {}, 455 | "source": [ 456 | "You may also want to query runs by [feedback](https://docs.smith.langchain.com/evaluation/capturing-feedback), however there are many degrees of freedom with how you can implement feedback. Furthermore, there are many ways you can utilize tags. For these cases, we suggest using the `langsmith` client directly as [discussed earlier](#Background). \n", 457 | "\n", 458 | "We will continue to update this library with additional recipes should we find other common patterns that are generalizable." 459 | ] 460 | }, 461 | { 462 | "cell_type": "markdown", 463 | "metadata": {}, 464 | "source": [ 465 | "## Parse Data" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": null, 471 | "metadata": {}, 472 | "outputs": [], 473 | "source": [ 474 | "#|export\n", 475 | "def _ischatopenai(run): \n", 476 | " if run.name != 'ChatOpenAI':\n", 477 | " raise TypeError(f'Run: {run.id} is of type `{run.name}`, but can only parse `ChatOpenAI` runs.')" 478 | ] 479 | }, 480 | { 481 | "cell_type": "code", 482 | "execution_count": null, 483 | "metadata": {}, 484 | "outputs": [], 485 | "source": [ 486 | "#|export\n", 487 | "def get_params(run:langsmith.schemas.Run) -> dict:\n", 488 | " \"Get important parameters from a run logged in LangSmith\"\n", 489 | " if 'invocation_params' in run.extra:\n", 490 | " p = run.extra['invocation_params']\n", 491 | " return dict(param_model_name=p.get('model'),\n", 492 | " param_n=p.get('n'),\n", 493 | " param_top_p=p.get('top_p'),\n", 494 | " param_temp=p.get('temperature'),\n", 495 | " param_presence_penalty=p.get('presence_penalty'),\n", 496 | " param_freq_penalty=p.get('frequency_penalty')\n", 497 | " )\n", 498 | " else: return {} " 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "metadata": {}, 505 | "outputs": [ 506 | { 507 | "data": { 508 | "text/plain": [ 509 | "{'param_model_name': 'gpt-3.5-turbo-0613',\n", 510 | " 'param_n': 1,\n", 511 | " 'param_top_p': 1,\n", 512 | " 'param_temp': 0,\n", 513 | " 'param_presence_penalty': 0,\n", 514 | " 'param_freq_penalty': 0}" 515 | ] 516 | }, 517 | "execution_count": null, 518 | "metadata": {}, 519 | "output_type": "execute_result" 520 | } 521 | ], 522 | "source": [ 523 | "_run = client.read_run('8cd7deed-9547-4a07-ac01-55e9513ca1cd')\n", 524 | "get_params(_run)" 525 | ] 526 | }, 527 | { 528 | "cell_type": "code", 529 | "execution_count": null, 530 | "metadata": {}, 531 | "outputs": [], 532 | "source": [ 533 | "#|export\n", 534 | "def get_functions(run:langsmith.schemas.Run) -> List[dict]:\n", 535 | " \"Get function definitions from a LangSmith run.\"\n", 536 | " if 'invocation_params' in run.extra:\n", 537 | " p = run.extra['invocation_params']\n", 538 | " return p.get('functions', [])\n", 539 | " else: return []" 540 | ] 541 | }, 542 | { 543 | "cell_type": "code", 544 | "execution_count": null, 545 | "metadata": {}, 546 | "outputs": [ 547 | { 548 | "name": "stdout", 549 | "output_type": "stream", 550 | "text": [ 551 | "contact-finder\n", 552 | "contact-creator\n", 553 | "email-campaign-creator\n", 554 | "task-creator\n", 555 | "task-finder\n", 556 | "human-chat\n", 557 | "calculator\n", 558 | "knowledge-base\n" 559 | ] 560 | } 561 | ], 562 | "source": [ 563 | "_funcs = get_functions(_run)\n", 564 | "for f in _funcs:\n", 565 | " print(f['name'])" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": null, 571 | "metadata": {}, 572 | "outputs": [], 573 | "source": [ 574 | "#|hide\n", 575 | "_funcs = get_functions(_run)\n", 576 | "assert _funcs[0]['name'] == 'contact-finder'\n", 577 | "assert len(_funcs) > 1" 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": null, 583 | "metadata": {}, 584 | "outputs": [], 585 | "source": [ 586 | "#|export\n", 587 | "def get_feedback(run:langsmith.schemas.Run) -> list:\n", 588 | " \"Get feedback from a run if exists.\"\n", 589 | " raw = L(client.list_feedback(run_ids=[run.id]))\n", 590 | " return list(raw.map(lambda x: dict(key=x.key, \n", 591 | " score=x.score, \n", 592 | " value=x.value, \n", 593 | " comment=x.comment, \n", 594 | " correction=x.correction)\n", 595 | " )\n", 596 | " )" 597 | ] 598 | }, 599 | { 600 | "cell_type": "code", 601 | "execution_count": null, 602 | "metadata": {}, 603 | "outputs": [ 604 | { 605 | "data": { 606 | "text/plain": [ 607 | "[{'key': 'empty response',\n", 608 | " 'score': 0.0,\n", 609 | " 'value': None,\n", 610 | " 'comment': \"expected '' to have a length above 0 but got 0\",\n", 611 | " 'correction': None}]" 612 | ] 613 | }, 614 | "execution_count": null, 615 | "metadata": {}, 616 | "output_type": "execute_result" 617 | } 618 | ], 619 | "source": [ 620 | "_feedback = get_feedback(client.read_run('7aba254d-3812-4050-85a5-ed64af50d2f1'))\n", 621 | "assert _feedback[0]['score'] == 0\n", 622 | "assert _feedback[0]['key'] == 'empty response'\n", 623 | "_feedback" 624 | ] 625 | }, 626 | { 627 | "cell_type": "markdown", 628 | "metadata": {}, 629 | "source": [ 630 | "## Exporting Runs To Pandas" 631 | ] 632 | }, 633 | { 634 | "cell_type": "markdown", 635 | "metadata": {}, 636 | "source": [ 637 | "See the [chatrecord](03_chatrecord.ipynb) module." 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": null, 643 | "metadata": {}, 644 | "outputs": [], 645 | "source": [ 646 | "#| hide\n", 647 | "import nbdev; nbdev.nbdev_export()" 648 | ] 649 | }, 650 | { 651 | "cell_type": "code", 652 | "execution_count": null, 653 | "metadata": {}, 654 | "outputs": [], 655 | "source": [] 656 | } 657 | ], 658 | "metadata": { 659 | "kernelspec": { 660 | "display_name": "python3", 661 | "language": "python", 662 | "name": "python3" 663 | } 664 | }, 665 | "nbformat": 4, 666 | "nbformat_minor": 4 667 | } 668 | -------------------------------------------------------------------------------- /nbs/02_transform.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "id": "db2116aa-9418-46cc-b283-39fd9b8a1e4d", 6 | "metadata": {}, 7 | "source": [ 8 | "---\n", 9 | "skip_showdoc: true\n", 10 | "skip_exec: true\n", 11 | "---" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "id": "4a573de2-34fe-4fdc-a5c7-7018318f167a", 17 | "metadata": {}, 18 | "source": [ 19 | "# transform\n", 20 | "\n", 21 | "> common transformations for LLM data" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "id": "d1851b3f-5b38-4d50-8f61-c3fe0d54f089", 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "#| default_exp transform" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "id": "279d65a5-c571-4341-b690-39ca2721fcfc", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "#|export\n", 42 | "import os, copy, json\n", 43 | "import openai, langsmith\n", 44 | "from typing import List, Callable\n", 45 | "from random import shuffle\n", 46 | "from collections import defaultdict\n", 47 | "\n", 48 | "from langfree.runs import _temp_env_var, Client, _ischatopenai\n", 49 | "from pydantic import BaseModel\n", 50 | "from langchain.adapters import openai as adapt\n", 51 | "from langchain.load import load\n", 52 | "from fastcore.foundation import L\n", 53 | "from tenacity import (\n", 54 | " retry,\n", 55 | " stop_after_attempt,\n", 56 | " wait_random_exponential,\n", 57 | ") # for exponential backoff\n" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "id": "5ea68e53-44b5-4cf5-876b-aead27071d14", 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "from nbdev.showdoc import show_doc" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "id": "620b0131-7055-418b-9263-69180553f3eb", 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "#|export\n", 78 | "client = openai.OpenAI()" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "id": "7b1248be-3d29-434e-9fc2-7e344d37d22f", 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "#|exports\n", 89 | "@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))\n", 90 | "def chat(**kwargs):\n", 91 | " \"A wrapper around `openai.ChatCompletion` that has automatic retries.\" \n", 92 | " client.api_key = os.environ['OPENAI_API_KEY']\n", 93 | " return client.chat.completions.create(**kwargs)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "id": "951bfb23-8774-46c0-8865-97c53c59dbf4", 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "#|hide\n", 104 | "tmp_env = {'LANGCHAIN_API_KEY': os.environ['LANGCHAIN_API_KEY_PUB'], 'LANGSMITH_PROJECT_ID': os.environ['LANGCHAIN_PROJECT_ID_PUB']}" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "9cc66954-70fa-4022-bd88-085722bcfa15", 111 | "metadata": {}, 112 | "outputs": [ 113 | { 114 | "name": "stderr", 115 | "output_type": "stream", 116 | "text": [ 117 | "/Users/hamel/mambaforge/lib/python3.10/site-packages/langchain_core/_api/beta_decorator.py:86: LangChainBetaWarning: The function `load` is in beta. It is actively being worked on, so the API may change.\n", 118 | " warn_beta(\n" 119 | ] 120 | } 121 | ], 122 | "source": [ 123 | "#|hide\n", 124 | "_tst_run_id = '59080971-8786-4849-be88-898d3ffc2b45'\n", 125 | "client = langsmith.Client()\n", 126 | "run = client.read_run(_tst_run_id)\n", 127 | "msg = run.outputs['generations'][0]['message']\n", 128 | "assert load(msg)" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "id": "7663a851-03a2-4f3d-8c58-2d5cc613ec26", 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "#|export\n", 139 | "def fetch_run_componets(run_id:str):\n", 140 | " \"Return the `inputs`, `output` and `funcs` for a run of type `ChatOpenAI`.\"\n", 141 | " client = langsmith.Client()\n", 142 | " run = client.read_run(run_id)\n", 143 | " _ischatopenai(run)\n", 144 | " output = adapt.convert_message_to_dict(load(run.outputs['generations'][0]['message']))\n", 145 | " inputs = [adapt.convert_message_to_dict(load(m)) for m in run.inputs['messages']]\n", 146 | " params = run.extra['invocation_params']\n", 147 | " \n", 148 | " for inp in inputs:\n", 149 | " if 'function_call' in inp and inp.get('content', None) is None:\n", 150 | " del inp['content']\n", 151 | " funcs = params.get(\"functions\", [])\n", 152 | " return inputs, output, funcs" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "id": "77caa6fd-deac-45e1-ba1b-aad781331075", 159 | "metadata": {}, 160 | "outputs": [ 161 | { 162 | "name": "stdout", 163 | "output_type": "stream", 164 | "text": [ 165 | "first input:\n", 166 | "{'role': 'system', 'content': \"You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\\nThe current time is 2023-09-05 16:49:07.308007.\\n\\nRelevant documents will be retrieved in the following messages.\"} \n", 167 | "\n", 168 | "output:\n", 169 | "{'role': 'assistant', 'content': \"Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\\n\\n1. Read the runs from the source organization using the SDK.\\n2. Write the runs to the destination organization using the SDK.\\n\\nBy following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\\n\\nIf you have any further questions or need assistance, please reach out to us at support@langchain.dev.\"} \n", 170 | "\n", 171 | "functions:\n", 172 | "[]\n" 173 | ] 174 | } 175 | ], 176 | "source": [ 177 | "_tst_run_id = '1863d76e-1462-489a-a8a7-e0404239fe47'\n", 178 | "\n", 179 | "with _temp_env_var(tmp_env): #context manager that has specific environment vars for testing \n", 180 | " _inp, _out, _funcs = fetch_run_componets(_tst_run_id)\n", 181 | "\n", 182 | "print(f\"\"\"first input:\n", 183 | "{_inp[0]} \n", 184 | "\n", 185 | "output:\n", 186 | "{_out} \n", 187 | "\n", 188 | "functions:\n", 189 | "{_funcs}\"\"\")" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "id": "2955d7b5-491f-4f93-9a0c-9cdbcba55000", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "#|hide\n", 200 | "_run_id = '59080971-8786-4849-be88-898d3ffc2b45'\n", 201 | "_inputs, _output, _funcs = fetch_run_componets(_run_id)" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "id": "db3deda0-b415-4683-9f5b-fc340f80c84f", 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "#|exports\n", 212 | "class RunData(BaseModel):\n", 213 | " \"Key components of a run from LangSmith\"\n", 214 | " inputs:List[dict]\n", 215 | " output:dict\n", 216 | " funcs:List[dict] \n", 217 | " run_id:str\n", 218 | "\n", 219 | " @classmethod\n", 220 | " def from_run_id(cls, run_id:str):\n", 221 | " \"Create a `RunData` object from a run id.\"\n", 222 | " inputs, output, funcs = fetch_run_componets(run_id)\n", 223 | " return cls(inputs=inputs, output=output, funcs=funcs, run_id=run_id)\n", 224 | "\n", 225 | " def to_msg_dict(self):\n", 226 | " \"Transform the instance into a dict in the format that can be used for OpenAI fine-tuning.\"\n", 227 | " msgs = self.inputs + [self.output]\n", 228 | " return {\"functions\": self.funcs,\n", 229 | " \"messages\": msgs}\n", 230 | "\n", 231 | " def to_json(self):\n", 232 | " \"The json version of `to_msg_dict`.\"\n", 233 | " return json.dumps(self.to_msg_dict())\n", 234 | "\n", 235 | " @property\n", 236 | " def outputs(self):\n", 237 | " \"Return outputs for langsmith Datasets compatibility.\"\n", 238 | " return self.output\n", 239 | "\n", 240 | " @property\n", 241 | " def flat_input(self):\n", 242 | " \"The input to the LLM in markdown.\"\n", 243 | " return self._flatten_data(self.inputs)\n", 244 | "\n", 245 | " @property\n", 246 | " def flat_output(self):\n", 247 | " \"The output of the LLM in markdown.\"\n", 248 | " return self._flatten_data([self.output])\n", 249 | "\n", 250 | " @classmethod\t\n", 251 | " def _flatten_data(cls, data):\n", 252 | " \"Produce a flattened view of the data as human readable Markdown.\"\n", 253 | " md_str = \"\"\n", 254 | " for item in data:\n", 255 | " # Heading\n", 256 | " role = item['role']\n", 257 | " if role == 'assistant' and 'function_call' in item:\n", 258 | " role += ' - function call'\n", 259 | " if role == 'function':\n", 260 | " role += ' - results'\n", 261 | " \n", 262 | " md_str += f\"### {role.title()}\\n\\n\"\n", 263 | "\n", 264 | " content = item.get('content', '')\n", 265 | " if content: md_str += content + \"\\n\"\n", 266 | " \n", 267 | " elif 'function_call' in item:\n", 268 | " func_name = item['function_call']['name']\n", 269 | " args = json.loads(item['function_call']['arguments'])\n", 270 | " formatted_args = ', '.join([f\"{k}={v}\" for k, v in args.items()])\n", 271 | " md_str += f\"{func_name}({formatted_args})\\n\"\n", 272 | " md_str += \"\\n\"\n", 273 | " return md_str" 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": null, 279 | "id": "91bf0eab-38c7-44b2-b287-c941ddba299c", 280 | "metadata": {}, 281 | "outputs": [ 282 | { 283 | "data": { 284 | "text/markdown": [ 285 | "---\n", 286 | "\n", 287 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L60){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 288 | "\n", 289 | "#### RunData.from_run_id\n", 290 | "\n", 291 | "> RunData.from_run_id (run_id:str)\n", 292 | "\n", 293 | "Create a `RunData` object from a run id." 294 | ], 295 | "text/plain": [ 296 | "---\n", 297 | "\n", 298 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L60){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 299 | "\n", 300 | "#### RunData.from_run_id\n", 301 | "\n", 302 | "> RunData.from_run_id (run_id:str)\n", 303 | "\n", 304 | "Create a `RunData` object from a run id." 305 | ] 306 | }, 307 | "execution_count": null, 308 | "metadata": {}, 309 | "output_type": "execute_result" 310 | } 311 | ], 312 | "source": [ 313 | "show_doc(RunData.from_run_id, title_level=4)" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "id": "9a2f6788-82a4-485c-8473-45c19d43e24c", 320 | "metadata": {}, 321 | "outputs": [ 322 | { 323 | "name": "stdout", 324 | "output_type": "stream", 325 | "text": [ 326 | "Run 1863d76e-1462-489a-a8a7-e0404239fe47 has 3 inputs.\n", 327 | "Run 1863d76e-1462-489a-a8a7-e0404239fe47 output:\n", 328 | "{'role': 'assistant', 'content': \"Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\\n\\n1. Read the runs from the source organization using the SDK.\\n2. Write the runs to the destination organization using the SDK.\\n\\nBy following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\\n\\nIf you have any further questions or need assistance, please reach out to us at support@langchain.dev.\"}\n" 329 | ] 330 | } 331 | ], 332 | "source": [ 333 | "with _temp_env_var(tmp_env): #context manager that has specific environment vars for testing\n", 334 | " rd = RunData.from_run_id(_tst_run_id)\n", 335 | "\n", 336 | "print(f'Run {rd.run_id} has {len(rd.inputs)} inputs.')\n", 337 | "print(f'Run {rd.run_id} output:\\n{rd.output}')" 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": null, 343 | "id": "72979269-83ad-468b-81f1-bbda71a27cda", 344 | "metadata": {}, 345 | "outputs": [ 346 | { 347 | "data": { 348 | "text/markdown": [ 349 | "---\n", 350 | "\n", 351 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L65){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 352 | "\n", 353 | "#### RunData.to_msg_dict\n", 354 | "\n", 355 | "> RunData.to_msg_dict ()\n", 356 | "\n", 357 | "Transform the instance into a dict in the format that can be used for OpenAI fine-tuning." 358 | ], 359 | "text/plain": [ 360 | "---\n", 361 | "\n", 362 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L65){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 363 | "\n", 364 | "#### RunData.to_msg_dict\n", 365 | "\n", 366 | "> RunData.to_msg_dict ()\n", 367 | "\n", 368 | "Transform the instance into a dict in the format that can be used for OpenAI fine-tuning." 369 | ] 370 | }, 371 | "execution_count": null, 372 | "metadata": {}, 373 | "output_type": "execute_result" 374 | } 375 | ], 376 | "source": [ 377 | "show_doc(RunData.to_msg_dict, title_level=4)" 378 | ] 379 | }, 380 | { 381 | "cell_type": "code", 382 | "execution_count": null, 383 | "id": "add34097-4946-4ad9-bd28-1e5c06734cea", 384 | "metadata": {}, 385 | "outputs": [ 386 | { 387 | "data": { 388 | "text/plain": [ 389 | "[{'role': 'user',\n", 390 | " 'content': 'How do I move my project between organizations?'},\n", 391 | " {'role': 'assistant',\n", 392 | " 'content': \"Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\\n\\n1. Read the runs from the source organization using the SDK.\\n2. Write the runs to the destination organization using the SDK.\\n\\nBy following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\\n\\nIf you have any further questions or need assistance, please reach out to us at support@langchain.dev.\"}]" 393 | ] 394 | }, 395 | "execution_count": null, 396 | "metadata": {}, 397 | "output_type": "execute_result" 398 | } 399 | ], 400 | "source": [ 401 | "rd.to_msg_dict()['messages'][-2:]" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "id": "f90d5fa0-4265-461c-a241-fdca3d0e51dc", 408 | "metadata": {}, 409 | "outputs": [ 410 | { 411 | "data": { 412 | "text/markdown": [ 413 | "---\n", 414 | "\n", 415 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L71){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 416 | "\n", 417 | "#### RunData.to_json\n", 418 | "\n", 419 | "> RunData.to_json ()\n", 420 | "\n", 421 | "The json version of `to_msg_dict`." 422 | ], 423 | "text/plain": [ 424 | "---\n", 425 | "\n", 426 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L71){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 427 | "\n", 428 | "#### RunData.to_json\n", 429 | "\n", 430 | "> RunData.to_json ()\n", 431 | "\n", 432 | "The json version of `to_msg_dict`." 433 | ] 434 | }, 435 | "execution_count": null, 436 | "metadata": {}, 437 | "output_type": "execute_result" 438 | } 439 | ], 440 | "source": [ 441 | "show_doc(RunData.to_json, title_level=4)" 442 | ] 443 | }, 444 | { 445 | "cell_type": "code", 446 | "execution_count": null, 447 | "id": "d6bb8e59-37cc-4a37-bb1d-564219b7b51d", 448 | "metadata": {}, 449 | "outputs": [ 450 | { 451 | "data": { 452 | "text/plain": [ 453 | "'{\"functions\": [], \"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful documentation Q&A as'" 454 | ] 455 | }, 456 | "execution_count": null, 457 | "metadata": {}, 458 | "output_type": "execute_result" 459 | } 460 | ], 461 | "source": [ 462 | "rd.to_json()[:100]" 463 | ] 464 | }, 465 | { 466 | "cell_type": "markdown", 467 | "id": "a8d314a9-7ced-40ea-9d2e-2628d6cefebe", 468 | "metadata": {}, 469 | "source": [ 470 | "The properties `flat_input` and `flat_output` allow you to view the input to the LLM and the output in a human readable format (markdown):" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": null, 476 | "id": "9f15e8a1-b173-4e94-935d-084cee1ea9a2", 477 | "metadata": {}, 478 | "outputs": [ 479 | { 480 | "data": { 481 | "text/markdown": [ 482 | "---\n", 483 | "\n", 484 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L81){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 485 | "\n", 486 | "#### RunData.flat_input\n", 487 | "\n", 488 | "> RunData.flat_input ()\n", 489 | "\n", 490 | "The input to the LLM in markdown." 491 | ], 492 | "text/plain": [ 493 | "---\n", 494 | "\n", 495 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L81){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 496 | "\n", 497 | "#### RunData.flat_input\n", 498 | "\n", 499 | "> RunData.flat_input ()\n", 500 | "\n", 501 | "The input to the LLM in markdown." 502 | ] 503 | }, 504 | "execution_count": null, 505 | "metadata": {}, 506 | "output_type": "execute_result" 507 | } 508 | ], 509 | "source": [ 510 | "show_doc(RunData.flat_input, title_level=4)" 511 | ] 512 | }, 513 | { 514 | "cell_type": "code", 515 | "execution_count": null, 516 | "id": "81f7abc8-3491-440b-9541-9ba362f5b1a5", 517 | "metadata": {}, 518 | "outputs": [ 519 | { 520 | "name": "stdout", 521 | "output_type": "stream", 522 | "text": [ 523 | "### System\n", 524 | "\n", 525 | "You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\n", 526 | "The current time is 2023-09-05 16:49:07.308007.\n", 527 | "\n", 528 | "Relevant documents will be retrieved in the following messages.\n", 529 | "\n", 530 | "### System\n", 531 | "\n", 532 | "\n", 533 | "\n", 534 | "Skip to main content\n", 535 | "\n", 536 | " **🦜️🛠️ LangSmith Docs**Python DocsJS/TS Docs\n", 537 | "\n", 538 | "Sear\n" 539 | ] 540 | } 541 | ], 542 | "source": [ 543 | "print(rd.flat_input[:400])" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": null, 549 | "id": "732c56d8-3a02-47fa-8b3e-16d530c59c3b", 550 | "metadata": {}, 551 | "outputs": [ 552 | { 553 | "data": { 554 | "text/markdown": [ 555 | "---\n", 556 | "\n", 557 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L86){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 558 | "\n", 559 | "#### RunData.flat_output\n", 560 | "\n", 561 | "> RunData.flat_output ()\n", 562 | "\n", 563 | "The output of the LLM in markdown." 564 | ], 565 | "text/plain": [ 566 | "---\n", 567 | "\n", 568 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/transform.py#L86){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 569 | "\n", 570 | "#### RunData.flat_output\n", 571 | "\n", 572 | "> RunData.flat_output ()\n", 573 | "\n", 574 | "The output of the LLM in markdown." 575 | ] 576 | }, 577 | "execution_count": null, 578 | "metadata": {}, 579 | "output_type": "execute_result" 580 | } 581 | ], 582 | "source": [ 583 | "show_doc(RunData.flat_output, title_level=4)" 584 | ] 585 | }, 586 | { 587 | "cell_type": "code", 588 | "execution_count": null, 589 | "id": "d35043ba-c21e-47e4-8339-43f42e6344ef", 590 | "metadata": {}, 591 | "outputs": [ 592 | { 593 | "name": "stdout", 594 | "output_type": "stream", 595 | "text": [ 596 | "### Assistant\n", 597 | "\n", 598 | "Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\n", 599 | "\n", 600 | "1. Read the runs from the source organization using the SDK.\n", 601 | "2. Write the runs to the destination organization using the SDK.\n", 602 | "\n", 603 | "By following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\n", 604 | "\n", 605 | "If you have any further questions or need assistance, please reach out to us at support@langchain.dev.\n", 606 | "\n", 607 | "\n" 608 | ] 609 | } 610 | ], 611 | "source": [ 612 | "print(rd.flat_output)" 613 | ] 614 | }, 615 | { 616 | "cell_type": "markdown", 617 | "id": "550a1b22-b51c-4ae5-a2d5-6ab935e9e1ee", 618 | "metadata": {}, 619 | "source": [ 620 | "## Preparing `.jsonl` files\n", 621 | "\n", 622 | "[OpenAI fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) takes `.jsonl` files." 623 | ] 624 | }, 625 | { 626 | "cell_type": "code", 627 | "execution_count": null, 628 | "id": "bcb6ce23-c8bb-47c4-b4b8-314666f82021", 629 | "metadata": {}, 630 | "outputs": [], 631 | "source": [ 632 | "#|export\n", 633 | "def write_to_jsonl(data_list:List[RunData], filename:str):\n", 634 | " \"\"\"\n", 635 | " Writes a list of dictionaries to a .jsonl file.\n", 636 | " \n", 637 | " Parameters:\n", 638 | " - data_list (list of `RunData`): The data to be written.\n", 639 | " - filename (str): The name of the output file.\n", 640 | " \"\"\"\n", 641 | " shuffle(data_list)\n", 642 | " with open(filename, 'w') as f:\n", 643 | " for entry in data_list:\n", 644 | " f.write(f\"{entry.to_json()}\\n\")" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": null, 650 | "id": "5144d12d-3f90-471d-a503-045832c9d552", 651 | "metadata": {}, 652 | "outputs": [], 653 | "source": [ 654 | "#|eval:false\n", 655 | "_rids = ['59080971-8786-4849-be88-898d3ffc2b45', '8cd7deed-9547-4a07-ac01-55e9513ca1cd']\n", 656 | "_tsfm_runs = [RunData.from_run_id(rid) for rid in _rids]\n", 657 | "write_to_jsonl(_tsfm_runs, '_data/test_data.jsonl');" 658 | ] 659 | }, 660 | { 661 | "cell_type": "markdown", 662 | "id": "4c9b3cd8-f7f7-4b24-90de-10505c118be8", 663 | "metadata": {}, 664 | "source": [ 665 | "It can save you time to validate jsonl files prior to uploading them." 666 | ] 667 | }, 668 | { 669 | "cell_type": "code", 670 | "execution_count": null, 671 | "id": "94a60ed0-a3c9-4220-95f7-bb168fb650ca", 672 | "metadata": {}, 673 | "outputs": [], 674 | "source": [ 675 | "#|export\n", 676 | "def validate_jsonl(fname):\n", 677 | " \"Code is modified from https://cookbook.openai.com/examples/chat_finetuning_data_prep, but updated for function calling.\"\n", 678 | " # Load the dataset\n", 679 | " with open(fname, 'r', encoding='utf-8') as f:\n", 680 | " dataset = [json.loads(line) for line in f]\n", 681 | "\n", 682 | " # Initial dataset stats\n", 683 | " print(\"Num examples:\", len(dataset))\n", 684 | " \n", 685 | " # Format error checks\n", 686 | " format_errors = defaultdict(int)\n", 687 | "\n", 688 | " for i, ex in enumerate(dataset):\n", 689 | " if not isinstance(ex, dict):\n", 690 | " format_errors[\"data_type\"] += 1\n", 691 | " continue\n", 692 | "\n", 693 | " messages = ex.get(\"messages\", None)\n", 694 | " if not messages:\n", 695 | " format_errors[\"missing_messages_list\"] += 1\n", 696 | " continue\n", 697 | "\n", 698 | " for im, message in enumerate(messages):\n", 699 | " if \"role\" not in message or (\"content\" not in message and 'function_call' not in message):\n", 700 | " format_errors[\"message_missing_key\"] += 1\n", 701 | "\n", 702 | " if any(k not in (\"role\", \"content\", \"name\", \"function_call\") for k in message):\n", 703 | " format_errors[\"message_unrecognized_key\"] += 1\n", 704 | " print(f'message_unrecognized_key {[k for k in message.keys() if k not in [\"role\", \"content\", \"name\"]]} in row:{i} message {im}')\n", 705 | "\n", 706 | " if message.get(\"role\", None) not in (\"system\", \"user\", \"assistant\", \"function\"):\n", 707 | " format_errors[\"unrecognized_role\"] += 1\n", 708 | " print(f'unrecognized_role {message.get(\"role\", None)} in row:{i} message {im}')\n", 709 | "\n", 710 | " content = message.get(\"content\", None)\n", 711 | " if (not content or not isinstance(content, str)) and 'function_call' not in message:\n", 712 | " format_errors[\"missing_content\"] += 1\n", 713 | " print(f'missing_content in row:{i} message {im}')\n", 714 | "\n", 715 | " if not any(message.get(\"role\", None) == \"assistant\" for message in messages):\n", 716 | " format_errors[\"example_missing_assistant_message\"] += 1\n", 717 | "\n", 718 | " if format_errors:\n", 719 | " print(\"Found errors:\")\n", 720 | " for k, v in format_errors.items():\n", 721 | " print(f\"{k}: {v}\")\n", 722 | " else:\n", 723 | " print(\"No errors found\")" 724 | ] 725 | }, 726 | { 727 | "cell_type": "code", 728 | "execution_count": null, 729 | "id": "223f8f01-1787-401b-9db7-d0657ec6af85", 730 | "metadata": {}, 731 | "outputs": [ 732 | { 733 | "name": "stdout", 734 | "output_type": "stream", 735 | "text": [ 736 | "Num examples: 2\n", 737 | "No errors found\n" 738 | ] 739 | } 740 | ], 741 | "source": [ 742 | "#|eval: false\n", 743 | "validate_jsonl('_data/test_data.jsonl')" 744 | ] 745 | }, 746 | { 747 | "cell_type": "code", 748 | "execution_count": null, 749 | "id": "90662f53-de19-4032-a9ac-80fdacb78509", 750 | "metadata": {}, 751 | "outputs": [], 752 | "source": [ 753 | "#|hide\n", 754 | "import nbdev; nbdev.nbdev_export()" 755 | ] 756 | }, 757 | { 758 | "cell_type": "code", 759 | "execution_count": null, 760 | "id": "7dc86a80-b68f-4ed5-9bbf-790b9dbe92b5", 761 | "metadata": {}, 762 | "outputs": [], 763 | "source": [] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "execution_count": null, 768 | "id": "598ae5fa-143f-4efb-88e4-217688a91b6d", 769 | "metadata": {}, 770 | "outputs": [], 771 | "source": [] 772 | } 773 | ], 774 | "metadata": { 775 | "kernelspec": { 776 | "display_name": "python3", 777 | "language": "python", 778 | "name": "python3" 779 | } 780 | }, 781 | "nbformat": 4, 782 | "nbformat_minor": 5 783 | } 784 | -------------------------------------------------------------------------------- /nbs/03_chatrecord.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "id": "33b4bd64-1cb6-4373-bb2c-265fea29502c", 6 | "metadata": {}, 7 | "source": [ 8 | "---\n", 9 | "skip_showdoc: true\n", 10 | "skip_exec: true\n", 11 | "---" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "id": "961f54c1-8eae-4ffa-af08-584e8612d198", 17 | "metadata": {}, 18 | "source": [ 19 | "# chatrecord\n", 20 | "> Tools for exporting chat related portions of Langchain runs." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "38c02c61-7fe1-4dbc-b74c-bf11a64ca9e7", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "#| default_exp chatrecord" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "id": "65cd47cc-3f52-4cfc-9efb-4dc6a6c61993", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "#|export\n", 41 | "from typing import List, Iterable, Union\n", 42 | "from collections import Counter\n", 43 | "from pathlib import Path\n", 44 | "import pickle\n", 45 | "\n", 46 | "import pandas as pd\n", 47 | "from pydantic import BaseModel\n", 48 | "import langsmith\n", 49 | "from fastcore.foundation import first, L\n", 50 | "from fastcore.test import test_eq\n", 51 | "from langfree.runs import (get_runs_by_commit, \n", 52 | " get_params, get_functions,\n", 53 | " get_feedback)\n", 54 | "from langfree.transform import RunData\n", 55 | "from langsmith import Client" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "id": "2909e32e-3066-4e9e-877b-d87b6f35211f", 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "from nbdev.showdoc import show_doc" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "id": "4b15b45a-9739-4f41-b4d7-1512472ac7e7", 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "#|export\n", 76 | "class NoChatOpenAI(Exception):\n", 77 | " def __init__(self, message, extra_data=None):\n", 78 | " super().__init__(message)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "id": "6efd7c50-2b56-4f2a-acbf-697cdf582e11", 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "#|export\n", 89 | "def get_nested_child_run(run):\n", 90 | " \"Get the last nested `ChatOpenAI` run inside a Runnable Agent.\"\n", 91 | " client = Client()\n", 92 | " run = client.read_run(run_id=run.id, load_child_runs=True)\n", 93 | " oai_children = []\n", 94 | " for r in run.child_runs:\n", 95 | " if r.name == 'RunnableAgent':\n", 96 | " for c in r.child_runs:\n", 97 | " if c.name == 'ChatOpenAI':\n", 98 | " oai_children.append(c)\n", 99 | " if r.name == 'ChatOpenAI':\n", 100 | " oai_children.append(r)\n", 101 | " if not oai_children:\n", 102 | " raise NoChatOpenAI(f'Not able to find ChatOpenAI child run from root run {run.id}')\n", 103 | " return oai_children[-1]\n", 104 | "\n", 105 | "def get_child_chat_run(run):\n", 106 | " \"Get the last child `ChatOpenAI` run.\"\n", 107 | " client = Client()\n", 108 | " if run.parent_run_id is not None:\n", 109 | " # if run.execution_order != 1: # this is a child run, get the parent\n", 110 | " run = client.read_run(run.parent_run_id)\n", 111 | "\n", 112 | " crun = get_nested_child_run(run)\n", 113 | " return run, crun" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "id": "7c314972-94a8-4730-8fac-7b8b8c2b05ac", 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "#|hide\n", 124 | "client = Client()\n", 125 | "_run_id = '98d1c463-bf25-46a1-90f2-a3a1b5e2fa3f'\n", 126 | "_root_run = client.read_run(_run_id)\n", 127 | "assert get_child_chat_run(_root_run)" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "id": "ae0841d1-6685-4203-b166-8188383b487e", 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "#|hide\n", 138 | "client = Client()\n", 139 | "_root_run = client.read_run('fbfd220a-c731-46a2-87b3-e64a477824f5')\n", 140 | "assert client.read_run(run_id=_root_run.id, load_child_runs=True)" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "id": "c7012b46-4c1b-442f-9d11-d6e2fc69c9d8", 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "#|export\n", 151 | "class ChatRecord(BaseModel):\n", 152 | " \"A parsed run from LangSmith, focused on the `ChatOpenAI` run type.\"\n", 153 | " child_run_id:str\n", 154 | " child_run:RunData\n", 155 | " child_url:Union[str,None] = None\n", 156 | " parent_run_id:Union[str,None] = None\n", 157 | " parent_url: Union[str,None] = None\n", 158 | " total_tokens:Union[int, None]\n", 159 | " prompt_tokens:Union[int, None]\n", 160 | " completion_tokens:Union[int, None]\n", 161 | " feedback: Union[List,None] = None\n", 162 | " feedback_keys: Union[List,None] = None\n", 163 | " tags: Union[List,None] = []\n", 164 | " start_dt: Union[str, None] = None\n", 165 | " function_defs: Union[List,None] = None\n", 166 | " param_model_name: Union[str,None]= None\n", 167 | " param_n: Union[int, None] = None\n", 168 | " param_top_p: Union[int, None] = None\n", 169 | " param_temp: Union[int, None] = None\n", 170 | " param_presence_penalty: Union[int, None] = None\n", 171 | " param_freq_penalty: Union[int, None] = None\n", 172 | "\n", 173 | " @property\n", 174 | " def flat_input(self): return self.child_run.flat_input\n", 175 | " \n", 176 | " @property\n", 177 | " def flat_output(self): return self.child_run.flat_output\n", 178 | "\n", 179 | " @classmethod\n", 180 | " def from_run_id(cls, \n", 181 | " run_id:str # the run id to fetch and parse.\n", 182 | " ):\n", 183 | " \"Collect information About A Run into a `ChatRecord`.\"\n", 184 | " client = Client()\n", 185 | " return cls.from_run(client.read_run(run_id=run_id))\n", 186 | " \n", 187 | " @classmethod\n", 188 | " def from_run(cls, \n", 189 | " run:langsmith.schemas.Run # the run object to parse.\n", 190 | " ):\n", 191 | " \"Collect information About A Run into a `ChatRecord`.\"\n", 192 | " run, crun = get_child_chat_run(run)\n", 193 | " \n", 194 | " if crun:\n", 195 | " params = get_params(crun)\n", 196 | " _feedback = get_feedback(run) # you must get feedback from the root\n", 197 | " \n", 198 | " return cls(child_run_id=str(crun.id),\n", 199 | " child_run=RunData.from_run_id(str(crun.id)),\n", 200 | " child_url=crun.url,\n", 201 | " parent_run_id=str(run.id) if run else None,\n", 202 | " parent_url=run.url if run else None,\n", 203 | " total_tokens=crun.total_tokens,\n", 204 | " prompt_tokens=crun.prompt_tokens,\n", 205 | " completion_tokens=crun.completion_tokens,\n", 206 | " feedback=_feedback, \n", 207 | " feedback_keys=list(L(_feedback).attrgot('key').filter()),\n", 208 | " tags=run.tags,\n", 209 | " start_dt=run.start_time.strftime('%m/%d/%Y'),\n", 210 | " function_defs=get_functions(crun),\n", 211 | " **params)" 212 | ] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "id": "10d1284f-790a-409b-a3aa-f4ff41a3dac7", 217 | "metadata": {}, 218 | "source": [ 219 | "When instantiating `ChatRecord` with the class methods `ChatRecord.from_run` or `ChatRecord.from_run_id`, we automatically query the parent run of the LangChain trace in LangSmith to get metadata like feedback. Additionally, if you instantiate `ChatRecord` with a root run or a run that is not a `ChatOpenAI` run type, `ChatRecord` will attempt to find the last `ChatOpenAI` in your chain and store the id in `ChatRecord.child_run_id`. The data for this child run (inputs, outputs, functions) is stored in `ChatRecord.child_run` and is of type `RunData`." 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "id": "c3ba391c-cce1-45d8-90c6-4422a43551c5", 226 | "metadata": {}, 227 | "outputs": [ 228 | { 229 | "name": "stderr", 230 | "output_type": "stream", 231 | "text": [ 232 | "/Users/hamel/mambaforge/lib/python3.10/site-packages/langchain_core/_api/beta_decorator.py:86: LangChainBetaWarning: The function `load` is in beta. It is actively being worked on, so the API may change.\n", 233 | " warn_beta(\n" 234 | ] 235 | }, 236 | { 237 | "data": { 238 | "text/plain": [ 239 | "AIMessage(content='```json\\n{\"id\":\"df952a3b-d04b-4329-865d-ef37e727da38\",\"type\":\"template_instance\"}\\n```')" 240 | ] 241 | }, 242 | "execution_count": null, 243 | "metadata": {}, 244 | "output_type": "execute_result" 245 | } 246 | ], 247 | "source": [ 248 | "#|hide\n", 249 | "# this used to cause a confusing deserialiization error\n", 250 | "from langchain.load import load\n", 251 | "\n", 252 | "_tst_run_id = '98d1c463-bf25-46a1-90f2-a3a1b5e2fa3f'\n", 253 | "client = Client()\n", 254 | "_trun = client.read_run(run_id=_tst_run_id)\n", 255 | "_run, _crun = get_child_chat_run(_trun)\n", 256 | "\n", 257 | "_msg = _crun.outputs['generations'][0]['message']\n", 258 | "load(_msg)" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "id": "57127967-b38c-421b-b8ce-6bff1339cf8d", 265 | "metadata": {}, 266 | "outputs": [ 267 | { 268 | "data": { 269 | "text/markdown": [ 270 | "---\n", 271 | "\n", 272 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L93){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 273 | "\n", 274 | "#### ChatRecord.from_run\n", 275 | "\n", 276 | "> ChatRecord.from_run (run:langsmith.schemas.Run)\n", 277 | "\n", 278 | "Collect information About A Run into a `ChatRecord`.\n", 279 | "\n", 280 | "| | **Type** | **Details** |\n", 281 | "| -- | -------- | ----------- |\n", 282 | "| run | Run | the run object to parse. |" 283 | ], 284 | "text/plain": [ 285 | "---\n", 286 | "\n", 287 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L93){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 288 | "\n", 289 | "#### ChatRecord.from_run\n", 290 | "\n", 291 | "> ChatRecord.from_run (run:langsmith.schemas.Run)\n", 292 | "\n", 293 | "Collect information About A Run into a `ChatRecord`.\n", 294 | "\n", 295 | "| | **Type** | **Details** |\n", 296 | "| -- | -------- | ----------- |\n", 297 | "| run | Run | the run object to parse. |" 298 | ] 299 | }, 300 | "execution_count": null, 301 | "metadata": {}, 302 | "output_type": "execute_result" 303 | } 304 | ], 305 | "source": [ 306 | "show_doc(ChatRecord.from_run, title_level=4)" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": null, 312 | "id": "43efaf24-b2db-41c2-983d-017a9167b862", 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "client = Client()\n", 317 | "_root_run = client.read_run('fbfd220a-c731-46a2-87b3-e64a477824f5')\n", 318 | "_root_result = ChatRecord.from_run(_root_run)" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "id": "008ae7c8-cb53-4308-8708-7535d14a223d", 325 | "metadata": {}, 326 | "outputs": [ 327 | { 328 | "data": { 329 | "text/markdown": [ 330 | "---\n", 331 | "\n", 332 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L85){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 333 | "\n", 334 | "#### ChatRecord.from_run_id\n", 335 | "\n", 336 | "> ChatRecord.from_run_id (run_id:str)\n", 337 | "\n", 338 | "Collect information About A Run into a `ChatRecord`.\n", 339 | "\n", 340 | "| | **Type** | **Details** |\n", 341 | "| -- | -------- | ----------- |\n", 342 | "| run_id | str | the run id to fetch and parse. |" 343 | ], 344 | "text/plain": [ 345 | "---\n", 346 | "\n", 347 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L85){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 348 | "\n", 349 | "#### ChatRecord.from_run_id\n", 350 | "\n", 351 | "> ChatRecord.from_run_id (run_id:str)\n", 352 | "\n", 353 | "Collect information About A Run into a `ChatRecord`.\n", 354 | "\n", 355 | "| | **Type** | **Details** |\n", 356 | "| -- | -------- | ----------- |\n", 357 | "| run_id | str | the run id to fetch and parse. |" 358 | ] 359 | }, 360 | "execution_count": null, 361 | "metadata": {}, 362 | "output_type": "execute_result" 363 | } 364 | ], 365 | "source": [ 366 | "show_doc(ChatRecord.from_run_id, title_level=4)" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": null, 372 | "id": "b300ab30-6d4d-474a-a5b6-b14b59fefe59", 373 | "metadata": {}, 374 | "outputs": [], 375 | "source": [ 376 | "_child_run_id = str(_root_run.child_run_ids[-1])\n", 377 | "_child_result = ChatRecord.from_run_id(_child_run_id)" 378 | ] 379 | }, 380 | { 381 | "cell_type": "markdown", 382 | "id": "d6d69caa-58fd-419b-b81a-72a5c492ba56", 383 | "metadata": {}, 384 | "source": [ 385 | "Tests" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": null, 391 | "id": "fd718377-5738-4179-9708-0bcf0d0108e2", 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | "# test that child and root runs are related\n", 396 | "test_eq(_root_result.flat_output, _child_result.flat_output)\n", 397 | "test_eq(_root_result.parent_run_id, _child_result.parent_run_id)\n", 398 | "\n", 399 | "# Test case without feedback\n", 400 | "_parent_run_no_feedback = client.read_run('87900cfc-0322-48fb-b009-33d226d73597')\n", 401 | "_no_feedback = ChatRecord.from_run(_parent_run_no_feedback)\n", 402 | "test_eq(_no_feedback.feedback, [])\n", 403 | "\n", 404 | "# Test case with feedback\n", 405 | "\n", 406 | "# ... starting with a child run\n", 407 | "_child_w_feedback = client.read_run('f8717b0e-fb90-45cd-be00-9b4614965a2e')\n", 408 | "_feedback = ChatRecord.from_run(_child_w_feedback).feedback\n", 409 | "assert _feedback[0]['key'] == 'empty response'\n", 410 | "\n", 411 | "# # ... starting with a parent run\n", 412 | "_parent_w_feedback = client.read_run(_child_w_feedback.parent_run_id)\n", 413 | "_feedback2 = ChatRecord.from_run(_parent_w_feedback).feedback\n", 414 | "test_eq(_feedback[0]['comment'], _feedback2[0]['comment'])" 415 | ] 416 | }, 417 | { 418 | "cell_type": "markdown", 419 | "id": "5c9b0e08-f640-441c-b825-da25f0f747ff", 420 | "metadata": {}, 421 | "source": [ 422 | "## `ChatRecordSet`, a list of `ChatRecord`" 423 | ] 424 | }, 425 | { 426 | "cell_type": "code", 427 | "execution_count": null, 428 | "id": "cc7563fc-b096-4f4f-ad6a-2fcf00485d44", 429 | "metadata": {}, 430 | "outputs": [], 431 | "source": [ 432 | "#|export\n", 433 | "class ChatRecordSet(BaseModel):\n", 434 | " \"A List of `ChatRecord`.\"\n", 435 | " records: List[ChatRecord]\n", 436 | " \n", 437 | " @classmethod\n", 438 | " def from_commit(cls, commit_id:str, limit:int=None):\n", 439 | " \"Create a `ChatRecordSet` from a commit id\"\n", 440 | " _runs = get_runs_by_commit(commit_id=commit_id, limit=limit)\n", 441 | " return cls.from_runs(_runs)\n", 442 | " \n", 443 | " @classmethod\n", 444 | " def from_runs(cls, runs:List[langsmith.schemas.Run]):\n", 445 | " \"Load ChatRecordSet from runs.\"\n", 446 | " _records = []\n", 447 | " for r in runs:\n", 448 | " try: _records.append(ChatRecord.from_run(r))\n", 449 | " except NoChatOpenAI as e: print(e) \n", 450 | " return cls(records=_records)\n", 451 | "\n", 452 | " @classmethod\n", 453 | " def from_run_ids(cls, runs:List[str]):\n", 454 | " \"Load ChatRecordSet from run ids.\"\n", 455 | " _records = []\n", 456 | " for r in runs:\n", 457 | " try: _records.append(ChatRecord.from_run_id(r))\n", 458 | " except NoChatOpenAI as e: print(e)\n", 459 | " return cls(records=_records)\n", 460 | " \n", 461 | " def __len__(self): return len(self.records)\n", 462 | "\n", 463 | " def __getitem__(self, index: int) -> ChatRecord:\n", 464 | " return self.records[index]\n", 465 | "\n", 466 | " def __repr__(self):\n", 467 | " return f'`List[ChatRecord]` of size {len(self.records)}.'\n", 468 | " \n", 469 | " def save(self, path:str):\n", 470 | " \"Save data to disk.\"\n", 471 | " dest_path = Path(path)\n", 472 | " if not dest_path.parent.exists(): dest_path.parent.mkdir(exist_ok=True)\n", 473 | " with open(dest_path, 'wb') as f:\n", 474 | " pickle.dump(self, f)\n", 475 | " return dest_path\n", 476 | " \n", 477 | " def __iter__(self): \n", 478 | " for r in self.records: \n", 479 | " yield r\n", 480 | " \n", 481 | " @classmethod\n", 482 | " def load(cls, path:str):\n", 483 | " \"Load data from disk.\"\n", 484 | " src_path = Path(path)\n", 485 | " with open(src_path, 'rb') as f:\n", 486 | " obj = pickle.load(f)\n", 487 | " if isinstance(obj, cls):\n", 488 | " return obj\n", 489 | " else:\n", 490 | " raise TypeError(f\"The loaded object is not of type {cls.__name__}\")\n", 491 | " \n", 492 | " def to_pandas(self):\n", 493 | " \"Convert the `ChatRecordSet` to a pandas.DataFrame.\"\n", 494 | " records = L(self.records).map(dict) \n", 495 | " return pd.DataFrame(records)\n", 496 | "\n", 497 | " def to_dicts(self):\n", 498 | " \"Convert the ChatRecordSet to a list of dicts, which you can convert to jsonl.\"\n", 499 | " return list(L(self.records).map(lambda x: x.child_run.to_msg_dict()))" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "id": "b7c0acbe-5edb-446f-8fa3-51c74d588a42", 506 | "metadata": {}, 507 | "outputs": [ 508 | { 509 | "data": { 510 | "text/markdown": [ 511 | "---\n", 512 | "\n", 513 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L130){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 514 | "\n", 515 | "#### ChatRecordSet.from_runs\n", 516 | "\n", 517 | "> ChatRecordSet.from_runs (runs:List[langsmith.schemas.Run])\n", 518 | "\n", 519 | "Load ChatRecordSet from runs." 520 | ], 521 | "text/plain": [ 522 | "---\n", 523 | "\n", 524 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L130){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 525 | "\n", 526 | "#### ChatRecordSet.from_runs\n", 527 | "\n", 528 | "> ChatRecordSet.from_runs (runs:List[langsmith.schemas.Run])\n", 529 | "\n", 530 | "Load ChatRecordSet from runs." 531 | ] 532 | }, 533 | "execution_count": null, 534 | "metadata": {}, 535 | "output_type": "execute_result" 536 | } 537 | ], 538 | "source": [ 539 | "show_doc(ChatRecordSet.from_runs, title_level=4)" 540 | ] 541 | }, 542 | { 543 | "cell_type": "markdown", 544 | "id": "b48d366f-052e-4539-9ec3-7d860e12d51d", 545 | "metadata": {}, 546 | "source": [ 547 | "We can create a `ChatRecordSet` directly from a list of runs:" 548 | ] 549 | }, 550 | { 551 | "cell_type": "code", 552 | "execution_count": null, 553 | "id": "26f451f5-ab9a-4e0a-b338-912d941dd5ed", 554 | "metadata": {}, 555 | "outputs": [ 556 | { 557 | "name": "stdout", 558 | "output_type": "stream", 559 | "text": [ 560 | "Fetching runs with this filter: and(eq(status, \"success\"), has(tags, \"commit:028e4aa4\"))\n" 561 | ] 562 | } 563 | ], 564 | "source": [ 565 | "# from langfree.runs import get_runs_by_commit\n", 566 | "_runs = get_runs_by_commit(commit_id='028e4aa4', limit=10)\n", 567 | "llmdata = ChatRecordSet.from_runs(_runs)" 568 | ] 569 | }, 570 | { 571 | "cell_type": "markdown", 572 | "id": "840645a5-18dc-4682-8511-e3bda826dcfb", 573 | "metadata": {}, 574 | "source": [ 575 | "There is a special shortcut to get runs by a commit tag which uses `get_runs_by_commit` for you:" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": null, 581 | "id": "241699d9-13f3-4c4c-9511-057dc1c2e62b", 582 | "metadata": {}, 583 | "outputs": [ 584 | { 585 | "data": { 586 | "text/markdown": [ 587 | "---\n", 588 | "\n", 589 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L124){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 590 | "\n", 591 | "#### ChatRecordSet.from_commit\n", 592 | "\n", 593 | "> ChatRecordSet.from_commit (commit_id:str, limit:int=None)\n", 594 | "\n", 595 | "Create a `ChatRecordSet` from a commit id" 596 | ], 597 | "text/plain": [ 598 | "---\n", 599 | "\n", 600 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L124){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 601 | "\n", 602 | "#### ChatRecordSet.from_commit\n", 603 | "\n", 604 | "> ChatRecordSet.from_commit (commit_id:str, limit:int=None)\n", 605 | "\n", 606 | "Create a `ChatRecordSet` from a commit id" 607 | ] 608 | }, 609 | "execution_count": null, 610 | "metadata": {}, 611 | "output_type": "execute_result" 612 | } 613 | ], 614 | "source": [ 615 | "show_doc(ChatRecordSet.from_commit, title_level=4)" 616 | ] 617 | }, 618 | { 619 | "cell_type": "code", 620 | "execution_count": null, 621 | "id": "9ca91b92-f293-4982-8a43-48e8c6e111ac", 622 | "metadata": {}, 623 | "outputs": [ 624 | { 625 | "name": "stdout", 626 | "output_type": "stream", 627 | "text": [ 628 | "Fetching runs with this filter: and(eq(status, \"success\"), has(tags, \"commit:028e4aa4\"))\n" 629 | ] 630 | } 631 | ], 632 | "source": [ 633 | "llmdata2 = ChatRecordSet.from_commit('028e4aa4', limit=10)\n", 634 | "assert llmdata[0].child_run_id == llmdata2[0].child_run_id" 635 | ] 636 | }, 637 | { 638 | "cell_type": "markdown", 639 | "id": "f9c88fbe-a57a-4c4b-a804-c5e504277f6e", 640 | "metadata": {}, 641 | "source": [ 642 | "Finally, you can also construct a `ChatRecordSet` from a list of run ids:" 643 | ] 644 | }, 645 | { 646 | "cell_type": "code", 647 | "execution_count": null, 648 | "id": "9ab513c0-46ad-48f5-941a-c69726635df0", 649 | "metadata": {}, 650 | "outputs": [ 651 | { 652 | "data": { 653 | "text/markdown": [ 654 | "---\n", 655 | "\n", 656 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L139){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 657 | "\n", 658 | "#### ChatRecordSet.from_run_ids\n", 659 | "\n", 660 | "> ChatRecordSet.from_run_ids (runs:List[str])\n", 661 | "\n", 662 | "Load ChatRecordSet from run ids." 663 | ], 664 | "text/plain": [ 665 | "---\n", 666 | "\n", 667 | "[source](https://github.com/parlance-labs/langfree/blob/main/langfree/chatrecord.py#L139){target=\"_blank\" style=\"float:right; font-size:smaller\"}\n", 668 | "\n", 669 | "#### ChatRecordSet.from_run_ids\n", 670 | "\n", 671 | "> ChatRecordSet.from_run_ids (runs:List[str])\n", 672 | "\n", 673 | "Load ChatRecordSet from run ids." 674 | ] 675 | }, 676 | "execution_count": null, 677 | "metadata": {}, 678 | "output_type": "execute_result" 679 | } 680 | ], 681 | "source": [ 682 | "show_doc(ChatRecordSet.from_run_ids, title_level=4)" 683 | ] 684 | }, 685 | { 686 | "cell_type": "code", 687 | "execution_count": null, 688 | "id": "ed10b22d-46e5-4e30-b280-ee9f71ed431e", 689 | "metadata": {}, 690 | "outputs": [], 691 | "source": [ 692 | "_run_ids = ['ba3c0a47-0803-4b0f-8a2f-380722edc2bf',\n", 693 | " '842fe1b4-c650-4bfa-bcf9-bf5c30f8204c',\n", 694 | " '5c06bbf3-ef14-47a1-a3a4-221f65d4a407',\n", 695 | " '327039ab-a0a5-488b-875f-21e0d30ee2cd']\n", 696 | "\n", 697 | "llmdata3 = ChatRecordSet.from_run_ids(_run_ids)\n", 698 | "assert len(llmdata3) == len(_run_ids)\n", 699 | "assert llmdata[0].child_run_id == _run_ids[0]" 700 | ] 701 | }, 702 | { 703 | "cell_type": "markdown", 704 | "id": "3d487386-c66d-44ea-b7e9-8dba650aa917", 705 | "metadata": {}, 706 | "source": [ 707 | "### Convert `ChatRecordSet` to a Pandas Dataframe\n", 708 | "\n", 709 | "You can do this with `to_pandas()`" 710 | ] 711 | }, 712 | { 713 | "cell_type": "code", 714 | "execution_count": null, 715 | "id": "05787582-4982-4d7a-8500-cccf283fbc0a", 716 | "metadata": {}, 717 | "outputs": [ 718 | { 719 | "data": { 720 | "text/html": [ 721 | "
\n", 722 | "\n", 735 | "\n", 736 | " \n", 737 | " \n", 738 | " \n", 739 | " \n", 740 | " \n", 741 | " \n", 742 | " \n", 743 | " \n", 744 | " \n", 745 | " \n", 746 | " \n", 747 | " \n", 748 | " \n", 749 | " \n", 750 | " \n", 751 | " \n", 752 | " \n", 753 | " \n", 754 | " \n", 755 | " \n", 756 | " \n", 757 | " \n", 758 | " \n", 759 | " \n", 760 | " \n", 761 | " \n", 762 | " \n", 763 | " \n", 764 | " \n", 765 | " \n", 766 | " \n", 767 | " \n", 768 | " \n", 769 | " \n", 770 | " \n", 771 | " \n", 772 | " \n", 773 | " \n", 774 | " \n", 775 | " \n", 776 | " \n", 777 | " \n", 778 | " \n", 779 | " \n", 780 | " \n", 781 | " \n", 782 | " \n", 783 | " \n", 784 | "
child_run_idchild_runchild_urlparent_run_idparent_urltotal_tokensprompt_tokenscompletion_tokensfeedbackfeedback_keystagsstart_dtfunction_defsparam_model_nameparam_nparam_top_pparam_tempparam_presence_penaltyparam_freq_penalty
0ba3c0a47-0803-4b0f-8a2f-380722edc2bfinputs=[{'role': 'system', 'content': 'You are...https://smith.langchain.com/o/9d90c3d2-ca7e-4c...7074af93-1821-4325-9d45-0f2e81eca0fehttps://smith.langchain.com/o/9d90c3d2-ca7e-4c...000[][][commit:028e4aa4, branch:testing, test, room:6...09/05/2023[{'name': 'contact-finder', 'parameters': {'ty...gpt-3.5-turbo-061311000
\n", 785 | "
" 786 | ], 787 | "text/plain": [ 788 | " child_run_id \\\n", 789 | "0 ba3c0a47-0803-4b0f-8a2f-380722edc2bf \n", 790 | "\n", 791 | " child_run \\\n", 792 | "0 inputs=[{'role': 'system', 'content': 'You are... \n", 793 | "\n", 794 | " child_url \\\n", 795 | "0 https://smith.langchain.com/o/9d90c3d2-ca7e-4c... \n", 796 | "\n", 797 | " parent_run_id \\\n", 798 | "0 7074af93-1821-4325-9d45-0f2e81eca0fe \n", 799 | "\n", 800 | " parent_url total_tokens \\\n", 801 | "0 https://smith.langchain.com/o/9d90c3d2-ca7e-4c... 0 \n", 802 | "\n", 803 | " prompt_tokens completion_tokens feedback feedback_keys \\\n", 804 | "0 0 0 [] [] \n", 805 | "\n", 806 | " tags start_dt \\\n", 807 | "0 [commit:028e4aa4, branch:testing, test, room:6... 09/05/2023 \n", 808 | "\n", 809 | " function_defs param_model_name \\\n", 810 | "0 [{'name': 'contact-finder', 'parameters': {'ty... gpt-3.5-turbo-0613 \n", 811 | "\n", 812 | " param_n param_top_p param_temp param_presence_penalty \\\n", 813 | "0 1 1 0 0 \n", 814 | "\n", 815 | " param_freq_penalty \n", 816 | "0 0 " 817 | ] 818 | }, 819 | "execution_count": null, 820 | "metadata": {}, 821 | "output_type": "execute_result" 822 | } 823 | ], 824 | "source": [ 825 | "_df = llmdata.to_pandas()\n", 826 | "_df.head(1)" 827 | ] 828 | }, 829 | { 830 | "cell_type": "code", 831 | "execution_count": null, 832 | "id": "31f80a84-d399-41dc-83f1-a9e01a7823b1", 833 | "metadata": {}, 834 | "outputs": [], 835 | "source": [ 836 | "#|hide\n", 837 | "assert _df.shape[0] == 10" 838 | ] 839 | }, 840 | { 841 | "cell_type": "markdown", 842 | "id": "088b1760-faa5-42bd-97d9-cb3e4348ed3f", 843 | "metadata": {}, 844 | "source": [ 845 | "### Save Data" 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "execution_count": null, 851 | "id": "e06c2214-a08e-4cc4-9188-ec755d1d8b79", 852 | "metadata": {}, 853 | "outputs": [ 854 | { 855 | "data": { 856 | "text/plain": [ 857 | "Path('_data/llm_data.pkl')" 858 | ] 859 | }, 860 | "execution_count": null, 861 | "metadata": {}, 862 | "output_type": "execute_result" 863 | } 864 | ], 865 | "source": [ 866 | "#|eval: false\n", 867 | "llmdata.save('_data/llm_data.pkl')" 868 | ] 869 | }, 870 | { 871 | "cell_type": "markdown", 872 | "id": "59dcb976-bb6c-4909-b8b0-0e8099272e81", 873 | "metadata": {}, 874 | "source": [ 875 | "### Load Data" 876 | ] 877 | }, 878 | { 879 | "cell_type": "code", 880 | "execution_count": null, 881 | "id": "1689b521-7f85-406f-9122-618dcae57d50", 882 | "metadata": {}, 883 | "outputs": [], 884 | "source": [ 885 | "#|eval: false\n", 886 | "_loaded = ChatRecordSet.load('_data/llm_data.pkl')\n", 887 | "assert llmdata.records[0].child_run_id == _loaded.records[0].child_run_id" 888 | ] 889 | }, 890 | { 891 | "cell_type": "code", 892 | "execution_count": null, 893 | "id": "77fd088e-2cbf-407c-bf6b-8a221193839e", 894 | "metadata": {}, 895 | "outputs": [], 896 | "source": [ 897 | "#|hide\n", 898 | "import nbdev; nbdev.nbdev_export()" 899 | ] 900 | }, 901 | { 902 | "cell_type": "code", 903 | "execution_count": null, 904 | "id": "80346342-5979-426f-973b-330a57232db9", 905 | "metadata": {}, 906 | "outputs": [], 907 | "source": [] 908 | } 909 | ], 910 | "metadata": { 911 | "kernelspec": { 912 | "display_name": "python3", 913 | "language": "python", 914 | "name": "python3" 915 | } 916 | }, 917 | "nbformat": 4, 918 | "nbformat_minor": 5 919 | } 920 | -------------------------------------------------------------------------------- /nbs/04_shiny.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "faff8878-d80b-4141-92b2-d64edd99ab24", 6 | "metadata": {}, 7 | "source": [ 8 | "# shiny\n", 9 | "> components for Shiny" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "id": "13d11348-e5b6-4221-98ce-1d25d220a9a5", 15 | "metadata": {}, 16 | "source": [ 17 | "[Shiny for Python](https://shiny.posit.co/py/) is a front end framework that allows you to quickly build simple applications. It's perfect for customizing your own data annotation and review app for LLMs[^1]. This module contains opinionated components that display [ChatOpenAI](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) run information in Shiny Apps.\n", 18 | "\n", 19 | "[^1]: We tried other similar frameworks like Gradio, Streamlit, and Panel, but found Shiny to fit our needs the best." 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "id": "5c67c400-6eb1-4ce8-8e3c-db129b5dca5c", 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "#|default_exp shiny" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "e8b6c078-873c-4dce-bb4a-3fc103eb5ccf", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "#|export\n", 40 | "import os, json\n", 41 | "from pprint import pformat\n", 42 | "from langfree.transform import RunData\n", 43 | "from shiny import module, ui, render, reactive\n", 44 | "import shiny.experimental as x\n", 45 | "import asyncio" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "id": "71e6b2f4-6399-4fd0-93c9-c9ca0d58e953", 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "#|hide\n", 56 | "from langfree.runs import _temp_env_var" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "id": "a16b95de-529a-42c0-b705-69af19af84a7", 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "#|export\n", 67 | "def _get_role(m):\n", 68 | " role = m['role'].upper()\n", 69 | " if 'function_call' in m: return f\"{role} - Function Call\"\n", 70 | " if role == 'FUNCTION': return 'FUNCTION RESULTS'\n", 71 | " else: return role\n", 72 | "\n", 73 | "def _get_content(m):\n", 74 | " if 'function_call' in m:\n", 75 | " func = m['function_call']\n", 76 | " return f\"{func['name']}({func['arguments']})\"\n", 77 | " else: return m['content']\n", 78 | "\n", 79 | "def render_input_chat(run:RunData, markdown=True):\n", 80 | " \"Render the chat history, except for the last output as a group of cards.\"\n", 81 | " cards = []\n", 82 | " num_inputs = len(run.inputs)\n", 83 | " for i,m in enumerate(run.inputs):\n", 84 | " content = str(_get_content(m))\n", 85 | " if _get_role(m) == 'FUNCTION RESULTS':\n", 86 | " try: content = '```json\\n' + pformat(json.loads(content)) + '\\n```'\n", 87 | " except: pass\n", 88 | " cards.append(\n", 89 | " ui.card(\n", 90 | " ui.card_header(ui.div({\"style\": \"display: flex; justify-content: space-between;\"},\n", 91 | " ui.span(\n", 92 | " {\"style\": \"font-weight: bold;\"}, \n", 93 | " _get_role(m),\n", 94 | " ),\n", 95 | " ui.span(f'({i+1}/{num_inputs})'),\n", 96 | " ) \n", 97 | " ),\n", 98 | " x.ui.card_body(ui.markdown(content) if markdown else content),\n", 99 | " class_= \"card border-dark mb-3\"\n", 100 | " )\n", 101 | " )\n", 102 | " return ui.div(*cards)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "id": "f4f7a1b6-0f8b-45cd-aa28-3fa53fdfff47", 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "#|hide\n", 113 | "tmp_env = {'LANGCHAIN_API_KEY': os.environ['LANGCHAIN_API_KEY_PUB'], \n", 114 | " 'LANGSMITH_PROJECT_ID': os.environ['LANGCHAIN_PROJECT_ID_PUB']}" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "id": "22b82a19-b45c-42d6-b302-c8d34b43563f", 120 | "metadata": {}, 121 | "source": [ 122 | "`render_input` will take an instance of `RunData` and render a set of Shiny cards, with each card containing one turn of the chat conversation:" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "id": "2b4ca6a3-a5d6-46cc-85c6-728bd1b173ef", 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "from langfree.transform import RunData" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "id": "4a323643-323b-4bd0-bce3-9ccd02b7c643", 139 | "metadata": {}, 140 | "outputs": [ 141 | { 142 | "name": "stderr", 143 | "output_type": "stream", 144 | "text": [ 145 | "/Users/hamel/mambaforge/lib/python3.10/site-packages/langchain_core/_api/beta_decorator.py:86: LangChainBetaWarning: The function `load` is in beta. It is actively being worked on, so the API may change.\n", 146 | " warn_beta(\n" 147 | ] 148 | } 149 | ], 150 | "source": [ 151 | "with _temp_env_var(tmp_env): #context manager that has specific environment vars for testing\n", 152 | " _tst_run = RunData.from_run_id('1863d76e-1462-489a-a8a7-e0404239fe47')\n", 153 | " \n", 154 | "_rendered_inp = render_input_chat(_tst_run) " 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "id": "602e3e72-4028-4bcb-b23c-d5f191b23c0d", 160 | "metadata": {}, 161 | "source": [ 162 | "Below, we render the first card in the conversation:" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": null, 168 | "id": "cdd705d8-d249-4c8d-8c5b-1a65c5aa1b69", 169 | "metadata": {}, 170 | "outputs": [ 171 | { 172 | "data": { 173 | "text/html": [ 174 | "
\n", 175 | "
\n", 176 | "
\n", 177 | " SYSTEM(1/3)\n", 178 | "
\n", 179 | "
\n", 180 | "

You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\n", 181 | "The current time is 2023-09-05 16:49:07.308007.

\n", 182 | "

Relevant documents will be retrieved in the following messages.

\n", 183 | "
\n", 184 | " \n", 185 | "
" 186 | ], 187 | "text/plain": [ 188 | "
\n", 189 | "
\n", 190 | "
\n", 191 | " SYSTEM(1/3)\n", 192 | "
\n", 193 | "
\n", 194 | "

You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\n", 195 | "The current time is 2023-09-05 16:49:07.308007.

\n", 196 | "

Relevant documents will be retrieved in the following messages.

\n", 197 | "
\n", 198 | " \n", 199 | "
" 200 | ] 201 | }, 202 | "execution_count": null, 203 | "metadata": {}, 204 | "output_type": "execute_result" 205 | } 206 | ], 207 | "source": [ 208 | "_rendered_inp.children[0] # the first message in the conversation" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "id": "f9c6a02f-62bd-42f8-a314-cf1e2e70f1d7", 214 | "metadata": {}, 215 | "source": [ 216 | "Here is the last card in the conversation:" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": null, 222 | "id": "e8c68ffa-500b-48d2-998e-fac86083107a", 223 | "metadata": {}, 224 | "outputs": [ 225 | { 226 | "data": { 227 | "text/html": [ 228 | "
\n", 229 | "
\n", 230 | "
\n", 231 | " USER(3/3)\n", 232 | "
\n", 233 | "
\n", 234 | "

How do I move my project between organizations?

\n", 235 | "
\n", 236 | " \n", 237 | "
" 238 | ], 239 | "text/plain": [ 240 | "
\n", 241 | "
\n", 242 | "
\n", 243 | " USER(3/3)\n", 244 | "
\n", 245 | "
\n", 246 | "

How do I move my project between organizations?

\n", 247 | "
\n", 248 | " \n", 249 | "
" 250 | ] 251 | }, 252 | "execution_count": null, 253 | "metadata": {}, 254 | "output_type": "execute_result" 255 | } 256 | ], 257 | "source": [ 258 | "_rendered_inp.children[-1] # the last message in the conversation" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "id": "51c2b5bd-9cbd-49f1-8d44-34ec38b4bf88", 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "#|hide\n", 269 | "_run = RunData.from_run_id('59080971-8786-4849-be88-898d3ffc2b45')\n", 270 | "_rendered_inp = render_input_chat(_run)" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "id": "8b74b70e-357d-4c7e-8712-569c7696d710", 277 | "metadata": {}, 278 | "outputs": [ 279 | { 280 | "data": { 281 | "text/html": [ 282 | "
\n", 283 | "
\n", 284 | "
\n", 285 | " FUNCTION RESULTS(4/7)\n", 286 | "
\n", 287 | "
\n", 288 | "
{'id': 'ee152e0b-0de2-48ea-94e5-a14b8c0d5178',\n",
289 |        " 'inputs': [{'required': False,\n",
290 |        "             'suggestions': [{'listing': {'address': '2430 Victory Park Lane '\n",
291 |        "                                                     'Unit 2508',\n",
292 |        "                                          'baths': 2.1,\n",
293 |        "                                          'beds': 2,\n",
294 |        "                                          'close_date': None,\n",
295 |        "                                          'close_price': None,\n",
296 |        "                                          'id': '7ff2fad0-cc63-11e5-913f-f23c91c841bd',\n",
297 |        "                                          'mls': 'NTREIS',\n",
298 |        "                                          'mls_number': '13315265',\n",
299 |        "                                          'price': 1350000,\n",
300 |        "                                          'status': 'Active',\n",
301 |        "                                          'type': 'compact_listing'},\n",
302 |        "                              'type': 'input_form_suggestion',\n",
303 |        "                              'value': '1st listing'},\n",
304 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
305 |        "                                                     'Unit 2003',\n",
306 |        "                                          'baths': 2,\n",
307 |        "                                          'beds': 1,\n",
308 |        "                                          'close_date': None,\n",
309 |        "                                          'close_price': None,\n",
310 |        "                                          'id': '33836686-d0db-11e5-b351-f23c91c841bd',\n",
311 |        "                                          'mls': 'NTREIS',\n",
312 |        "                                          'mls_number': '13317847',\n",
313 |        "                                          'price': 770000,\n",
314 |        "                                          'status': 'Active',\n",
315 |        "                                          'type': 'compact_listing'},\n",
316 |        "                              'type': 'input_form_suggestion',\n",
317 |        "                              'value': '2nd listing'},\n",
318 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
319 |        "                                                     'Unit 3001',\n",
320 |        "                                          'baths': 7.3,\n",
321 |        "                                          'beds': 5,\n",
322 |        "                                          'close_date': None,\n",
323 |        "                                          'close_price': None,\n",
324 |        "                                          'id': 'cdaef89c-cb9a-11e5-b4c2-f23c91c841bd',\n",
325 |        "                                          'mls': 'NTREIS',\n",
326 |        "                                          'mls_number': '13314620',\n",
327 |        "                                          'price': 7995000,\n",
328 |        "                                          'status': 'Active',\n",
329 |        "                                          'type': 'compact_listing'},\n",
330 |        "                              'type': 'input_form_suggestion',\n",
331 |        "                              'value': '3rd listing'},\n",
332 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
333 |        "                                                     'Unit 2301',\n",
334 |        "                                          'baths': 1,\n",
335 |        "                                          'beds': 1,\n",
336 |        "                                          'close_date': None,\n",
337 |        "                                          'close_price': None,\n",
338 |        "                                          'id': '7e84d768-a814-11e5-8e1e-f23c91c841bd',\n",
339 |        "                                          'mls': 'NTREIS',\n",
340 |        "                                          'mls_number': '13291126',\n",
341 |        "                                          'price': 399900,\n",
342 |        "                                          'status': 'Active',\n",
343 |        "                                          'type': 'compact_listing'},\n",
344 |        "                              'type': 'input_form_suggestion',\n",
345 |        "                              'value': '4th listing'},\n",
346 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
347 |        "                                                     'Unit 1908',\n",
348 |        "                                          'baths': 2.1,\n",
349 |        "                                          'beds': 2,\n",
350 |        "                                          'close_date': None,\n",
351 |        "                                          'close_price': None,\n",
352 |        "                                          'id': '58a718e4-9f54-11e5-a0f8-f23c91c841bd',\n",
353 |        "                                          'mls': 'NTREIS',\n",
354 |        "                                          'mls_number': '13286938',\n",
355 |        "                                          'price': 999000,\n",
356 |        "                                          'status': 'Active',\n",
357 |        "                                          'type': 'compact_listing'},\n",
358 |        "                              'type': 'input_form_suggestion',\n",
359 |        "                              'value': '5th listing'}],\n",
360 |        "             'title': 'Which one of the following listings do you want to use?',\n",
361 |        "             'type': 'input_form_input'}],\n",
362 |        " 'type': 'input_form'}\n",
363 |        "
\n", 364 | "
\n", 365 | " \n", 366 | "
" 367 | ], 368 | "text/plain": [ 369 | "
\n", 370 | "
\n", 371 | "
\n", 372 | " FUNCTION RESULTS(4/7)\n", 373 | "
\n", 374 | "
\n", 375 | "
{'id': 'ee152e0b-0de2-48ea-94e5-a14b8c0d5178',\n",
376 |        " 'inputs': [{'required': False,\n",
377 |        "             'suggestions': [{'listing': {'address': '2430 Victory Park Lane '\n",
378 |        "                                                     'Unit 2508',\n",
379 |        "                                          'baths': 2.1,\n",
380 |        "                                          'beds': 2,\n",
381 |        "                                          'close_date': None,\n",
382 |        "                                          'close_price': None,\n",
383 |        "                                          'id': '7ff2fad0-cc63-11e5-913f-f23c91c841bd',\n",
384 |        "                                          'mls': 'NTREIS',\n",
385 |        "                                          'mls_number': '13315265',\n",
386 |        "                                          'price': 1350000,\n",
387 |        "                                          'status': 'Active',\n",
388 |        "                                          'type': 'compact_listing'},\n",
389 |        "                              'type': 'input_form_suggestion',\n",
390 |        "                              'value': '1st listing'},\n",
391 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
392 |        "                                                     'Unit 2003',\n",
393 |        "                                          'baths': 2,\n",
394 |        "                                          'beds': 1,\n",
395 |        "                                          'close_date': None,\n",
396 |        "                                          'close_price': None,\n",
397 |        "                                          'id': '33836686-d0db-11e5-b351-f23c91c841bd',\n",
398 |        "                                          'mls': 'NTREIS',\n",
399 |        "                                          'mls_number': '13317847',\n",
400 |        "                                          'price': 770000,\n",
401 |        "                                          'status': 'Active',\n",
402 |        "                                          'type': 'compact_listing'},\n",
403 |        "                              'type': 'input_form_suggestion',\n",
404 |        "                              'value': '2nd listing'},\n",
405 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
406 |        "                                                     'Unit 3001',\n",
407 |        "                                          'baths': 7.3,\n",
408 |        "                                          'beds': 5,\n",
409 |        "                                          'close_date': None,\n",
410 |        "                                          'close_price': None,\n",
411 |        "                                          'id': 'cdaef89c-cb9a-11e5-b4c2-f23c91c841bd',\n",
412 |        "                                          'mls': 'NTREIS',\n",
413 |        "                                          'mls_number': '13314620',\n",
414 |        "                                          'price': 7995000,\n",
415 |        "                                          'status': 'Active',\n",
416 |        "                                          'type': 'compact_listing'},\n",
417 |        "                              'type': 'input_form_suggestion',\n",
418 |        "                              'value': '3rd listing'},\n",
419 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
420 |        "                                                     'Unit 2301',\n",
421 |        "                                          'baths': 1,\n",
422 |        "                                          'beds': 1,\n",
423 |        "                                          'close_date': None,\n",
424 |        "                                          'close_price': None,\n",
425 |        "                                          'id': '7e84d768-a814-11e5-8e1e-f23c91c841bd',\n",
426 |        "                                          'mls': 'NTREIS',\n",
427 |        "                                          'mls_number': '13291126',\n",
428 |        "                                          'price': 399900,\n",
429 |        "                                          'status': 'Active',\n",
430 |        "                                          'type': 'compact_listing'},\n",
431 |        "                              'type': 'input_form_suggestion',\n",
432 |        "                              'value': '4th listing'},\n",
433 |        "                             {'listing': {'address': '2430 Victory Park Lane '\n",
434 |        "                                                     'Unit 1908',\n",
435 |        "                                          'baths': 2.1,\n",
436 |        "                                          'beds': 2,\n",
437 |        "                                          'close_date': None,\n",
438 |        "                                          'close_price': None,\n",
439 |        "                                          'id': '58a718e4-9f54-11e5-a0f8-f23c91c841bd',\n",
440 |        "                                          'mls': 'NTREIS',\n",
441 |        "                                          'mls_number': '13286938',\n",
442 |        "                                          'price': 999000,\n",
443 |        "                                          'status': 'Active',\n",
444 |        "                                          'type': 'compact_listing'},\n",
445 |        "                              'type': 'input_form_suggestion',\n",
446 |        "                              'value': '5th listing'}],\n",
447 |        "             'title': 'Which one of the following listings do you want to use?',\n",
448 |        "             'type': 'input_form_input'}],\n",
449 |        " 'type': 'input_form'}\n",
450 |        "
\n", 451 | "
\n", 452 | " \n", 453 | "
" 454 | ] 455 | }, 456 | "execution_count": null, 457 | "metadata": {}, 458 | "output_type": "execute_result" 459 | } 460 | ], 461 | "source": [ 462 | "_rendered_inp.children[3]" 463 | ] 464 | }, 465 | { 466 | "cell_type": "code", 467 | "execution_count": null, 468 | "id": "2bb77f62-5b71-4850-b9c4-adcf11c343cf", 469 | "metadata": {}, 470 | "outputs": [], 471 | "source": [ 472 | "assert len(_rendered_inp.children) == len(_run.inputs)" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": null, 478 | "id": "27668337-b353-4f8d-b83e-b5396ae49f2d", 479 | "metadata": {}, 480 | "outputs": [], 481 | "source": [ 482 | "#|export\n", 483 | "def render_funcs(run:RunData, markdown=True):\n", 484 | " \"Render functions as a group of cards.\"\n", 485 | " cards = []\n", 486 | " if run.funcs:\n", 487 | " num_inputs = len(run.funcs)\n", 488 | " for i,m in enumerate(run.funcs):\n", 489 | " nm = m.get('name', '')\n", 490 | " desc = m.get('description', '')\n", 491 | " content = json.dumps(m.get('parameters', ''), indent=4)\n", 492 | " cards.append(\n", 493 | " ui.card(\n", 494 | " ui.card_header(ui.div({\"style\": \"display: flex; justify-content: space-between;\"},\n", 495 | " ui.span(\n", 496 | " {\"style\": \"font-weight: bold;\"}, \n", 497 | " nm,\n", 498 | " ),\n", 499 | " ui.span(f'({i+1}/{num_inputs})'),\n", 500 | " ) \n", 501 | " ),\n", 502 | " x.ui.card_body(\n", 503 | " ui.strong(f'Description: {desc}'),\n", 504 | " ui.markdown(content) if markdown else content\n", 505 | " ),\n", 506 | " class_= \"card border-dark mb-3\"\n", 507 | " )\n", 508 | " )\n", 509 | " return ui.div(*cards)" 510 | ] 511 | }, 512 | { 513 | "cell_type": "markdown", 514 | "id": "6eb8bfdd-424e-4257-97e4-dc2be60be2bd", 515 | "metadata": {}, 516 | "source": [ 517 | "Similar to `render_input`, `render_funcs` will take an instance of `RunData` and render a set of Shiny cards, with each card containing a function definition that was passed to OpenAI via the [Function Calling API](https://platform.openai.com/docs/guides/gpt/function-calling):" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": null, 523 | "id": "f89c46e0-83f6-4930-befa-b900e8d9b96f", 524 | "metadata": {}, 525 | "outputs": [], 526 | "source": [ 527 | "_rendered_func = render_funcs(_run)\n", 528 | "assert len(_run.funcs) == len(_rendered_func.children)" 529 | ] 530 | }, 531 | { 532 | "cell_type": "markdown", 533 | "id": "98940744-c79f-41f5-b79c-4bfbe0012c0a", 534 | "metadata": {}, 535 | "source": [ 536 | "This is one of the functions:" 537 | ] 538 | }, 539 | { 540 | "cell_type": "code", 541 | "execution_count": null, 542 | "id": "287e01b6-5d9a-4390-8a59-7cdce17c61b9", 543 | "metadata": {}, 544 | "outputs": [ 545 | { 546 | "data": { 547 | "text/html": [ 548 | "
\n", 549 | "
\n", 550 | "
\n", 551 | " human-chat(3/5)\n", 552 | "
\n", 553 | "
\n", 554 | "
\n", 555 | " Description: You can ask a human for guidance when you think you got stuck or you are not sure what to do next. You can also ask him to clarify something or let user you dont know the answer to his request. You can also chat and hold a conversation with the human. Respond to their basic questions. You can also ask human generic questions. The input should be a question for the human.

{\n", 556 | ""type": "object",\n", 557 | ""$schema": "http://json-schema.org/draft-07/schema#",\n", 558 | ""properties": {\n", 559 | ""input": {\n", 560 | ""type": "string"\n", 561 | "}\n", 562 | "},\n", 563 | ""additionalProperties": false\n", 564 | "}

\n", 565 | "\n", 566 | "
\n", 567 | " \n", 568 | "
" 569 | ], 570 | "text/plain": [ 571 | "
\n", 572 | "
\n", 573 | "
\n", 574 | " human-chat(3/5)\n", 575 | "
\n", 576 | "
\n", 577 | "
\n", 578 | " Description: You can ask a human for guidance when you think you got stuck or you are not sure what to do next. You can also ask him to clarify something or let user you dont know the answer to his request. You can also chat and hold a conversation with the human. Respond to their basic questions. You can also ask human generic questions. The input should be a question for the human.

{\n", 579 | ""type": "object",\n", 580 | ""$schema": "http://json-schema.org/draft-07/schema#",\n", 581 | ""properties": {\n", 582 | ""input": {\n", 583 | ""type": "string"\n", 584 | "}\n", 585 | "},\n", 586 | ""additionalProperties": false\n", 587 | "}

\n", 588 | "\n", 589 | "
\n", 590 | " \n", 591 | "
" 592 | ] 593 | }, 594 | "execution_count": null, 595 | "metadata": {}, 596 | "output_type": "execute_result" 597 | } 598 | ], 599 | "source": [ 600 | "_rendered_func.children[2]" 601 | ] 602 | }, 603 | { 604 | "cell_type": "markdown", 605 | "id": "33126ccd-1c5c-480b-b275-7ac2fb2a2479", 606 | "metadata": {}, 607 | "source": [ 608 | "Here is another function:" 609 | ] 610 | }, 611 | { 612 | "cell_type": "code", 613 | "execution_count": null, 614 | "id": "90b23528-6a92-43cc-997e-a04abd057d7d", 615 | "metadata": {}, 616 | "outputs": [ 617 | { 618 | "data": { 619 | "text/html": [ 620 | "
\n", 621 | "
\n", 622 | "
\n", 623 | " calculator(4/5)\n", 624 | "
\n", 625 | "
\n", 626 | "
\n", 627 | " Description: Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.

{\n", 628 | ""type": "object",\n", 629 | ""$schema": "http://json-schema.org/draft-07/schema#",\n", 630 | ""properties": {\n", 631 | ""input": {\n", 632 | ""type": "string"\n", 633 | "}\n", 634 | "},\n", 635 | ""additionalProperties": false\n", 636 | "}

\n", 637 | "\n", 638 | "
\n", 639 | " \n", 640 | "
" 641 | ], 642 | "text/plain": [ 643 | "
\n", 644 | "
\n", 645 | "
\n", 646 | " calculator(4/5)\n", 647 | "
\n", 648 | "
\n", 649 | "
\n", 650 | " Description: Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.

{\n", 651 | ""type": "object",\n", 652 | ""$schema": "http://json-schema.org/draft-07/schema#",\n", 653 | ""properties": {\n", 654 | ""input": {\n", 655 | ""type": "string"\n", 656 | "}\n", 657 | "},\n", 658 | ""additionalProperties": false\n", 659 | "}

\n", 660 | "\n", 661 | "
\n", 662 | " \n", 663 | "
" 664 | ] 665 | }, 666 | "execution_count": null, 667 | "metadata": {}, 668 | "output_type": "execute_result" 669 | } 670 | ], 671 | "source": [ 672 | "_rendered_func.children[3]" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "id": "8452f09f-9b5a-4b73-916a-8ac8ac7f1e42", 679 | "metadata": {}, 680 | "outputs": [], 681 | "source": [ 682 | "#|export\n", 683 | "def render_llm_output(run, width=\"100%\", height=\"250px\"):\n", 684 | " \"Render the LLM output as an editable text box.\"\n", 685 | " o = run.output\n", 686 | " return ui.input_text_area('llm_output', label=ui.h3('LLM Output (Editable)'), \n", 687 | " value=o['content'], width=width, height=height)" 688 | ] 689 | }, 690 | { 691 | "cell_type": "markdown", 692 | "id": "5e216885-b011-4c97-8121-e8247b4ef587", 693 | "metadata": {}, 694 | "source": [ 695 | "Below is a demonstration of using `render_llm_output` to produce an editable text box component. The goal is to allow the user to edit the output for fine tuning to correct errors." 696 | ] 697 | }, 698 | { 699 | "cell_type": "code", 700 | "execution_count": null, 701 | "id": "81367c89-b457-4465-b611-1b5555365002", 702 | "metadata": {}, 703 | "outputs": [ 704 | { 705 | "data": { 706 | "text/html": [ 707 | "
\n", 708 | " \n", 716 | "
" 717 | ], 718 | "text/plain": [ 719 | "
\n", 720 | " \n", 728 | "
" 729 | ] 730 | }, 731 | "execution_count": null, 732 | "metadata": {}, 733 | "output_type": "execute_result" 734 | } 735 | ], 736 | "source": [ 737 | "render_llm_output(_tst_run)" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": null, 743 | "id": "8c935378-4b41-4aab-801d-c66b0a11eff1", 744 | "metadata": {}, 745 | "outputs": [], 746 | "source": [ 747 | "#|hide\n", 748 | "_rendered_out = render_llm_output(_run)\n", 749 | "assert _rendered_out.children[1].children[0] == _run.output['content']" 750 | ] 751 | }, 752 | { 753 | "cell_type": "code", 754 | "execution_count": null, 755 | "id": "d41f4308-67d0-4643-9a38-dcdffb100489", 756 | "metadata": {}, 757 | "outputs": [], 758 | "source": [ 759 | "#|export\n", 760 | "def invoke_later(delaySecs:int, callback:callable):\n", 761 | " \"Execute code in a shiny app with a time delay of `delaySecs` asynchronously.\"\n", 762 | " async def delay_task():\n", 763 | " await asyncio.sleep(delaySecs)\n", 764 | " async with reactive.lock():\n", 765 | " callback()\n", 766 | " await reactive.flush()\n", 767 | " asyncio.create_task(delay_task())" 768 | ] 769 | }, 770 | { 771 | "cell_type": "code", 772 | "execution_count": null, 773 | "id": "455c9bc6-2709-45fd-908f-b92464492ab9", 774 | "metadata": {}, 775 | "outputs": [], 776 | "source": [ 777 | "#|hide\n", 778 | "import nbdev; nbdev.nbdev_export()" 779 | ] 780 | }, 781 | { 782 | "cell_type": "code", 783 | "execution_count": null, 784 | "id": "ec06f16f-1f9e-4277-91a3-56870f1b2961", 785 | "metadata": {}, 786 | "outputs": [], 787 | "source": [] 788 | } 789 | ], 790 | "metadata": { 791 | "kernelspec": { 792 | "display_name": "python3", 793 | "language": "python", 794 | "name": "python3" 795 | } 796 | }, 797 | "nbformat": 4, 798 | "nbformat_minor": 5 799 | } 800 | -------------------------------------------------------------------------------- /nbs/CNAME: -------------------------------------------------------------------------------- 1 | langfree.parlance-labs.com -------------------------------------------------------------------------------- /nbs/_quarto.yml: -------------------------------------------------------------------------------- 1 | project: 2 | type: website 3 | 4 | format: 5 | html: 6 | theme: cosmo 7 | css: styles.css 8 | toc: true 9 | 10 | website: 11 | twitter-card: true 12 | open-graph: 13 | image: langfree.png 14 | repo-actions: [issue] 15 | navbar: 16 | background: primary 17 | search: true 18 | sidebar: 19 | style: floating 20 | favicon: favicon.png 21 | 22 | metadata-files: [nbdev.yml, sidebar.yml] -------------------------------------------------------------------------------- /nbs/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parlance-labs/langfree/6aee32f08b8b71b2af077249c1e9dc47f35e0b6d/nbs/favicon.png -------------------------------------------------------------------------------- /nbs/index.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "metadata": {}, 6 | "source": [ 7 | "---\n", 8 | "skip_showdoc: true\n", 9 | "skip_exec: true\n", 10 | "---" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "# langfree\n", 18 | "\n", 19 | "> Tools for extraction, transformation, and curation of `ChatOpenAI` runs from LangSmith." 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "::: {.content-visible when-format=\"markdown\"}\n", 27 | "[![](https://github.com/parlance-labs/langfree/actions/workflows/test.yaml/badge.svg)](https://github.com/parlance-labs/langfree/actions/workflows/test.yaml)\n", 28 | "[![Deploy to GitHub Pages](https://github.com/parlance-labs/langfree/actions/workflows/deploy.yaml/badge.svg)](https://github.com/parlance-labs/langfree/actions/workflows/deploy.yaml)\n", 29 | ":::" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "`langfree` helps you extract, transform and curate [ChatOpenAI](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) runs from [traces](https://js.langchain.com/docs/modules/agents/how_to/logging_and_tracing) stored in [LangSmith](https://www.langchain.com/langsmith), which can be used for fine-tuning and evaluation.\n", 37 | "\n", 38 | ":::{.content-visible when-format=\"html\"}\n", 39 | "![](langfree.png)\n", 40 | ":::\n", 41 | "\n", 42 | ":::{.content-visible when-format=\"markdown\"}\n", 43 | "![](https://github.com/parlance-labs/langfree/assets/1483922/0e37d5a4-1ffb-4661-85ba-7c9eb80dd06b)\n", 44 | ":::" 45 | ] 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "metadata": {}, 50 | "source": [ 51 | "### Motivation\n", 52 | "\n", 53 | "Langchain has native [tracing support](https://blog.langchain.dev/tracing/) that allows you to log runs. This data is a valuable resource for fine-tuning and evaluation. [LangSmith](https://docs.smith.langchain.com/) is a commercial application that facilitates some of these tasks.\n", 54 | "\n", 55 | "However, LangSmith may not suit everyone's needs. It is often desirable to buid your own data inspection and curation infrastructure:\n", 56 | "\n", 57 | "> One pattern I noticed is that great AI researchers are willing to manually inspect lots of data. And more than that, **they build infrastructure that allows them to manually inspect data quickly.** Though not glamorous, manually examining data gives valuable intuitions about the problem. The canonical example here is Andrej Karpathy doing the ImageNet 2000-way classification task himself.\n", 58 | "> \n", 59 | "> -- [Jason Wei, AI Researcher at OpenAI](https://x.com/_jasonwei/status/1708921475829481683?s=20)\n", 60 | "\n", 61 | "`langfree` helps you export data from LangSmith and build data curation tools. By building you own data curation tools, so you can add features you need like:\n", 62 | "\n", 63 | "- connectivity to data sources beyond LangSmith.\n", 64 | "- customized data transformations of runs.\n", 65 | "- ability to route, tag and annotate data in special ways.\n", 66 | "- ... etc.\n", 67 | "\n", 68 | "Furthermore,`langfree` provides a handful of [Shiny for Python](04_shiny.ipynb) components ease the process of creating data curation applications." 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "## Install" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "```sh\n", 83 | "pip install langfree\n", 84 | "```" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "## How to use\n", 92 | "\n", 93 | ":::{.content-visible when-format=\"markdown\"}\n", 94 | "\n", 95 | "See the [docs site](http://langfree.parlance-labs.com/).\n", 96 | "\n", 97 | ":::" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "### Get runs from LangSmith\n", 105 | "\n", 106 | "The [runs](01_runs.ipynb) module contains some utilities to quickly get runs. We can get the recent runs from langsmith like so:" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "#|hide\n", 116 | "import sys, os\n", 117 | "from langfree.runs import _temp_env_var\n", 118 | "tmp_env = ({'LANGCHAIN_API_KEY': os.environ['LANGCHAIN_API_KEY_PUB'],\n", 119 | " 'LANGSMITH_PROJECT_ID':'2a9996a3-f2d2-4c96-9bea-31a926c18b55'})" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [ 127 | { 128 | "name": "stdout", 129 | "output_type": "stream", 130 | "text": [ 131 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"11/03/2023\"), lte(start_time, \"11/07/2023\"))\n" 132 | ] 133 | } 134 | ], 135 | "source": [ 136 | "from langfree.runs import get_recent_runs\n", 137 | "runs = get_recent_runs(last_n_days=3, limit=5)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [ 145 | { 146 | "name": "stdout", 147 | "output_type": "stream", 148 | "text": [ 149 | "Fetching runs with this filter: and(eq(status, \"success\"), gte(start_time, \"04/20/2019\"), lte(start_time, \"09/07/2023\"))\n" 150 | ] 151 | } 152 | ], 153 | "source": [ 154 | "#|hide\n", 155 | "with _temp_env_var(tmp_env): runs = get_recent_runs(last_n_days=1600, limit=5)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "metadata": {}, 162 | "outputs": [ 163 | { 164 | "name": "stdout", 165 | "output_type": "stream", 166 | "text": [ 167 | "Fetched 5 runs\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "print(f'Fetched {len(list(runs))} runs')" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "There are other utlities like `get_runs_by_commit` if you are tagging runs by commit SHA. You can also use the [langsmith sdk](https://docs.smith.langchain.com/) to get runs." 180 | ] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "### Parse The Data\n", 187 | "\n", 188 | "`ChatRecordSet` parses the LangChain run in the following ways:\n", 189 | "\n", 190 | "- finds the last child run that calls the language model (`ChatOpenAI`) in the chain where the run resides. You are often interested in the last call to the language model in the chain when curating data for fine tuning.\n", 191 | "- extracts the inputs, outputs and function definitions that are sent to the language model.\n", 192 | "- extracts other metadata that influences the run, such as the model version and parameters." 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "metadata": {}, 198 | "source": [ 199 | "```python\n", 200 | "from langfree.chatrecord import ChatRecordSet\n", 201 | "llm_data = ChatRecordSet.from_runs(runs)\n", 202 | "```" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": null, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "#|hide\n", 212 | "with _temp_env_var(tmp_env): \n", 213 | " from langfree.chatrecord import ChatRecordSet\n", 214 | " llm_data = ChatRecordSet.from_runs(runs)" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "Inspect Data" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [ 229 | { 230 | "data": { 231 | "text/plain": [ 232 | "{'role': 'system',\n", 233 | " 'content': \"You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\\nThe current time is 2023-09-05 16:49:07.308007.\\n\\nRelevant documents will be retrieved in the following messages.\"}" 234 | ] 235 | }, 236 | "execution_count": null, 237 | "metadata": {}, 238 | "output_type": "execute_result" 239 | } 240 | ], 241 | "source": [ 242 | "llm_data[0].child_run.inputs[0]" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": null, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "data": { 252 | "text/plain": [ 253 | "{'role': 'assistant',\n", 254 | " 'content': \"Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Here's an example of exporting runs:\\n\\n1. Read the runs from the source organization using the SDK.\\n2. Write the runs to the destination organization using the SDK.\\n\\nBy following this process, you can transfer your runs from one organization to another. However, it may be faster to create a new project within your destination organization and start fresh.\\n\\nIf you have any further questions or need assistance, please reach out to us at support@langchain.dev.\"}" 255 | ] 256 | }, 257 | "execution_count": null, 258 | "metadata": {}, 259 | "output_type": "execute_result" 260 | } 261 | ], 262 | "source": [ 263 | "llm_data[0].child_run.output" 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "metadata": {}, 269 | "source": [ 270 | "You can also see a flattened version of the input and the output" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "metadata": {}, 277 | "outputs": [ 278 | { 279 | "name": "stdout", 280 | "output_type": "stream", 281 | "text": [ 282 | "### System\n", 283 | "\n", 284 | "You are a helpful documentation Q&A assistant, trained to answer questions from LangSmith's documentation. LangChain is a framework for building applications using large language models.\n", 285 | "T\n" 286 | ] 287 | } 288 | ], 289 | "source": [ 290 | "print(llm_data[0].flat_input[:200])" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": null, 296 | "metadata": {}, 297 | "outputs": [ 298 | { 299 | "name": "stdout", 300 | "output_type": "stream", 301 | "text": [ 302 | "### Assistant\n", 303 | "\n", 304 | "Currently, LangSmith does not support project migration between organizations. However, you can manually imitate this process by reading and writing runs and datasets using the SDK. Her\n" 305 | ] 306 | } 307 | ], 308 | "source": [ 309 | "print(llm_data[0].flat_output[:200])" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "### Transform The Data\n", 317 | "\n", 318 | "Perform data augmentation by rephrasing the first human input. Here is the first human input before data augmentation:" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "metadata": {}, 325 | "outputs": [ 326 | { 327 | "data": { 328 | "text/plain": [ 329 | "[{'role': 'user',\n", 330 | " 'content': 'How do I move my project between organizations?'}]" 331 | ] 332 | }, 333 | "execution_count": null, 334 | "metadata": {}, 335 | "output_type": "execute_result" 336 | } 337 | ], 338 | "source": [ 339 | "run = llm_data[0].child_run\n", 340 | "[x for x in run.inputs if x['role'] == 'user']" 341 | ] 342 | }, 343 | { 344 | "cell_type": "markdown", 345 | "metadata": {}, 346 | "source": [ 347 | "Update the inputs:" 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": null, 353 | "metadata": {}, 354 | "outputs": [ 355 | { 356 | "name": "stdout", 357 | "output_type": "stream", 358 | "text": [ 359 | "rephrased input as: How can I transfer my project from one organization to another?\n" 360 | ] 361 | } 362 | ], 363 | "source": [ 364 | "from langfree.transform import reword_input\n", 365 | "run.inputs = reword_input(run.inputs)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "markdown", 370 | "metadata": {}, 371 | "source": [ 372 | "Check that the inputs are updated correctly:" 373 | ] 374 | }, 375 | { 376 | "cell_type": "code", 377 | "execution_count": null, 378 | "metadata": {}, 379 | "outputs": [ 380 | { 381 | "data": { 382 | "text/plain": [ 383 | "[{'role': 'user',\n", 384 | " 'content': 'How can I transfer my project from one organization to another?'}]" 385 | ] 386 | }, 387 | "execution_count": null, 388 | "metadata": {}, 389 | "output_type": "execute_result" 390 | } 391 | ], 392 | "source": [ 393 | "[x for x in run.inputs if x['role'] == 'user']" 394 | ] 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "metadata": {}, 399 | "source": [ 400 | "You can also call `.to_dicts()` to convert `llm_data` to a list of dicts that can be converted to jsonl for fine-tuning OpenAI models." 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "metadata": {}, 407 | "outputs": [ 408 | { 409 | "name": "stdout", 410 | "output_type": "stream", 411 | "text": [ 412 | "dict_keys(['functions', 'messages']) 5\n" 413 | ] 414 | } 415 | ], 416 | "source": [ 417 | "llm_dicts = llm_data.to_dicts()\n", 418 | "print(llm_dicts[0].keys(), len(llm_dicts))" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "metadata": {}, 424 | "source": [ 425 | "You can use `write_to_jsonl` and `validate_jsonl` to help write this data to `.jsonl` and validate it." 426 | ] 427 | }, 428 | { 429 | "cell_type": "markdown", 430 | "metadata": {}, 431 | "source": [ 432 | "## Build & Customize Tools For Curating LLM Data" 433 | ] 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "metadata": {}, 438 | "source": [ 439 | "The previous steps showed you how to collect and transform your data from LangChain runs. Next, you can feed this data into a tool to help you curate this data for fine tuning.\n", 440 | "\n", 441 | "To learn how to run and customize this kind of tool, [read the tutorial](tutorials/shiny.ipynb). `langfree` can help you quickly build something that looks like this:" 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "metadata": {}, 447 | "source": [ 448 | ":::{.content-visible when-format=\"html\"}\n", 449 | "![](tutorials/screenshot.png)\n", 450 | ":::\n", 451 | "\n", 452 | ":::{.content-visible when-format=\"markdown\"}\n", 453 | "![](https://github.com/parlance-labs/langfree/assets/1483922/57d98336-d43f-432b-a730-e41261168cb2)\n", 454 | ":::" 455 | ] 456 | }, 457 | { 458 | "cell_type": "markdown", 459 | "metadata": {}, 460 | "source": [ 461 | ":::{.content-visible when-format=\"markdown\"}\n", 462 | "\n", 463 | "## Documentation\n", 464 | "\n", 465 | "See the [docs site](http://langfree.parlance-labs.com/).\n", 466 | "\n", 467 | ":::" 468 | ] 469 | }, 470 | { 471 | "cell_type": "markdown", 472 | "metadata": {}, 473 | "source": [ 474 | "## FAQ\n", 475 | "\n", 476 | "1. **We don't use LangChain. Can we still use something from this library?** No, not directly. However, we recommend looking at how the [Shiny for Python App works](tutorials/shiny.ipynb) so you can adapt it towards your own use cases.\n", 477 | "\n", 478 | "2. **Why did you use [Shiny For Python](https://shiny.posit.co/py/)?** Python has many great front-end libraries like Gradio, Streamlit, Panel and others. However, we liked Shiny For Python the best, because of its reactive model, modularity, strong integration with [Quarto](https://quarto.org/), and [WASM support](https://shiny.posit.co/py/docs/shinylive.html). You can read more about it [here](https://shiny.posit.co/py/docs/overview.html).\n", 479 | "\n", 480 | "3. **Does this only work with runs from LangChain/LangSmith?** Yes, `langfree` has only been tested with `LangChain` runs that have been logged to`LangSmith`, however we suspect that you could log your traces elsewhere and pull them in a similar manner.\n", 481 | "\n", 482 | "4. **Does this only work with [`ChatOpenAI`](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) runs?** A: Yes, `langfree` is opinionated and only works with runs that use chat models from OpenAI (which use [`ChatOpenAI`](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) in LangChain). We didn't want to over-generalize this tool too quickly and started with the most popular combination of things.\n", 483 | "\n", 484 | "5. **Do you offer support?**: These tools are free and licensed under [Apache 2.0](https://github.com/parlance-labs/langfree/blob/main/LICENSE). If you want support or customization, feel free to [reach out to us](https://parlance-labs.com/).\n" 485 | ] 486 | }, 487 | { 488 | "cell_type": "markdown", 489 | "metadata": {}, 490 | "source": [ 491 | "## Contributing" 492 | ] 493 | }, 494 | { 495 | "cell_type": "markdown", 496 | "metadata": {}, 497 | "source": [ 498 | "This library was created with [nbdev](https://nbdev.fast.ai/). See [Contributing.md](https://github.com/parlance-labs/langfree/blob/main/CONTRIBUTING.md) for further guidelines." 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "metadata": {}, 505 | "outputs": [], 506 | "source": [] 507 | } 508 | ], 509 | "metadata": { 510 | "kernelspec": { 511 | "display_name": "python3", 512 | "language": "python", 513 | "name": "python3" 514 | } 515 | }, 516 | "nbformat": 4, 517 | "nbformat_minor": 4 518 | } 519 | -------------------------------------------------------------------------------- /nbs/langfree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parlance-labs/langfree/6aee32f08b8b71b2af077249c1e9dc47f35e0b6d/nbs/langfree.png -------------------------------------------------------------------------------- /nbs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parlance-labs/langfree/6aee32f08b8b71b2af077249c1e9dc47f35e0b6d/nbs/logo.png -------------------------------------------------------------------------------- /nbs/nbdev.yml: -------------------------------------------------------------------------------- 1 | project: 2 | output-dir: _docs 3 | 4 | website: 5 | title: "langfree" 6 | site-url: "https://parlance-labs.github.io/langfree" 7 | description: "Utilities to help you work with your language model data outside LangSmith" 8 | repo-branch: main 9 | repo-url: "https://github.com/parlance-labs/langfree" 10 | -------------------------------------------------------------------------------- /nbs/sidebar.yml: -------------------------------------------------------------------------------- 1 | website: 2 | sidebar: 3 | contents: 4 | - index.ipynb 5 | - 01_runs.ipynb 6 | - 02_transform.ipynb 7 | - 03_chatrecord.ipynb 8 | - 04_shiny.ipynb 9 | - section: tutorials 10 | contents: 11 | - tutorials/shiny.ipynb 12 | -------------------------------------------------------------------------------- /nbs/styles.css: -------------------------------------------------------------------------------- 1 | .cell { 2 | margin-bottom: 1rem; 3 | } 4 | 5 | .cell > .sourceCode { 6 | margin-bottom: 0; 7 | } 8 | 9 | .cell-output > pre { 10 | margin-bottom: 0; 11 | } 12 | 13 | .cell-output > pre, .cell-output > .sourceCode > pre, .cell-output-stdout > pre { 14 | margin-left: 0.8rem; 15 | margin-top: 0; 16 | background: none; 17 | border-left: 2px solid lightsalmon; 18 | border-top-left-radius: 0; 19 | border-top-right-radius: 0; 20 | } 21 | 22 | .cell-output > .sourceCode { 23 | border: none; 24 | } 25 | 26 | .cell-output > .sourceCode { 27 | background: none; 28 | margin-top: 0; 29 | } 30 | 31 | div.description { 32 | padding-left: 2px; 33 | padding-top: 5px; 34 | font-style: italic; 35 | font-size: 135%; 36 | opacity: 70%; 37 | } 38 | -------------------------------------------------------------------------------- /nbs/tutorials/_data/sample_data.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parlance-labs/langfree/6aee32f08b8b71b2af077249c1e9dc47f35e0b6d/nbs/tutorials/_data/sample_data.pkl -------------------------------------------------------------------------------- /nbs/tutorials/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | from shiny import App, ui, reactive, render 3 | import shiny.experimental as x 4 | from langfree.shiny import render_input_chat, render_llm_output 5 | import pandas as pd 6 | 7 | 8 | FILENAME = "_data/sample_data.pkl" 9 | df = pd.read_pickle(FILENAME) 10 | n_rows = len(df) 11 | def save(df): df.to_pickle(FILENAME) 12 | 13 | status_styles = {'Accepted': 'bg-success', 'Rejected': 'bg-danger','Pending': 'bg-warning'} 14 | status_icons = {'Accepted': ui.HTML(''), 15 | 'Rejected': ui.HTML(''), 16 | 'Pending': ui.HTML('') 17 | } 18 | 19 | app_ui = ui.page_fluid( 20 | ui.panel_title("Fine Tune Data Review"), 21 | ui.div( 22 | {"style": "position: absolute; top: 10px; right: 10px; font-size: 0.8em;"}, 23 | ui.a("by Parlance Labs", href="https://parlance-labs.com/") 24 | ), 25 | x.ui.card( 26 | ui.layout_sidebar( 27 | ui.panel_sidebar( 28 | ui.output_ui("status_card"), 29 | ui.output_data_frame("stats"), 30 | ), 31 | ui.panel_main( 32 | ui.output_ui("llm_input"), 33 | ), 34 | ), 35 | max_height="900px", 36 | ), 37 | x.ui.card( 38 | x.ui.card_body( 39 | ui.output_ui("llm_output"), 40 | ), 41 | ui.div( 42 | {"style": "display: flex; justify-content:center;"}, 43 | ui.input_action_button("accept", label="Accept", class_='btn-success', width="10%", style="margin-right: 10px;"), 44 | ui.input_action_button("reject", label="Reject", class_='btn-danger', width="10%", style="margin-right: 50px;"), 45 | ui.input_action_button("back", label="Back", class_='btn-secondary', width="10%", style="margin-right: 10px;"), 46 | ui.input_action_button("reset", label="Reset", class_='btn-warning', width="10%", style="margin-right: 10px;"), 47 | ui.input_action_button("next", label="Next", class_='btn-secondary', width="10%", style="margin-right: 10px;"), 48 | ) 49 | ), 50 | ) 51 | 52 | def server(input, output, session): 53 | cursor = reactive.Value(0) 54 | status_trigger = reactive.Value(True) 55 | 56 | @reactive.Calc 57 | def current_run(): 58 | _ = status_trigger() 59 | return df.loc[cursor(), 'child_run'] 60 | 61 | @reactive.Calc 62 | def current_row(): 63 | _ = status_trigger() 64 | return df.loc[cursor()] 65 | 66 | @reactive.Calc 67 | def progress(): return f"Record {cursor()+1} of {n_rows:,}" 68 | 69 | @output 70 | @render.ui 71 | def llm_input(): return render_input_chat(current_run()) 72 | 73 | @output 74 | @render.ui 75 | def llm_output(): return render_llm_output(current_run()) 76 | 77 | @output 78 | @render.data_frame 79 | def stats(): 80 | _ = status_trigger() 81 | return df.groupby('status').count().reset_index().rename(columns={'child_run': 'Count', 'status': 'Status'})[['Status', 'Count']] 82 | 83 | @output 84 | @render.ui 85 | def status_card(): 86 | status = current_row().status 87 | return x.ui.value_box(title=ui.h1(f'Status: {status}'), 88 | value=ui.h2(progress()), 89 | showcase=status_icons[status], 90 | class_=status_styles[status]) 91 | 92 | @reactive.Effect 93 | @reactive.event(input.reset) 94 | def reset(): 95 | update_status('Pending') 96 | save(df) 97 | 98 | @reactive.Effect 99 | @reactive.event(input.reject) 100 | def reject(): 101 | update_status('Rejected') 102 | go_next() 103 | 104 | @reactive.Effect 105 | @reactive.event(input.accept) 106 | def accept(): 107 | update_status('Accepted') 108 | current_row().child_run.output['content'] = input.llm_output() 109 | go_next() 110 | 111 | @reactive.Effect 112 | @reactive.event(input.back) 113 | def back(): 114 | if cursor() > 0: cursor.set(cursor()-1) 115 | 116 | @reactive.Effect 117 | @reactive.event(input.next) 118 | def next(): go_next() 119 | 120 | def modal(): 121 | m = ui.modal("You are done!", title="Done",easy_close=True,footer=None) 122 | ui.modal_show(m) 123 | 124 | def go_next(): 125 | save(df) 126 | if cursor() + 1 < n_rows: cursor.set(cursor()+1) 127 | else: modal() 128 | 129 | def update_status(status): 130 | df.loc[cursor(), 'status'] = status 131 | status_trigger.set(not status_trigger()) 132 | 133 | abs_path = os.path.join(os.path.dirname(__file__), 'assets') 134 | app = App(app_ui, server, static_assets=abs_path) -------------------------------------------------------------------------------- /nbs/tutorials/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parlance-labs/langfree/6aee32f08b8b71b2af077249c1e9dc47f35e0b6d/nbs/tutorials/screenshot.png -------------------------------------------------------------------------------- /nbs/tutorials/shiny.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "id": "5edc76b6-62a1-4bf9-9be7-344214bcfc57", 6 | "metadata": {}, 7 | "source": [ 8 | "---\n", 9 | "skip_showdoc: true\n", 10 | "skip_exec: true\n", 11 | "---" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "id": "376dfa7e-5578-418e-b07f-a46b07a8ef05", 17 | "metadata": {}, 18 | "source": [ 19 | "# App To Review LLM Data" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "id": "5083a7db-e773-48eb-aaed-41f321d27eb3", 25 | "metadata": {}, 26 | "source": [ 27 | "> How to use `langfree` to build an app you can use to review LLM data." 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "id": "7941b249-8947-4497-b1e3-cd60fe9d6418", 33 | "metadata": {}, 34 | "source": [ 35 | "The motivation for building your own review app is discussed on [the homepage](../#Motivation). This tutorial walks you through how you can build a minimal app using [Shiny For Python](https://shiny.posit.co/py/).\n", 36 | "\n", 37 | "### Prerequisites\n", 38 | "\n", 39 | "- Runs logged to LangSmith that contain `ChatOpenAI` child runs.\n", 40 | "- Set the `LANGCHAIN_API_KEY`, `LANGSMITH_PROJECT_ID` and `LANGCHAIN_ENDPOINT` environment variables as [described here](https://docs.smith.langchain.com/).\n", 41 | "- Install langfree: `pip install langfree`\n", 42 | "- Clone this repo: `git clone https://github.com/parlance-labs/langfree.git`\n", 43 | "\n", 44 | "### 1. Pull Data From Langsmith\n", 45 | "\n", 46 | ":::{.callout-note}\n", 47 | "### If you have not logged runs to LangSmith\n", 48 | "\n", 49 | "If you have not logged runs to LangSmith and want to see the app, you can skip to the next step and use the sample data in this repo, which is located in the [nbs/tutorials/_data](https://github.com/parlance-labs/langfree/tree/main/nbs/tutorials/_data) directory.\n", 50 | "\n", 51 | "However, it is probably more interesting to use this with your own data.\n", 52 | ":::\n", 53 | "\n", 54 | "First, we will pull data from LangSmith. There are many ways to do this, including using the `langsmith` client, which we illustrate below. \n", 55 | "\n", 56 | "We will pull four specific run ids, parse the data and save it to a dataframe named `sample_data.pkl` that we will use as our backend \"database\" [^2] for demo purposes. We initialize all records to have a status of `Pending`.\n", 57 | "\n", 58 | "[^1]: See the [deployment](#deployment) section for resources on how you can easily deploy a Shiny app with authentication.\n", 59 | "[^2]: We recommend using a real database for production applications, but this allows you to get an understanding of how the system works." 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "id": "0ee5bd65-5915-4eea-8919-3d6e62b73579", 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "#|hide\n", 70 | "#|eval: false\n", 71 | "import os\n", 72 | "from langfree.chatrecord import ChatRecordSet \n", 73 | "import pandas as pd\n", 74 | "from langfree.runs import _temp_env_var\n", 75 | "from langsmith import Client\n", 76 | "\n", 77 | "_tst_run_ids = ['a05e1668-57b4-4e4d-99d9-1f8578ddba5d',\n", 78 | " '6b9f6c78-dbef-4352-8e4e-0b1777b59cf0',\n", 79 | " 'cebad2c1-a00b-43ee-86d0-1d42310e744a',\n", 80 | " '2e1e7686-ae4b-45ab-bae0-0fb18749f1d2']\n", 81 | "\n", 82 | "tmp_env = ({'LANGCHAIN_API_KEY': os.environ['LANGCHAIN_API_KEY_PUB'],\n", 83 | " 'LANGSMITH_PROJECT_ID':'2a9996a3-f2d2-4c96-9bea-31a926c18b55'})\n", 84 | "\n", 85 | "with _temp_env_var(tmp_env): # sets temporary enviornment variabes for testing.\n", 86 | " llm_data=ChatRecordSet.from_run_ids(_tst_run_ids)\n", 87 | " llm_data_df = llm_data.to_pandas()\n", 88 | " llm_data_df['status'] = 'Pending'\n", 89 | " llm_data_df.to_pickle('_data/sample_data.pkl')" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "id": "b73538d5-2712-49d3-b286-2466df8c9217", 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "#|hide\n", 100 | "#|eval: false\n", 101 | "# just for shiny live\n", 102 | "from pydantic import BaseModel\n", 103 | "import json\n", 104 | "from typing import List\n", 105 | "class RunData(BaseModel):\n", 106 | " \"Key components of a run from LangSmith\"\n", 107 | " inputs:List[dict]\n", 108 | " output:dict\n", 109 | " funcs:List[dict] \n", 110 | " run_id:str\n", 111 | "\n", 112 | "shiny_live_df = llm_data_df.copy().head(3)\n", 113 | "shiny_live_df[['child_run', 'status']].to_json('_data/shiny_live.json')" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "id": "7c35f11b-74c5-44fb-be5c-ac21cc6baf89", 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "id": "c84fda6f-b9dc-40a6-8a5b-cd89b695c9f6", 128 | "metadata": {}, 129 | "outputs": [ 130 | { 131 | "data": { 132 | "text/plain": [ 133 | "0 inputs=[{'role': 'system', 'content': \"You are...\n", 134 | "1 inputs=[{'role': 'system', 'content': \"You are...\n", 135 | "2 inputs=[{'role': 'system', 'content': \"You are...\n", 136 | "Name: child_run, dtype: object" 137 | ] 138 | }, 139 | "execution_count": null, 140 | "metadata": {}, 141 | "output_type": "execute_result" 142 | } 143 | ], 144 | "source": [ 145 | "_df = pd.read_json('_data/shiny_live.json')\n", 146 | "_df['child_run'].apply(lambda x: RunData(**x))" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "id": "8c86b14c-226a-4afb-a01a-ed23c60cf31d", 152 | "metadata": {}, 153 | "source": [ 154 | "```python\n", 155 | "from langsmith import Client # <1>\n", 156 | "from langfree.chatrecord import ChatRecordSet # <2>\n", 157 | "\n", 158 | "# Change these run IDs to your runs\n", 159 | "run_ids = ['a05e1668-57b4-4e4d-99d9-1f8578ddba5d', # <3>\n", 160 | " '6b9f6c78-dbef-4352-8e4e-0b1777b59cf0', # <3>\n", 161 | " 'cebad2c1-a00b-43ee-86d0-1d42310e744a', # <3>\n", 162 | " '2e1e7686-ae4b-45ab-bae0-0fb18749f1d2'] # <3>\n", 163 | "\n", 164 | "llm_data=ChatRecordSet.from_run_ids(run_ids) # <4>\n", 165 | "llm_data_df = llm_data.to_pandas() # <5>\n", 166 | "llm_data_df['status'] = 'Pending' # <6>\n", 167 | "llm_data_df.to_pickle('_data/sample_data.pkl') # <7>\n", 168 | "```\n", 169 | "1. The [langsmith sdk](https://github.com/langchain-ai/langsmith-sdk) offers the simplest way to retreive runs. However, there are additional utilities for retreiving runs provided in [`langfree.runs`](../01_runs.ipynb).\n", 170 | "2. `ChatRecordSet` allows you to parse and extract key information from your langchain [ChatOpenAI](https://api.python.langchain.com/en/latest/chat_models/langchain.chat_models.openai.ChatOpenAI.html) runs.\n", 171 | "3. These are the run ids that we will pull from langsmith. You will have to pull your own run ids. Make sure that your runs have at least one child that is of type `ChatOpenAI` for this to work. \n", 172 | "4. `ChatRecordSet.from_run_ids` allows you to fetch and parse this data froma list of run ids.\n", 173 | "5. `ChatRecordSet.to_pandas` allows you to convert this data into a pandas DataFrame\n", 174 | "6. The status of each record is initialized to `Pending` which will changed by the front end app depending on user actions.\n", 175 | "7. Finally, we save the data to `_data/sample_data.pkl` which will be read by the front end application." 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "id": "c9bb9c17-5af4-4857-a215-7dca08a4f121", 181 | "metadata": {}, 182 | "source": [ 183 | "### 2. Run the Shiny App Locally\n", 184 | "\n", 185 | "Assuming you have completed the [Prerequisites](#prerequisites), go to the `nbs/tutorials/` folder from the root of the `langfree` repo you cloned locally. \n", 186 | "\n", 187 | "Execute Shiny by running:\n", 188 | "\n", 189 | "```\n", 190 | "shiny run app.py --reload\n", 191 | "```" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "id": "22968acd-1787-4310-a81a-0f8f3a4247ab", 197 | "metadata": {}, 198 | "source": [ 199 | "![](screenshot.png)" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "id": "1a1a0e17-5339-4413-81d1-bec361f95166", 205 | "metadata": {}, 206 | "source": [ 207 | "### 3. Read The Code & Modify It\n", 208 | "\n", 209 | "The web application defined in [app.py](https://github.com/parlance-labs/langfree/blob/main/nbs/tutorials/app.py) is around 150 lines of code, in python. This means you can easily hack it suit your own needs! Some resources that are helpful in understanding Shiny and this code:\n", 210 | "\n", 211 | "- Do the excercises on Gordon Shotwell's [Shiny for Python Tutorial](https://posit-dev.github.io/shiny-python-workshop-2023/)\n", 212 | "- Read the [Shiny for Python documentation](https://shiny.posit.co/py/docs/overview.html).\n", 213 | "\n", 214 | "#### Suggested modifications:\n", 215 | "\n", 216 | "- Add more information to the side panel.\n", 217 | "- Connect to a remote backend database (instead of the DataFrame) using [reactive.poll](https://shiny.posit.co/py/api/reactive.poll.html) or [reactive.file_reader](https://shiny.posit.co/py/api/reactive.file_reader.html).\n", 218 | "- Advanced: adapt the hotkeys from this [Wordle example](https://shinylive.io/py/examples/#wordle) so that they work these buttons.\n", 219 | "\n", 220 | "### 4. Deploy\n", 221 | "\n", 222 | "Here are detailed guides for [cloud hosting](https://shiny.posit.co/py/docs/deploy-cloud.html) and [self hosted deployments](https://shiny.posit.co/py/docs/deploy-on-prem.html) for Shiny apps. Some of the cloud hosting providers provide an easy way to add an authentication layer on top of your Shiny apps incase you want to make your apps private." 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "id": "a415a421-5125-4586-9f92-4c511650a76a", 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [] 232 | } 233 | ], 234 | "metadata": { 235 | "kernelspec": { 236 | "display_name": "python3", 237 | "language": "python", 238 | "name": "python3" 239 | } 240 | }, 241 | "nbformat": 4, 242 | "nbformat_minor": 5 243 | } 244 | -------------------------------------------------------------------------------- /settings.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | repo = langfree 3 | lib_name = langfree 4 | version = 0.0.32 5 | min_python = 3.7 6 | license = apache2 7 | black_formatting = False 8 | doc_path = _docs 9 | lib_path = langfree 10 | nbs_path = nbs 11 | recursive = True 12 | tst_flags = notest 13 | put_version_in_init = True 14 | branch = main 15 | custom_sidebar = False 16 | doc_host = https://parlance-labs.github.io 17 | doc_baseurl = /langfree 18 | git_url = https://github.com/parlance-labs/langfree 19 | title = langfree 20 | audience = Developers 21 | author = Hamel Husain 22 | author_email = hamel.husain@gmail.com 23 | copyright = 2023 onwards, Hamel Husain 24 | description = Utilities to help you work with your language model data outside LangSmith 25 | keywords = nbdev jupyter notebook python langchain langsmith openai 26 | language = English 27 | status = 3 28 | user = parlance-labs 29 | requirements = fastcore pandas tabulate langchain>=0.1.9 langsmith>=0.1.9 pydantic openai>=1.6.1 shiny>=0.6.1.1 langchain_core>=0.1.27 30 | readme_nb = index.ipynb 31 | allowed_metadata_keys = 32 | allowed_cell_metadata_keys = 33 | jupyter_hooks = True 34 | clean_ids = True 35 | clear_all = False 36 | 37 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from pkg_resources import parse_version 2 | from configparser import ConfigParser 3 | import setuptools, shlex 4 | assert parse_version(setuptools.__version__)>=parse_version('36.2') 5 | 6 | # note: all settings are in settings.ini; edit there, not here 7 | config = ConfigParser(delimiters=['=']) 8 | config.read('settings.ini', encoding='utf-8') 9 | cfg = config['DEFAULT'] 10 | 11 | cfg_keys = 'version description keywords author author_email'.split() 12 | expected = cfg_keys + "lib_name user branch license status min_python audience language".split() 13 | for o in expected: assert o in cfg, "missing expected setting: {}".format(o) 14 | setup_cfg = {o:cfg[o] for o in cfg_keys} 15 | 16 | licenses = { 17 | 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'), 18 | 'mit': ('MIT License', 'OSI Approved :: MIT License'), 19 | 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'), 20 | 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'), 21 | 'bsd3': ('BSD License', 'OSI Approved :: BSD License'), 22 | } 23 | statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha', 24 | '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ] 25 | py_versions = '3.6 3.7 3.8 3.9 3.10'.split() 26 | 27 | requirements = shlex.split(cfg.get('requirements', '')) 28 | if cfg.get('pip_requirements'): requirements += shlex.split(cfg.get('pip_requirements', '')) 29 | min_python = cfg['min_python'] 30 | lic = licenses.get(cfg['license'].lower(), (cfg['license'], None)) 31 | dev_requirements = (cfg.get('dev_requirements') or '').split() 32 | 33 | setuptools.setup( 34 | name = cfg['lib_name'], 35 | license = lic[0], 36 | classifiers = [ 37 | 'Development Status :: ' + statuses[int(cfg['status'])], 38 | 'Intended Audience :: ' + cfg['audience'].title(), 39 | 'Natural Language :: ' + cfg['language'].title(), 40 | ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []), 41 | url = cfg['git_url'], 42 | packages = setuptools.find_packages(), 43 | include_package_data = True, 44 | install_requires = requirements, 45 | extras_require={ 'dev': dev_requirements }, 46 | dependency_links = cfg.get('dep_links','').split(), 47 | python_requires = '>=' + cfg['min_python'], 48 | long_description = open('README.md', encoding='utf-8').read(), 49 | long_description_content_type = 'text/markdown', 50 | zip_safe = False, 51 | entry_points = { 52 | 'console_scripts': cfg.get('console_scripts','').split(), 53 | 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d'] 54 | }, 55 | **setup_cfg) 56 | 57 | 58 | --------------------------------------------------------------------------------