aimagics 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aimagics-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,5 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.4
2
+ Name: aimagics
3
+ Version: 0.0.1
4
+ Summary: LLM access from within Jupyter notebooks via line and cell magic commands
5
+ Author-email: adrische <adrianscheerer@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/adrische/aimagics
8
+ Project-URL: Documentation, https://adrische.github.io/aimagics/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.2.19
16
+ Requires-Dist: IPython
17
+ Requires-Dist: nbformat>=5.11.1
18
+ Requires-Dist: ipynbname>=2025.8.0.0
19
+ Requires-Dist: traitlets>=5.14.3
20
+ Requires-Dist: aidialog>=0.0.23
21
+ Requires-Dist: python-fastllm>=0.0.49
22
+ Requires-Dist: nbdev>=3.3.15
23
+ Dynamic: license-file
24
+
25
+ # aimagics
26
+
27
+
28
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
29
+
30
+ ![](Screenshot.png)
31
+
32
+ ## Installation
33
+
34
+ Install latest from the GitHub [repository](https://github.com/adrische/aimagics):
35
+
36
+ ``` sh
37
+ $ pip install git+https://github.com/adrische/aimagics.git
38
+ ```
39
+
40
+ or from [conda](https://anaconda.org/adrische/aimagics)
41
+
42
+ ``` sh
43
+ $ conda install -c adrische aimagics
44
+ ```
45
+
46
+ or from [pypi](https://pypi.org/project/aimagics/)
47
+
48
+ ``` sh
49
+ $ pip install aimagics
50
+ ```
51
+
52
+ ## Setup
53
+
54
+ ### 1. Load the package
55
+
56
+ After installation, you can load the package in Jupyter and ipython with
57
+
58
+ ``` python
59
+ %load_ext aimagics
60
+ ```
61
+
62
+ Whether the package has been loaded can be checked with
63
+
64
+ ``` python
65
+ from IPython import get_ipython
66
+ get_ipython().extension_manager.loaded
67
+ ```
68
+
69
+ {'IPython.extensions.storemagic', 'aimagics'}
70
+
71
+ ‘aimagics’ should appear in the output.
72
+
73
+ ### 2. Set LLM API key
74
+
75
+ You should set your environment API key to your favorite LLM provider. The default model is
76
+
77
+ ``` python
78
+ AIMagics().model
79
+ ```
80
+
81
+ 'openrouter/openai/gpt-oss-120b'
82
+
83
+ so the environment key needed is `OPENROUTER_API_KEY`.
84
+
85
+ All [LiteLLM](https://models.litellm.ai/) models are compatible.
86
+
87
+ ### 3. Turn auto save on
88
+
89
+ The package works by retrieving the current notebook from disk. To always get the current state, it is recommended to turn auto save on. This is the default in jupyter notebooks, and can be toggled in vscode via `Show and Run Commands` \> `File: Toggle Auto Save`.
90
+
91
+ ## Usage
92
+
93
+ The package exposes two commands: `%ai` and `%%ai`. These are so-called ‘line’ and ‘cell magics’ and can be used as follows:
94
+
95
+ ### Line magic
96
+
97
+ The command `%ai` processes what comes after on the same line as request to the LLM:
98
+
99
+ ``` python
100
+ %ai What is aimagics?
101
+ ```
102
+
103
+ **`aimagics`** is a Python package and IPython extension that brings Large Language Model (LLM) capabilities directly into Jupyter notebooks via magic commands.
104
+
105
+ ### Key Features:
106
+
107
+ - **Magic Commands**: Offers `%ai` (line magic) and `%%ai` (cell magic) to interact with models directly within code cells.
108
+ - **Context-Aware**: Reads the current notebook state from disk to provide context-aware responses to your code and markdown.
109
+ - **Broad Model Support**: Built on [LiteLLM](https://models.litellm.ai/), allowing you to connect to OpenRouter, OpenAI, Anthropic, and dozens of other LLM providers.
110
+
111
+ ### Cell magic
112
+
113
+ The command `%%ai` processes what comes after it on the same line, but also what is in the same cell below it:
114
+
115
+ <!-- Sorry this is hard-coded because of some issues with getting the output of %%ai in nbdev.
116
+ The code ran as expected, see hidden cell below-->
117
+
118
+ ``` python
119
+ %%ai Why does the following code fail?
120
+ 1/0
121
+ ```
122
+
123
+ **Answer**
124
+
125
+ ``` python
126
+ 1/0
127
+ ```
128
+
129
+ fails because it raises a **`ZeroDivisionError`**. In Python (and mathematics), division by zero is undefined, so attempting to compute `1 / 0` triggers this exception:
130
+
131
+ ZeroDivisionError: division by zero
132
+
133
+ To avoid the error, ensure the denominator is never zero, e.g.:
134
+
135
+ ``` python
136
+ denominator = 2 # any non‑zero value
137
+ result = 1 / denominator
138
+ ```
139
+
140
+ By default, the entire notebook up to and including the calling cell is included in the prompt as context.
141
+
142
+ ## Configuration
143
+
144
+ The possible configuration options can be viewed with
145
+
146
+ ``` python
147
+ %config AIMagics
148
+ ```
149
+
150
+ AIMagics(Magics) options
151
+ ----------------------
152
+ AIMagics.model=<Unicode>
153
+ Provider/model to be used.
154
+ Current: 'openrouter/openai/gpt-oss-120b'
155
+ AIMagics.system_prompt=<Unicode>
156
+ The system prompt prepended to any prompt and context.
157
+ Current: "You are a helpful assistant living inside a user's Jupyter notebook. \n Use markdown syntax for styling your responses.\n Keep your responses brief and to the point.\n"
158
+
159
+ For example, you can change the model with
160
+
161
+ ``` python
162
+ %config AIMagics.model = "openrouter/google/gemini-3.8-flash"
163
+ ```
164
+
165
+ ``` python
166
+ %ai what model are you?
167
+ ```
168
+
169
+ I am **Gemini** (specifically configured as `openrouter/google/gemini-3.8-flash`), a large language model trained by Google.
170
+
171
+ ### Documentation
172
+
173
+ Documentation can be found hosted on this GitHub [repository](https://github.com/adrische/aimagics)’s [pages](https://adrische.github.io/aimagics/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/adrische/aimagics) and [pypi](https://pypi.org/project/aimagics/) respectively.
174
+
175
+ ## Acknowledgements
176
+
177
+ This repository would not be possible without the FastAI / AnswerAI open source packages, in particular [FastLLM](https://github.com/AnswerDotAI/fastllm). AnswerAI even have a dedicated platform for notebooks with AI integration: [SolveIt](https://solve.it.com/).
178
+
179
+ There are a number of packages implementing basically the same ideas (just much better):
180
+
181
+ - [AnswerDotAI/ai-jup](https://github.com/AnswerDotAI/ai-jup) An extension for Jupyter Lab
182
+ - [AnswerDotAI/ipyai](https://github.com/AnswerDotAI/ipyai) An extension of IPython in the terminal
183
+ - <https://nathancooper.io/blog/2026-08-10-ipython-is-all-you-need> An excellent blog post implementing these ideas much better for ipython.
184
+
185
+ During the finishing stages I also found https://pypi.org/project/aimagic/ on PyPi, which is basically what I am implementing here, even with the same syntax and the same name, just for Jupyter (relying on Javascript to get the cells for context).
@@ -0,0 +1,161 @@
1
+ # aimagics
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ ![](Screenshot.png)
7
+
8
+ ## Installation
9
+
10
+ Install latest from the GitHub [repository](https://github.com/adrische/aimagics):
11
+
12
+ ``` sh
13
+ $ pip install git+https://github.com/adrische/aimagics.git
14
+ ```
15
+
16
+ or from [conda](https://anaconda.org/adrische/aimagics)
17
+
18
+ ``` sh
19
+ $ conda install -c adrische aimagics
20
+ ```
21
+
22
+ or from [pypi](https://pypi.org/project/aimagics/)
23
+
24
+ ``` sh
25
+ $ pip install aimagics
26
+ ```
27
+
28
+ ## Setup
29
+
30
+ ### 1. Load the package
31
+
32
+ After installation, you can load the package in Jupyter and ipython with
33
+
34
+ ``` python
35
+ %load_ext aimagics
36
+ ```
37
+
38
+ Whether the package has been loaded can be checked with
39
+
40
+ ``` python
41
+ from IPython import get_ipython
42
+ get_ipython().extension_manager.loaded
43
+ ```
44
+
45
+ {'IPython.extensions.storemagic', 'aimagics'}
46
+
47
+ ‘aimagics’ should appear in the output.
48
+
49
+ ### 2. Set LLM API key
50
+
51
+ You should set your environment API key to your favorite LLM provider. The default model is
52
+
53
+ ``` python
54
+ AIMagics().model
55
+ ```
56
+
57
+ 'openrouter/openai/gpt-oss-120b'
58
+
59
+ so the environment key needed is `OPENROUTER_API_KEY`.
60
+
61
+ All [LiteLLM](https://models.litellm.ai/) models are compatible.
62
+
63
+ ### 3. Turn auto save on
64
+
65
+ The package works by retrieving the current notebook from disk. To always get the current state, it is recommended to turn auto save on. This is the default in jupyter notebooks, and can be toggled in vscode via `Show and Run Commands` \> `File: Toggle Auto Save`.
66
+
67
+ ## Usage
68
+
69
+ The package exposes two commands: `%ai` and `%%ai`. These are so-called ‘line’ and ‘cell magics’ and can be used as follows:
70
+
71
+ ### Line magic
72
+
73
+ The command `%ai` processes what comes after on the same line as request to the LLM:
74
+
75
+ ``` python
76
+ %ai What is aimagics?
77
+ ```
78
+
79
+ **`aimagics`** is a Python package and IPython extension that brings Large Language Model (LLM) capabilities directly into Jupyter notebooks via magic commands.
80
+
81
+ ### Key Features:
82
+
83
+ - **Magic Commands**: Offers `%ai` (line magic) and `%%ai` (cell magic) to interact with models directly within code cells.
84
+ - **Context-Aware**: Reads the current notebook state from disk to provide context-aware responses to your code and markdown.
85
+ - **Broad Model Support**: Built on [LiteLLM](https://models.litellm.ai/), allowing you to connect to OpenRouter, OpenAI, Anthropic, and dozens of other LLM providers.
86
+
87
+ ### Cell magic
88
+
89
+ The command `%%ai` processes what comes after it on the same line, but also what is in the same cell below it:
90
+
91
+ <!-- Sorry this is hard-coded because of some issues with getting the output of %%ai in nbdev.
92
+ The code ran as expected, see hidden cell below-->
93
+
94
+ ``` python
95
+ %%ai Why does the following code fail?
96
+ 1/0
97
+ ```
98
+
99
+ **Answer**
100
+
101
+ ``` python
102
+ 1/0
103
+ ```
104
+
105
+ fails because it raises a **`ZeroDivisionError`**. In Python (and mathematics), division by zero is undefined, so attempting to compute `1 / 0` triggers this exception:
106
+
107
+ ZeroDivisionError: division by zero
108
+
109
+ To avoid the error, ensure the denominator is never zero, e.g.:
110
+
111
+ ``` python
112
+ denominator = 2 # any non‑zero value
113
+ result = 1 / denominator
114
+ ```
115
+
116
+ By default, the entire notebook up to and including the calling cell is included in the prompt as context.
117
+
118
+ ## Configuration
119
+
120
+ The possible configuration options can be viewed with
121
+
122
+ ``` python
123
+ %config AIMagics
124
+ ```
125
+
126
+ AIMagics(Magics) options
127
+ ----------------------
128
+ AIMagics.model=<Unicode>
129
+ Provider/model to be used.
130
+ Current: 'openrouter/openai/gpt-oss-120b'
131
+ AIMagics.system_prompt=<Unicode>
132
+ The system prompt prepended to any prompt and context.
133
+ Current: "You are a helpful assistant living inside a user's Jupyter notebook. \n Use markdown syntax for styling your responses.\n Keep your responses brief and to the point.\n"
134
+
135
+ For example, you can change the model with
136
+
137
+ ``` python
138
+ %config AIMagics.model = "openrouter/google/gemini-3.8-flash"
139
+ ```
140
+
141
+ ``` python
142
+ %ai what model are you?
143
+ ```
144
+
145
+ I am **Gemini** (specifically configured as `openrouter/google/gemini-3.8-flash`), a large language model trained by Google.
146
+
147
+ ### Documentation
148
+
149
+ Documentation can be found hosted on this GitHub [repository](https://github.com/adrische/aimagics)’s [pages](https://adrische.github.io/aimagics/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/adrische/aimagics) and [pypi](https://pypi.org/project/aimagics/) respectively.
150
+
151
+ ## Acknowledgements
152
+
153
+ This repository would not be possible without the FastAI / AnswerAI open source packages, in particular [FastLLM](https://github.com/AnswerDotAI/fastllm). AnswerAI even have a dedicated platform for notebooks with AI integration: [SolveIt](https://solve.it.com/).
154
+
155
+ There are a number of packages implementing basically the same ideas (just much better):
156
+
157
+ - [AnswerDotAI/ai-jup](https://github.com/AnswerDotAI/ai-jup) An extension for Jupyter Lab
158
+ - [AnswerDotAI/ipyai](https://github.com/AnswerDotAI/ipyai) An extension of IPython in the terminal
159
+ - <https://nathancooper.io/blog/2026-08-10-ipython-is-all-you-need> An excellent blog post implementing these ideas much better for ipython.
160
+
161
+ During the finishing stages I also found https://pypi.org/project/aimagic/ on PyPi, which is basically what I am implementing here, even with the same syntax and the same name, just for Jupyter (relying on Javascript to get the cells for context).
@@ -0,0 +1,20 @@
1
+ __version__ = "0.0.1"
2
+
3
+
4
+ # Added manually
5
+ from .core import AIMagics, line_magic_quotes, cell_magic_dummy_character
6
+ from fastcore.aio import enable_async_magics
7
+
8
+ def load_ipython_extension(ipython):
9
+ "Makes magics available after running `%load_ext aimagics` in Jupyter / ipython"
10
+
11
+ ipython.register_magics(AIMagics)
12
+
13
+ enable_async_magics(ipython)
14
+
15
+ if hasattr(ipython, "input_transformers_cleanup"):
16
+ ipython.input_transformers_cleanup.insert(0, line_magic_quotes)
17
+ ipython.input_transformers_cleanup.insert(0, cell_magic_dummy_character)
18
+ elif hasattr(ipython, "input_transformer_manager"):
19
+ ipython.input_transformer_manager.cleanup_transforms.insert(0, line_magic_quotes)
20
+ ipython.input_transformer_manager.cleanup_transforms.insert(0, cell_magic_dummy_character)
@@ -0,0 +1,13 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/aimagics',
5
+ 'doc_host': 'https://adrische.github.io',
6
+ 'git_url': 'https://github.com/adrische/aimagics',
7
+ 'lib_path': 'aimagics'},
8
+ 'syms': { 'aimagics.core': { 'aimagics.core.AIMagics': ('core.html#aimagics', 'aimagics/core.py'),
9
+ 'aimagics.core.AIMagics.ai': ('core.html#aimagics.ai', 'aimagics/core.py'),
10
+ 'aimagics.core.adisplay_stream_own': ('core.html#adisplay_stream_own', 'aimagics/core.py'),
11
+ 'aimagics.core.cell_magic_dummy_character': ('core.html#cell_magic_dummy_character', 'aimagics/core.py'),
12
+ 'aimagics.core.get_context': ('core.html#get_context', 'aimagics/core.py'),
13
+ 'aimagics.core.line_magic_quotes': ('core.html#line_magic_quotes', 'aimagics/core.py')}}}
@@ -0,0 +1,116 @@
1
+ """Docs: https://adrische.github.io/aimagics/core.html.md"""
2
+
3
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/0_core.ipynb.
4
+
5
+ # %% auto #0
6
+ __all__ = []
7
+
8
+ # %% ../nbs/0_core.ipynb #aa35d777
9
+ from IPython import get_ipython
10
+ from IPython.core.magic import magics_class, Magics, line_cell_magic
11
+ import nbformat, ipynbname
12
+ from traitlets import Unicode
13
+ from aidialog.msg_parts import Text, Msg
14
+ from fastllm.chat import StreamAccum, acomplete
15
+
16
+ # %% ../nbs/0_core.ipynb #c93523a0
17
+ @magics_class
18
+ class AIMagics(Magics):
19
+ """AIMagics class defining %ai line and %%ai cell magic.
20
+
21
+ Can be configured with
22
+ %config
23
+ %config AIMagis
24
+ %config.model = "openrouter/google/gemini-3.8-flash"
25
+ """
26
+
27
+ # The config values
28
+ model = Unicode(
29
+ "openrouter/openai/gpt-oss-120b",
30
+ help="Provider/model to be used."
31
+ ).tag(config=True)
32
+
33
+ system_prompt = Unicode(
34
+ """You are a helpful assistant living inside a user's Jupyter notebook.
35
+ Use markdown syntax for styling your responses.
36
+ Keep your responses brief and to the point.\n""",
37
+ help="The system prompt prepended to any prompt and context."
38
+ ).tag(config=True)
39
+
40
+
41
+ @line_cell_magic
42
+ async def ai(self, line, cell=None):
43
+ """Prompt an LLM as magic command.
44
+
45
+ - Can be used as
46
+ %ai prompt
47
+ - or as
48
+ %%ai prompt
49
+ code
50
+ and any other text in the cell
51
+ """
52
+ line = line or ""
53
+ prompt = line if cell is None else f"{line}\n{cell}".strip()
54
+
55
+ ctx = get_context()
56
+ final_prompt = f"{self.system_prompt}\n{ctx}\n{prompt}"
57
+
58
+ msg = Msg('user', [Text(final_prompt)]) # TODO correct and better message history, TODO handle system prompt correctly, TODO tools
59
+ rs = await acomplete([msg], model=self.model, stream=True)
60
+ fmt = await adisplay_stream_own(rs)
61
+
62
+ # %% ../nbs/0_core.ipynb #b96a782b
63
+ def line_magic_quotes(lines):
64
+ """For line magic, add quotes if a ? is present. This prevents triggering ipython's help with ?"""
65
+ magic_string = "%ai"
66
+ if not lines or not lines[0].lstrip().split()[0] == magic_string: return lines
67
+ arg = lines[0].lstrip()[len(magic_string):].strip() # the part after %ai stripped from whitespaces
68
+ if "?" in arg:
69
+ arg = arg.strip("'\"") # remove any " or ' at beginning or end
70
+ line = f"{magic_string} '{arg}'\n" # build up new line magic with quoted input
71
+ lines[0] = line
72
+ return lines
73
+ else:
74
+ return lines
75
+
76
+ # %% ../nbs/0_core.ipynb #16c71aff
77
+ def cell_magic_dummy_character(lines):
78
+ """For cell magic (%%ai), don't need to add quotes,
79
+ but need to add a dummy character in case cell is empty"""
80
+ magic_string = "%%ai"
81
+ if not lines or not lines[0].lstrip().split()[0] == magic_string: return lines
82
+ if len(lines) == 1:
83
+ lines.append("\n")
84
+ return lines
85
+
86
+ # %% ../nbs/0_core.ipynb #5e91137c
87
+ def get_context():
88
+ """Get notebook cells up to and including the calling cell.
89
+
90
+ - Relies on state of notebook on disk. Recommended to turn autosave on.
91
+ - If multiple cells have the same source, cells only up and including the first one are included.
92
+ - Currently just uses the raw text content (json) of the current ipynb notebook."""
93
+ ip = get_ipython()
94
+ source_of_calling_cell = ip.kernel.get_parent()['content']['code']
95
+ def normalize(s):
96
+ return s.strip().replace("'", "").replace('"', "") # becomes fuzzy matching basically
97
+ normalized_source = normalize(source_of_calling_cell)
98
+ nb = nbformat.read(ipynbname.path(), as_version=4)
99
+ for i, cell in enumerate(nb['cells']):
100
+ # there may be an error matching cells that have been modified by line_magic_quotes / cell_magic_dummy_character
101
+ if cell['source'] == source_of_calling_cell or normalize(cell['source']) == normalized_source:
102
+ break
103
+ ctx = "\n".join([repr(cell) for cell in nb['cells'][:i+1]])
104
+ return ctx
105
+
106
+ # %% ../nbs/0_core.ipynb #f969491b
107
+ async def adisplay_stream_own(rs, chat=None, mx=2000):
108
+ "Use IPython.display to markdown display the response stream, refreshing from `chat.full()` on `Refresh`."
109
+ try: from IPython.display import display, Markdown
110
+ except ModuleNotFoundError: raise ModuleNotFoundError("This function requires ipython. Please run `pip install ipython` to use.")
111
+ acc = StreamAccum(chat, mx=mx)
112
+ h = display(Markdown('Processing request ...'), display_id=True) # Placeholder text
113
+ async for o in rs:
114
+ if acc(o) and acc.txt:
115
+ h.update(Markdown(acc.txt))
116
+ return acc.txt
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.4
2
+ Name: aimagics
3
+ Version: 0.0.1
4
+ Summary: LLM access from within Jupyter notebooks via line and cell magic commands
5
+ Author-email: adrische <adrianscheerer@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/adrische/aimagics
8
+ Project-URL: Documentation, https://adrische.github.io/aimagics/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.2.19
16
+ Requires-Dist: IPython
17
+ Requires-Dist: nbformat>=5.11.1
18
+ Requires-Dist: ipynbname>=2025.8.0.0
19
+ Requires-Dist: traitlets>=5.14.3
20
+ Requires-Dist: aidialog>=0.0.23
21
+ Requires-Dist: python-fastllm>=0.0.49
22
+ Requires-Dist: nbdev>=3.3.15
23
+ Dynamic: license-file
24
+
25
+ # aimagics
26
+
27
+
28
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
29
+
30
+ ![](Screenshot.png)
31
+
32
+ ## Installation
33
+
34
+ Install latest from the GitHub [repository](https://github.com/adrische/aimagics):
35
+
36
+ ``` sh
37
+ $ pip install git+https://github.com/adrische/aimagics.git
38
+ ```
39
+
40
+ or from [conda](https://anaconda.org/adrische/aimagics)
41
+
42
+ ``` sh
43
+ $ conda install -c adrische aimagics
44
+ ```
45
+
46
+ or from [pypi](https://pypi.org/project/aimagics/)
47
+
48
+ ``` sh
49
+ $ pip install aimagics
50
+ ```
51
+
52
+ ## Setup
53
+
54
+ ### 1. Load the package
55
+
56
+ After installation, you can load the package in Jupyter and ipython with
57
+
58
+ ``` python
59
+ %load_ext aimagics
60
+ ```
61
+
62
+ Whether the package has been loaded can be checked with
63
+
64
+ ``` python
65
+ from IPython import get_ipython
66
+ get_ipython().extension_manager.loaded
67
+ ```
68
+
69
+ {'IPython.extensions.storemagic', 'aimagics'}
70
+
71
+ ‘aimagics’ should appear in the output.
72
+
73
+ ### 2. Set LLM API key
74
+
75
+ You should set your environment API key to your favorite LLM provider. The default model is
76
+
77
+ ``` python
78
+ AIMagics().model
79
+ ```
80
+
81
+ 'openrouter/openai/gpt-oss-120b'
82
+
83
+ so the environment key needed is `OPENROUTER_API_KEY`.
84
+
85
+ All [LiteLLM](https://models.litellm.ai/) models are compatible.
86
+
87
+ ### 3. Turn auto save on
88
+
89
+ The package works by retrieving the current notebook from disk. To always get the current state, it is recommended to turn auto save on. This is the default in jupyter notebooks, and can be toggled in vscode via `Show and Run Commands` \> `File: Toggle Auto Save`.
90
+
91
+ ## Usage
92
+
93
+ The package exposes two commands: `%ai` and `%%ai`. These are so-called ‘line’ and ‘cell magics’ and can be used as follows:
94
+
95
+ ### Line magic
96
+
97
+ The command `%ai` processes what comes after on the same line as request to the LLM:
98
+
99
+ ``` python
100
+ %ai What is aimagics?
101
+ ```
102
+
103
+ **`aimagics`** is a Python package and IPython extension that brings Large Language Model (LLM) capabilities directly into Jupyter notebooks via magic commands.
104
+
105
+ ### Key Features:
106
+
107
+ - **Magic Commands**: Offers `%ai` (line magic) and `%%ai` (cell magic) to interact with models directly within code cells.
108
+ - **Context-Aware**: Reads the current notebook state from disk to provide context-aware responses to your code and markdown.
109
+ - **Broad Model Support**: Built on [LiteLLM](https://models.litellm.ai/), allowing you to connect to OpenRouter, OpenAI, Anthropic, and dozens of other LLM providers.
110
+
111
+ ### Cell magic
112
+
113
+ The command `%%ai` processes what comes after it on the same line, but also what is in the same cell below it:
114
+
115
+ <!-- Sorry this is hard-coded because of some issues with getting the output of %%ai in nbdev.
116
+ The code ran as expected, see hidden cell below-->
117
+
118
+ ``` python
119
+ %%ai Why does the following code fail?
120
+ 1/0
121
+ ```
122
+
123
+ **Answer**
124
+
125
+ ``` python
126
+ 1/0
127
+ ```
128
+
129
+ fails because it raises a **`ZeroDivisionError`**. In Python (and mathematics), division by zero is undefined, so attempting to compute `1 / 0` triggers this exception:
130
+
131
+ ZeroDivisionError: division by zero
132
+
133
+ To avoid the error, ensure the denominator is never zero, e.g.:
134
+
135
+ ``` python
136
+ denominator = 2 # any non‑zero value
137
+ result = 1 / denominator
138
+ ```
139
+
140
+ By default, the entire notebook up to and including the calling cell is included in the prompt as context.
141
+
142
+ ## Configuration
143
+
144
+ The possible configuration options can be viewed with
145
+
146
+ ``` python
147
+ %config AIMagics
148
+ ```
149
+
150
+ AIMagics(Magics) options
151
+ ----------------------
152
+ AIMagics.model=<Unicode>
153
+ Provider/model to be used.
154
+ Current: 'openrouter/openai/gpt-oss-120b'
155
+ AIMagics.system_prompt=<Unicode>
156
+ The system prompt prepended to any prompt and context.
157
+ Current: "You are a helpful assistant living inside a user's Jupyter notebook. \n Use markdown syntax for styling your responses.\n Keep your responses brief and to the point.\n"
158
+
159
+ For example, you can change the model with
160
+
161
+ ``` python
162
+ %config AIMagics.model = "openrouter/google/gemini-3.8-flash"
163
+ ```
164
+
165
+ ``` python
166
+ %ai what model are you?
167
+ ```
168
+
169
+ I am **Gemini** (specifically configured as `openrouter/google/gemini-3.8-flash`), a large language model trained by Google.
170
+
171
+ ### Documentation
172
+
173
+ Documentation can be found hosted on this GitHub [repository](https://github.com/adrische/aimagics)’s [pages](https://adrische.github.io/aimagics/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/adrische/aimagics) and [pypi](https://pypi.org/project/aimagics/) respectively.
174
+
175
+ ## Acknowledgements
176
+
177
+ This repository would not be possible without the FastAI / AnswerAI open source packages, in particular [FastLLM](https://github.com/AnswerDotAI/fastllm). AnswerAI even have a dedicated platform for notebooks with AI integration: [SolveIt](https://solve.it.com/).
178
+
179
+ There are a number of packages implementing basically the same ideas (just much better):
180
+
181
+ - [AnswerDotAI/ai-jup](https://github.com/AnswerDotAI/ai-jup) An extension for Jupyter Lab
182
+ - [AnswerDotAI/ipyai](https://github.com/AnswerDotAI/ipyai) An extension of IPython in the terminal
183
+ - <https://nathancooper.io/blog/2026-08-10-ipython-is-all-you-need> An excellent blog post implementing these ideas much better for ipython.
184
+
185
+ During the finishing stages I also found https://pypi.org/project/aimagic/ on PyPi, which is basically what I am implementing here, even with the same syntax and the same name, just for Jupyter (relying on Javascript to get the cells for context).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ aimagics/__init__.py
6
+ aimagics/_modidx.py
7
+ aimagics/core.py
8
+ aimagics.egg-info/PKG-INFO
9
+ aimagics.egg-info/SOURCES.txt
10
+ aimagics.egg-info/dependency_links.txt
11
+ aimagics.egg-info/entry_points.txt
12
+ aimagics.egg-info/requires.txt
13
+ aimagics.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ aimagics = aimagics._modidx:d
@@ -0,0 +1,8 @@
1
+ fastcore>=2.2.19
2
+ IPython
3
+ nbformat>=5.11.1
4
+ ipynbname>=2025.8.0.0
5
+ traitlets>=5.14.3
6
+ aidialog>=0.0.23
7
+ python-fastllm>=0.0.49
8
+ nbdev>=3.3.15
@@ -0,0 +1 @@
1
+ aimagics
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "aimagics"
7
+ dynamic = ["version"]
8
+ description = "LLM access from within Jupyter notebooks via line and cell magic commands"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "adrische", email = "adrianscheerer@gmail.com"}]
13
+ keywords = ['nbdev']
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+ dependencies = [
19
+ "fastcore>=2.2.19",
20
+ "IPython",
21
+ "nbformat>=5.11.1",
22
+ "ipynbname>=2025.8.0.0",
23
+ "traitlets>=5.14.3",
24
+ "aidialog>=0.0.23",
25
+ "python-fastllm>=0.0.49",
26
+ "nbdev>=3.3.15"
27
+ ]
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/adrische/aimagics"
31
+ Documentation = "https://adrische.github.io/aimagics/"
32
+
33
+ [project.entry-points.nbdev]
34
+ aimagics = "aimagics._modidx:d"
35
+
36
+ [tool.setuptools.dynamic]
37
+ version = {attr = "aimagics.__version__"}
38
+
39
+ [tool.setuptools.packages.find]
40
+ include = ["aimagics"]
41
+
42
+ [tool.nbdev]
43
+ export_procs = []
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+