llm-rsa 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.
llm_rsa-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 settings.ini
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
llm_rsa-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm_rsa
3
+ Version: 0.0.1
4
+ Summary: Recursive self aggregation
5
+ Home-page: https://github.com/risheekkumarb/llm_rsa
6
+ Author: Risheek kumar B
7
+ Author-email: b.risheekkumar@gmail.com
8
+ License: Apache-2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: fastcore
22
+ Requires-Dist: litellm
23
+ Provides-Extra: dev
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: keywords
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: provides-extra
34
+ Dynamic: requires-dist
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ # RSA - Recursive Self-Aggregation
39
+
40
+
41
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
42
+
43
+ RSA implements Recursive Self-Aggregation, a technique for improving LLM
44
+ responses by generating multiple candidate answers and iteratively
45
+ aggregating them. The algorithm samples k candidates from a pool of M
46
+ responses, asks the LLM to synthesize an improved answer, and repeats
47
+ this process across multiple loops to converge on higher-quality
48
+ outputs.
49
+
50
+ ## Developer Guide
51
+
52
+ If you are new to using `nbdev` here are some useful pointers to get you
53
+ started.
54
+
55
+ ### Install in Development mode
56
+
57
+ ``` sh
58
+ # make sure package is installed in development mode
59
+ $ pip install -e .
60
+
61
+ # make changes under nbs/ directory
62
+ # ...
63
+
64
+ # compile to have changes apply to
65
+ $ nbdev_prepare
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### Installation
71
+
72
+ Install latest from the GitHub \[repository\]\[repo\]:
73
+
74
+ ``` sh
75
+ $ pip install git+https://github.com//.git
76
+ ```
77
+
78
+ or from \[conda\]\[conda\]
79
+
80
+ ``` sh
81
+ $ conda install -c
82
+ ```
83
+
84
+ or from \[pypi\]\[pypi\]
85
+
86
+ ``` sh
87
+ $ pip install
88
+ ```
89
+
90
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
91
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
92
+
93
+ ### Documentation
94
+
95
+ Documentation can be found hosted on this GitHub
96
+ \[repository\]\[repo\]’s \[pages\]\[docs\]. Additionally you can find
97
+ package manager specific guidelines on \[conda\]\[conda\] and
98
+ \[pypi\]\[pypi\] respectively.
99
+
100
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
101
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
102
+
103
+ ## How to use
104
+
105
+ ### Basic Usage
106
+
107
+ Create an RSA instance with your task prompt and call it to run the
108
+ aggregation:
109
+
110
+ ``` python
111
+ task_prompt = '''Three people check into a hotel room that costs $30. They each contribute $10.
112
+ Later, the manager realizes the room only costs $25 and gives $5 to the bellboy to return.
113
+ The bellboy keeps $2 and gives $1 back to each person.
114
+ So each person paid $9 (total $27), plus the bellboy has $2, which equals $29.
115
+ Where did the extra dollar go?'''
116
+ ```
117
+
118
+ ``` python
119
+ agg_prompt = """Below is a reasoning problem followed by several candidate solutions.
120
+ Your job is to:
121
+ 1. Carefully analyze each candidate's reasoning step-by-step
122
+ 2. Identify which candidates make logical errors or arithmetic mistakes
123
+ 3. Note which approaches lead to correct reasoning
124
+ 4. Synthesize the best reasoning into a single, clear, correct solution
125
+
126
+ Show your work step-by-step, then state your final answer clearly."""
127
+ ```
128
+
129
+ ``` python
130
+ from llm_rsa.core import RSA
131
+
132
+ # Create RSA instance with a reasoning task
133
+ rsa = RSA(
134
+ task_prompt=task_prompt,
135
+ agg_prompt=agg_prompt,
136
+ M=4,
137
+ k=2,
138
+ loops=3
139
+ )
140
+
141
+ # Run the aggregation
142
+ results = rsa.run()
143
+ print(f"Generated {len(rsa.history)} total candidates across {rsa.loops} loops")
144
+ print('llm response: \n', results[-1].response)
145
+ ```
146
+
147
+ Generated 12 total candidates across 3 loops
148
+ llm response:
149
+ ### Analysis of Candidate Reasoning
150
+
151
+ Both **Candidate 1** and **Candidate 2** provide identical logical conclusions and correctly identify the fallacy.
152
+ * They both recognize that $27 is the total amount the guests spent ($30 - $3 refund).
153
+ * They both correctly point out that the $2 held by the bellboy is a *subset* of that $27, not an additional amount to be added to it.
154
+ * They both demonstrate that the correct way to reach the original $30 is to add the $3 refund to the $27 spent, rather than adding the $2 tip to the $27 spent.
155
+
156
+ The candidates effectively "debunked" the riddle's misdirection, which relies on the psychological trick of adding two numbers that do not belong together in a balance sheet.
157
+
158
+ ---
159
+
160
+ ### Step-by-Step Reasoning and Solution
161
+
162
+ To solve the mystery of the "missing dollar," we must track the $30 carefully and distinguish between **Assets** (money held) and **Expenses** (money spent).
163
+
164
+ **1. Track the $30 Total**
165
+ At the end of the transaction, the $30 is distributed as follows:
166
+ * **$25** is in the hotel's register (the actual price of the room).
167
+ * **$2** is in the bellboy's pocket (the stolen tip).
168
+ * **$3** is in the guests' pockets ($1 each).
169
+ * **Total: $25 + $2 + $3 = $30.**
170
+ Nothing is missing.
171
+
172
+ **2. Analyze the Guest Perspective (The $27)**
173
+ The riddle says: "Each person paid $9, total $27." This is correct. Let's look at what happened to that $27:
174
+ * **$25** went to the hotel for the room.
175
+ * **$2** went to the bellboy as a tip.
176
+ * **Total: $25 + $2 = $27.**
177
+ The $2 is already *inside* the $27.
178
+
179
+ **3. Identify the Logical Fallacy**
180
+ The riddle's error is the statement: *"Each person paid $9 (total $27), plus the bellboy has $2, which equals $29."*
181
+ This is an accounting error. You cannot add the bellboy's $2 to the $27 because the bellboy's $2 is **part of** the $27.
182
+
183
+ To reconcile the total to $30, you must add the money the guests **kept** (the $3 refund) to the money they **spent** ($27):
184
+ * **$27 (Spent) + $3 (Refunded) = $30.**
185
+
186
+ **Conclusion:**
187
+ The "extra dollar" does not exist. The riddle creates an illusion by adding a component of an expense ($2) to the total expense ($27), rather than adding the remaining cash on hand ($3) to the total expense.
188
+
189
+ ### Final Answer
190
+ The dollar is not missing. The mistake is in the calculation: it adds the bellboy's $2 to the $27 spent, even though the $2 is already included in the $27. The correct calculation is $27 (spent) + $3 (returned to guests) = $30.
191
+
192
+ ``` python
193
+ from litellm import completion
194
+
195
+ # Single direct call (baseline)
196
+ response = completion(
197
+ model='openrouter/google/gemini-3-flash-preview',
198
+ messages=[{"role": "user", "content": task_prompt}],
199
+ temperature=1.0
200
+ )
201
+ baseline_answer = response.choices[0].message.content
202
+ print("=== BASELINE (single call) ===")
203
+ print(baseline_answer)
204
+ ```
205
+
206
+ === BASELINE (single call) ===
207
+ The extra dollar didn't go anywhere; the confusion comes from **adding** the bellboy's tip to the guests' expenses instead of **subtracting** it.
208
+
209
+ Here is the correct breakdown of the math:
210
+
211
+ ### 1. The Total Spent
212
+ Each person paid $9, for a total of **$27**.
213
+
214
+ ### 2. Where that $27 is currently located
215
+ Of that $27:
216
+ * **$25** is in the cash register (the actual price of the room).
217
+ * **$2** is in the bellboy’s pocket.
218
+ * **Total: $27.**
219
+
220
+ ### 3. The Logical Fallacy
221
+ The riddle tricks you by saying: *"$27 (paid) + $2 (bellboy) = $29."*
222
+
223
+ This is an error in logic because the **$2 is already included in the $27**. You are essentially adding the bellboy's tip twice.
224
+
225
+ **The correct math should be:**
226
+ * **Total Spent ($27) + Total Refunded ($3) = $30**
227
+ * OR
228
+ * **Total Spent ($27) - Bellboy's Tip ($2) = Room Price ($25)**
229
+
230
+ ### Configuration Options
231
+
232
+ | Parameter | Default | Description |
233
+ |----|----|----|
234
+ | `task_prompt` | (required) | The main task/question to solve |
235
+ | `model` | `'openrouter/google/gemini-3-flash-preview'` | LLM model to use (any litellm-compatible model) |
236
+ | `M` | 8 | Number of candidates generated per loop |
237
+ | `k` | 4 | Number of candidates sampled for each aggregation |
238
+ | `loops` | 3 | Number of aggregation iterations |
239
+ | `temperature` | 1.0 | LLM sampling temperature |
240
+ | `n_workers` | 4 | Parallel workers for LLM calls |
241
+ | `agg_prompt` | (auto) | Custom aggregation prompt (optional) |
242
+
243
+ ### How RSA Works
244
+
245
+ 1. **Loop 0**: Generate M independent responses to the task prompt
246
+ 2. **Loop 1+**: For each of M new candidates, randomly sample k
247
+ previous candidates and ask the LLM to aggregate them into an
248
+ improved answer
249
+ 3. **Repeat** for the specified number of loops
250
+ 4. **Return** the final pool of aggregated candidates
251
+
252
+ The `history` attribute stores all candidates across all loops, allowing
253
+ you to trace the aggregation process.
@@ -0,0 +1,216 @@
1
+ # RSA - Recursive Self-Aggregation
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ RSA implements Recursive Self-Aggregation, a technique for improving LLM
7
+ responses by generating multiple candidate answers and iteratively
8
+ aggregating them. The algorithm samples k candidates from a pool of M
9
+ responses, asks the LLM to synthesize an improved answer, and repeats
10
+ this process across multiple loops to converge on higher-quality
11
+ outputs.
12
+
13
+ ## Developer Guide
14
+
15
+ If you are new to using `nbdev` here are some useful pointers to get you
16
+ started.
17
+
18
+ ### Install in Development mode
19
+
20
+ ``` sh
21
+ # make sure package is installed in development mode
22
+ $ pip install -e .
23
+
24
+ # make changes under nbs/ directory
25
+ # ...
26
+
27
+ # compile to have changes apply to
28
+ $ nbdev_prepare
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ### Installation
34
+
35
+ Install latest from the GitHub \[repository\]\[repo\]:
36
+
37
+ ``` sh
38
+ $ pip install git+https://github.com//.git
39
+ ```
40
+
41
+ or from \[conda\]\[conda\]
42
+
43
+ ``` sh
44
+ $ conda install -c
45
+ ```
46
+
47
+ or from \[pypi\]\[pypi\]
48
+
49
+ ``` sh
50
+ $ pip install
51
+ ```
52
+
53
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
54
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
55
+
56
+ ### Documentation
57
+
58
+ Documentation can be found hosted on this GitHub
59
+ \[repository\]\[repo\]’s \[pages\]\[docs\]. Additionally you can find
60
+ package manager specific guidelines on \[conda\]\[conda\] and
61
+ \[pypi\]\[pypi\] respectively.
62
+
63
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
64
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
65
+
66
+ ## How to use
67
+
68
+ ### Basic Usage
69
+
70
+ Create an RSA instance with your task prompt and call it to run the
71
+ aggregation:
72
+
73
+ ``` python
74
+ task_prompt = '''Three people check into a hotel room that costs $30. They each contribute $10.
75
+ Later, the manager realizes the room only costs $25 and gives $5 to the bellboy to return.
76
+ The bellboy keeps $2 and gives $1 back to each person.
77
+ So each person paid $9 (total $27), plus the bellboy has $2, which equals $29.
78
+ Where did the extra dollar go?'''
79
+ ```
80
+
81
+ ``` python
82
+ agg_prompt = """Below is a reasoning problem followed by several candidate solutions.
83
+ Your job is to:
84
+ 1. Carefully analyze each candidate's reasoning step-by-step
85
+ 2. Identify which candidates make logical errors or arithmetic mistakes
86
+ 3. Note which approaches lead to correct reasoning
87
+ 4. Synthesize the best reasoning into a single, clear, correct solution
88
+
89
+ Show your work step-by-step, then state your final answer clearly."""
90
+ ```
91
+
92
+ ``` python
93
+ from llm_rsa.core import RSA
94
+
95
+ # Create RSA instance with a reasoning task
96
+ rsa = RSA(
97
+ task_prompt=task_prompt,
98
+ agg_prompt=agg_prompt,
99
+ M=4,
100
+ k=2,
101
+ loops=3
102
+ )
103
+
104
+ # Run the aggregation
105
+ results = rsa.run()
106
+ print(f"Generated {len(rsa.history)} total candidates across {rsa.loops} loops")
107
+ print('llm response: \n', results[-1].response)
108
+ ```
109
+
110
+ Generated 12 total candidates across 3 loops
111
+ llm response:
112
+ ### Analysis of Candidate Reasoning
113
+
114
+ Both **Candidate 1** and **Candidate 2** provide identical logical conclusions and correctly identify the fallacy.
115
+ * They both recognize that $27 is the total amount the guests spent ($30 - $3 refund).
116
+ * They both correctly point out that the $2 held by the bellboy is a *subset* of that $27, not an additional amount to be added to it.
117
+ * They both demonstrate that the correct way to reach the original $30 is to add the $3 refund to the $27 spent, rather than adding the $2 tip to the $27 spent.
118
+
119
+ The candidates effectively "debunked" the riddle's misdirection, which relies on the psychological trick of adding two numbers that do not belong together in a balance sheet.
120
+
121
+ ---
122
+
123
+ ### Step-by-Step Reasoning and Solution
124
+
125
+ To solve the mystery of the "missing dollar," we must track the $30 carefully and distinguish between **Assets** (money held) and **Expenses** (money spent).
126
+
127
+ **1. Track the $30 Total**
128
+ At the end of the transaction, the $30 is distributed as follows:
129
+ * **$25** is in the hotel's register (the actual price of the room).
130
+ * **$2** is in the bellboy's pocket (the stolen tip).
131
+ * **$3** is in the guests' pockets ($1 each).
132
+ * **Total: $25 + $2 + $3 = $30.**
133
+ Nothing is missing.
134
+
135
+ **2. Analyze the Guest Perspective (The $27)**
136
+ The riddle says: "Each person paid $9, total $27." This is correct. Let's look at what happened to that $27:
137
+ * **$25** went to the hotel for the room.
138
+ * **$2** went to the bellboy as a tip.
139
+ * **Total: $25 + $2 = $27.**
140
+ The $2 is already *inside* the $27.
141
+
142
+ **3. Identify the Logical Fallacy**
143
+ The riddle's error is the statement: *"Each person paid $9 (total $27), plus the bellboy has $2, which equals $29."*
144
+ This is an accounting error. You cannot add the bellboy's $2 to the $27 because the bellboy's $2 is **part of** the $27.
145
+
146
+ To reconcile the total to $30, you must add the money the guests **kept** (the $3 refund) to the money they **spent** ($27):
147
+ * **$27 (Spent) + $3 (Refunded) = $30.**
148
+
149
+ **Conclusion:**
150
+ The "extra dollar" does not exist. The riddle creates an illusion by adding a component of an expense ($2) to the total expense ($27), rather than adding the remaining cash on hand ($3) to the total expense.
151
+
152
+ ### Final Answer
153
+ The dollar is not missing. The mistake is in the calculation: it adds the bellboy's $2 to the $27 spent, even though the $2 is already included in the $27. The correct calculation is $27 (spent) + $3 (returned to guests) = $30.
154
+
155
+ ``` python
156
+ from litellm import completion
157
+
158
+ # Single direct call (baseline)
159
+ response = completion(
160
+ model='openrouter/google/gemini-3-flash-preview',
161
+ messages=[{"role": "user", "content": task_prompt}],
162
+ temperature=1.0
163
+ )
164
+ baseline_answer = response.choices[0].message.content
165
+ print("=== BASELINE (single call) ===")
166
+ print(baseline_answer)
167
+ ```
168
+
169
+ === BASELINE (single call) ===
170
+ The extra dollar didn't go anywhere; the confusion comes from **adding** the bellboy's tip to the guests' expenses instead of **subtracting** it.
171
+
172
+ Here is the correct breakdown of the math:
173
+
174
+ ### 1. The Total Spent
175
+ Each person paid $9, for a total of **$27**.
176
+
177
+ ### 2. Where that $27 is currently located
178
+ Of that $27:
179
+ * **$25** is in the cash register (the actual price of the room).
180
+ * **$2** is in the bellboy’s pocket.
181
+ * **Total: $27.**
182
+
183
+ ### 3. The Logical Fallacy
184
+ The riddle tricks you by saying: *"$27 (paid) + $2 (bellboy) = $29."*
185
+
186
+ This is an error in logic because the **$2 is already included in the $27**. You are essentially adding the bellboy's tip twice.
187
+
188
+ **The correct math should be:**
189
+ * **Total Spent ($27) + Total Refunded ($3) = $30**
190
+ * OR
191
+ * **Total Spent ($27) - Bellboy's Tip ($2) = Room Price ($25)**
192
+
193
+ ### Configuration Options
194
+
195
+ | Parameter | Default | Description |
196
+ |----|----|----|
197
+ | `task_prompt` | (required) | The main task/question to solve |
198
+ | `model` | `'openrouter/google/gemini-3-flash-preview'` | LLM model to use (any litellm-compatible model) |
199
+ | `M` | 8 | Number of candidates generated per loop |
200
+ | `k` | 4 | Number of candidates sampled for each aggregation |
201
+ | `loops` | 3 | Number of aggregation iterations |
202
+ | `temperature` | 1.0 | LLM sampling temperature |
203
+ | `n_workers` | 4 | Parallel workers for LLM calls |
204
+ | `agg_prompt` | (auto) | Custom aggregation prompt (optional) |
205
+
206
+ ### How RSA Works
207
+
208
+ 1. **Loop 0**: Generate M independent responses to the task prompt
209
+ 2. **Loop 1+**: For each of M new candidates, randomly sample k
210
+ previous candidates and ask the LLM to aggregate them into an
211
+ improved answer
212
+ 3. **Repeat** for the specified number of loops
213
+ 4. **Return** the final pool of aggregated candidates
214
+
215
+ The `history` attribute stores all candidates across all loops, allowing
216
+ you to trace the aggregation process.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,19 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/llm_rsa',
5
+ 'doc_host': 'https://risheekkumarb.github.io',
6
+ 'git_url': 'https://github.com/risheekkumarb/llm_rsa',
7
+ 'lib_path': 'llm_rsa'},
8
+ 'syms': { 'llm_rsa.core': { 'llm_rsa.core.RSA': ('core.html#rsa', 'llm_rsa/core.py'),
9
+ 'llm_rsa.core.RSA.__init__': ('core.html#rsa.__init__', 'llm_rsa/core.py'),
10
+ 'llm_rsa.core.RSA.__repr__': ('core.html#rsa.__repr__', 'llm_rsa/core.py'),
11
+ 'llm_rsa.core.RSA._agg_prompt': ('core.html#rsa._agg_prompt', 'llm_rsa/core.py'),
12
+ 'llm_rsa.core.RSA._call_llm': ('core.html#rsa._call_llm', 'llm_rsa/core.py'),
13
+ 'llm_rsa.core.RSA._run_loop': ('core.html#rsa._run_loop', 'llm_rsa/core.py'),
14
+ 'llm_rsa.core.RSA.aggregate': ('core.html#rsa.aggregate', 'llm_rsa/core.py'),
15
+ 'llm_rsa.core.RSA.get_prompts': ('core.html#rsa.get_prompts', 'llm_rsa/core.py'),
16
+ 'llm_rsa.core.RSA.run': ('core.html#rsa.run', 'llm_rsa/core.py'),
17
+ 'llm_rsa.core.RSACandidate': ('core.html#rsacandidate', 'llm_rsa/core.py'),
18
+ 'llm_rsa.core.RSACandidate.__init__': ('core.html#rsacandidate.__init__', 'llm_rsa/core.py'),
19
+ 'llm_rsa.core.RSACandidate.__repr__': ('core.html#rsacandidate.__repr__', 'llm_rsa/core.py')}}}
@@ -0,0 +1,107 @@
1
+ """Recursive Self-Aggregation (RSA) - A general-purpose LLM aggregation algorithm using litellm based on the paper **https://rsa-llm.github.io/**"""
2
+
3
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
4
+
5
+ # %% auto #0
6
+ __all__ = ['RSACandidate', 'RSA']
7
+
8
+ # %% ../nbs/00_core.ipynb #ccd7cb56
9
+ from fastcore.all import *
10
+ from fastcore.test import *
11
+ from litellm import completion
12
+ import random, uuid
13
+ from itertools import combinations
14
+ from fastprogress import progress_bar
15
+
16
+ # %% ../nbs/00_core.ipynb #c8def011
17
+ class RSACandidate:
18
+ "A candidate response in the RSA algorithm"
19
+ def __init__(self, id:str, loop_id:int, prompt:str, response:str=None, parent_ids:list=None): store_attr()
20
+ def __repr__(self): return f'id:{self.id}\nloop_id:{self.loop_id}\nprompt:\n{self.prompt}\nresponse:\n{self.response}\nparent_ids:\n{self.parent_ids}'
21
+
22
+ # %% ../nbs/00_core.ipynb #cc5af69e
23
+ class RSA:
24
+ "Recursive Self-Aggregation algorithm for LLM response aggregation"
25
+ def __init__(
26
+ self,
27
+ task_prompt:str, # The main task/question to solve
28
+ agg_prompt:str=None, # Custom aggregation prompt
29
+ model:str='openrouter/google/gemini-3-flash-preview', # LLM model to use
30
+ N:int=4, # Population size (candidates per loop)
31
+ K:int=3, # Number of candidates to aggregate
32
+ loops:int=2, # Number of aggregation loops
33
+ history:list=None, # History of all candidates
34
+ temperature:float=1.0, # LLM temperature
35
+ n_workers:int=4 # Parallel workers
36
+ ):
37
+ if not task_prompt: raise ValueError("task_prompt is required")
38
+ store_attr()
39
+ if not history: self.history = L()
40
+ if not self.agg_prompt: self.agg_prompt = """You are given question with training examples and a test input.\nYou are also provided several candidate solutions. Some candidates may be incorrect\nAggregate/consider all the candidates and use their help to produce the improved correct solution"""
41
+
42
+ def __repr__(self): return f'RSA(model={self.model!r}, \nN={self.N}, \nK={self.K}, \nloops={self.loops}, \nhistory={len(self.history)} candidates, \ntask_prompt={self.task_prompt})'
43
+
44
+ # %% ../nbs/00_core.ipynb #3c39e9e6
45
+ @patch
46
+ def _call_llm(self:RSA, prompt):
47
+ "Call the LLM with the given prompt and return the response content"
48
+ response = completion(
49
+ model=self.model,
50
+ messages=[{"role": "user", "content": prompt}],
51
+ temperature=self.temperature,
52
+ )
53
+ return response.choices[0].message.content
54
+
55
+ # %% ../nbs/00_core.ipynb #ef493c51
56
+ @patch
57
+ def _agg_prompt(self:RSA, candidates: list[RSACandidate]) -> str:
58
+ "Build an aggregation prompt combining the task prompt with candidate responses"
59
+ parts = [
60
+ self.agg_prompt,
61
+ self.task_prompt,
62
+ "\nCANDIDATE ANSWERS (may contain mistakes):",
63
+ ]
64
+ for i, cand in enumerate(candidates, 1):
65
+ parts.append(f"---- Candidate {i} ----\n{cand.response}")
66
+ parts.append("\nYour response:")
67
+ return "\n".join(parts)
68
+
69
+ # %% ../nbs/00_core.ipynb #81deb527
70
+ @patch
71
+ def get_prompts(self:RSA, loop_id, cands=None):
72
+ "Generate candidate prompts for a given loop: N initial candidates, or all C(n,K) combinations for aggregation"
73
+ if not cands: return L(RSACandidate(id=str(uuid.uuid4()), loop_id=loop_id, prompt=self.task_prompt) for _ in range(self.N))
74
+ if len(cands) < self.K: raise ValueError(f"Need at least {self.K} candidates, got {len(cands)}")
75
+ sel_cands = L(combinations(cands, self.K))
76
+ if len(sel_cands) < self.N: raise ValueError(f"C({len(cands)},{self.K})={len(sel_cands)} combinations is less than N={self.N}")
77
+ sel_cands = sel_cands.shuffle()[:self.N]
78
+ return sel_cands.map(lambda x: RSACandidate(id=str(uuid.uuid4()), loop_id=loop_id, prompt=self._agg_prompt(x), parent_ids=L(x).attrgot('id')))
79
+
80
+ # %% ../nbs/00_core.ipynb #80329d80
81
+ @patch
82
+ def _run_loop(self:RSA, loop_id, pool=None):
83
+ "Execute one loop: generate prompts, call LLM in parallel, attach responses"
84
+ prompts = self.get_prompts(loop_id, pool)
85
+ responses = parallel(self._call_llm, prompts.attrgot('prompt'), n_workers=self.n_workers, progress=True)
86
+ for p, r in zip(prompts, responses): p.response = r
87
+ return prompts
88
+
89
+ # %% ../nbs/00_core.ipynb #02599e94
90
+ @patch
91
+ def run(self:RSA):
92
+ "Run the full RSA algorithm for the configured number of loops and return the final candidate pool"
93
+ pbar = progress_bar(range(self.loops))
94
+ for i in pbar:
95
+ pbar.comment = f"Loop {i+1}"
96
+ pool = self._run_loop(i, pool if i > 0 else None)
97
+ self.history.extend(pool)
98
+ return pool
99
+
100
+ # %% ../nbs/00_core.ipynb #b4edf71c
101
+ @patch
102
+ def aggregate(self:RSA):
103
+ "Final aggregation one LLM call to aggregate all the final loop candidates"
104
+ candidates = self.history.filter(lambda x: x.loop_id==(self.loops-1))
105
+ responses = '\n'.join(f"---- Candidate {i+1} ----\n{c.response}" for i, c in enumerate(candidates))
106
+ prompt = f"{self.agg_prompt}\n{self.task_prompt}\n\nCANDIDATE ANSWERS:\n{responses}\n\nProvide the best aggregated answer:"
107
+ return prompt, self._call_llm(prompt)
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm_rsa
3
+ Version: 0.0.1
4
+ Summary: Recursive self aggregation
5
+ Home-page: https://github.com/risheekkumarb/llm_rsa
6
+ Author: Risheek kumar B
7
+ Author-email: b.risheekkumar@gmail.com
8
+ License: Apache-2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: fastcore
22
+ Requires-Dist: litellm
23
+ Provides-Extra: dev
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: keywords
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: provides-extra
34
+ Dynamic: requires-dist
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ # RSA - Recursive Self-Aggregation
39
+
40
+
41
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
42
+
43
+ RSA implements Recursive Self-Aggregation, a technique for improving LLM
44
+ responses by generating multiple candidate answers and iteratively
45
+ aggregating them. The algorithm samples k candidates from a pool of M
46
+ responses, asks the LLM to synthesize an improved answer, and repeats
47
+ this process across multiple loops to converge on higher-quality
48
+ outputs.
49
+
50
+ ## Developer Guide
51
+
52
+ If you are new to using `nbdev` here are some useful pointers to get you
53
+ started.
54
+
55
+ ### Install in Development mode
56
+
57
+ ``` sh
58
+ # make sure package is installed in development mode
59
+ $ pip install -e .
60
+
61
+ # make changes under nbs/ directory
62
+ # ...
63
+
64
+ # compile to have changes apply to
65
+ $ nbdev_prepare
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### Installation
71
+
72
+ Install latest from the GitHub \[repository\]\[repo\]:
73
+
74
+ ``` sh
75
+ $ pip install git+https://github.com//.git
76
+ ```
77
+
78
+ or from \[conda\]\[conda\]
79
+
80
+ ``` sh
81
+ $ conda install -c
82
+ ```
83
+
84
+ or from \[pypi\]\[pypi\]
85
+
86
+ ``` sh
87
+ $ pip install
88
+ ```
89
+
90
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
91
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
92
+
93
+ ### Documentation
94
+
95
+ Documentation can be found hosted on this GitHub
96
+ \[repository\]\[repo\]’s \[pages\]\[docs\]. Additionally you can find
97
+ package manager specific guidelines on \[conda\]\[conda\] and
98
+ \[pypi\]\[pypi\] respectively.
99
+
100
+ \[repo\]: \[docs\]: https://.github.io// \[pypi\]:
101
+ https://pypi.org/project// \[conda\]: https://anaconda.org//
102
+
103
+ ## How to use
104
+
105
+ ### Basic Usage
106
+
107
+ Create an RSA instance with your task prompt and call it to run the
108
+ aggregation:
109
+
110
+ ``` python
111
+ task_prompt = '''Three people check into a hotel room that costs $30. They each contribute $10.
112
+ Later, the manager realizes the room only costs $25 and gives $5 to the bellboy to return.
113
+ The bellboy keeps $2 and gives $1 back to each person.
114
+ So each person paid $9 (total $27), plus the bellboy has $2, which equals $29.
115
+ Where did the extra dollar go?'''
116
+ ```
117
+
118
+ ``` python
119
+ agg_prompt = """Below is a reasoning problem followed by several candidate solutions.
120
+ Your job is to:
121
+ 1. Carefully analyze each candidate's reasoning step-by-step
122
+ 2. Identify which candidates make logical errors or arithmetic mistakes
123
+ 3. Note which approaches lead to correct reasoning
124
+ 4. Synthesize the best reasoning into a single, clear, correct solution
125
+
126
+ Show your work step-by-step, then state your final answer clearly."""
127
+ ```
128
+
129
+ ``` python
130
+ from llm_rsa.core import RSA
131
+
132
+ # Create RSA instance with a reasoning task
133
+ rsa = RSA(
134
+ task_prompt=task_prompt,
135
+ agg_prompt=agg_prompt,
136
+ M=4,
137
+ k=2,
138
+ loops=3
139
+ )
140
+
141
+ # Run the aggregation
142
+ results = rsa.run()
143
+ print(f"Generated {len(rsa.history)} total candidates across {rsa.loops} loops")
144
+ print('llm response: \n', results[-1].response)
145
+ ```
146
+
147
+ Generated 12 total candidates across 3 loops
148
+ llm response:
149
+ ### Analysis of Candidate Reasoning
150
+
151
+ Both **Candidate 1** and **Candidate 2** provide identical logical conclusions and correctly identify the fallacy.
152
+ * They both recognize that $27 is the total amount the guests spent ($30 - $3 refund).
153
+ * They both correctly point out that the $2 held by the bellboy is a *subset* of that $27, not an additional amount to be added to it.
154
+ * They both demonstrate that the correct way to reach the original $30 is to add the $3 refund to the $27 spent, rather than adding the $2 tip to the $27 spent.
155
+
156
+ The candidates effectively "debunked" the riddle's misdirection, which relies on the psychological trick of adding two numbers that do not belong together in a balance sheet.
157
+
158
+ ---
159
+
160
+ ### Step-by-Step Reasoning and Solution
161
+
162
+ To solve the mystery of the "missing dollar," we must track the $30 carefully and distinguish between **Assets** (money held) and **Expenses** (money spent).
163
+
164
+ **1. Track the $30 Total**
165
+ At the end of the transaction, the $30 is distributed as follows:
166
+ * **$25** is in the hotel's register (the actual price of the room).
167
+ * **$2** is in the bellboy's pocket (the stolen tip).
168
+ * **$3** is in the guests' pockets ($1 each).
169
+ * **Total: $25 + $2 + $3 = $30.**
170
+ Nothing is missing.
171
+
172
+ **2. Analyze the Guest Perspective (The $27)**
173
+ The riddle says: "Each person paid $9, total $27." This is correct. Let's look at what happened to that $27:
174
+ * **$25** went to the hotel for the room.
175
+ * **$2** went to the bellboy as a tip.
176
+ * **Total: $25 + $2 = $27.**
177
+ The $2 is already *inside* the $27.
178
+
179
+ **3. Identify the Logical Fallacy**
180
+ The riddle's error is the statement: *"Each person paid $9 (total $27), plus the bellboy has $2, which equals $29."*
181
+ This is an accounting error. You cannot add the bellboy's $2 to the $27 because the bellboy's $2 is **part of** the $27.
182
+
183
+ To reconcile the total to $30, you must add the money the guests **kept** (the $3 refund) to the money they **spent** ($27):
184
+ * **$27 (Spent) + $3 (Refunded) = $30.**
185
+
186
+ **Conclusion:**
187
+ The "extra dollar" does not exist. The riddle creates an illusion by adding a component of an expense ($2) to the total expense ($27), rather than adding the remaining cash on hand ($3) to the total expense.
188
+
189
+ ### Final Answer
190
+ The dollar is not missing. The mistake is in the calculation: it adds the bellboy's $2 to the $27 spent, even though the $2 is already included in the $27. The correct calculation is $27 (spent) + $3 (returned to guests) = $30.
191
+
192
+ ``` python
193
+ from litellm import completion
194
+
195
+ # Single direct call (baseline)
196
+ response = completion(
197
+ model='openrouter/google/gemini-3-flash-preview',
198
+ messages=[{"role": "user", "content": task_prompt}],
199
+ temperature=1.0
200
+ )
201
+ baseline_answer = response.choices[0].message.content
202
+ print("=== BASELINE (single call) ===")
203
+ print(baseline_answer)
204
+ ```
205
+
206
+ === BASELINE (single call) ===
207
+ The extra dollar didn't go anywhere; the confusion comes from **adding** the bellboy's tip to the guests' expenses instead of **subtracting** it.
208
+
209
+ Here is the correct breakdown of the math:
210
+
211
+ ### 1. The Total Spent
212
+ Each person paid $9, for a total of **$27**.
213
+
214
+ ### 2. Where that $27 is currently located
215
+ Of that $27:
216
+ * **$25** is in the cash register (the actual price of the room).
217
+ * **$2** is in the bellboy’s pocket.
218
+ * **Total: $27.**
219
+
220
+ ### 3. The Logical Fallacy
221
+ The riddle tricks you by saying: *"$27 (paid) + $2 (bellboy) = $29."*
222
+
223
+ This is an error in logic because the **$2 is already included in the $27**. You are essentially adding the bellboy's tip twice.
224
+
225
+ **The correct math should be:**
226
+ * **Total Spent ($27) + Total Refunded ($3) = $30**
227
+ * OR
228
+ * **Total Spent ($27) - Bellboy's Tip ($2) = Room Price ($25)**
229
+
230
+ ### Configuration Options
231
+
232
+ | Parameter | Default | Description |
233
+ |----|----|----|
234
+ | `task_prompt` | (required) | The main task/question to solve |
235
+ | `model` | `'openrouter/google/gemini-3-flash-preview'` | LLM model to use (any litellm-compatible model) |
236
+ | `M` | 8 | Number of candidates generated per loop |
237
+ | `k` | 4 | Number of candidates sampled for each aggregation |
238
+ | `loops` | 3 | Number of aggregation iterations |
239
+ | `temperature` | 1.0 | LLM sampling temperature |
240
+ | `n_workers` | 4 | Parallel workers for LLM calls |
241
+ | `agg_prompt` | (auto) | Custom aggregation prompt (optional) |
242
+
243
+ ### How RSA Works
244
+
245
+ 1. **Loop 0**: Generate M independent responses to the task prompt
246
+ 2. **Loop 1+**: For each of M new candidates, randomly sample k
247
+ previous candidates and ask the LLM to aggregate them into an
248
+ improved answer
249
+ 3. **Repeat** for the specified number of loops
250
+ 4. **Return** the final pool of aggregated candidates
251
+
252
+ The `history` attribute stores all candidates across all loops, allowing
253
+ you to trace the aggregation process.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ settings.ini
6
+ setup.py
7
+ llm_rsa/__init__.py
8
+ llm_rsa/_modidx.py
9
+ llm_rsa/core.py
10
+ llm_rsa.egg-info/PKG-INFO
11
+ llm_rsa.egg-info/SOURCES.txt
12
+ llm_rsa.egg-info/dependency_links.txt
13
+ llm_rsa.egg-info/entry_points.txt
14
+ llm_rsa.egg-info/not-zip-safe
15
+ llm_rsa.egg-info/requires.txt
16
+ llm_rsa.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ llm_rsa = llm_rsa._modidx:d
@@ -0,0 +1,4 @@
1
+ fastcore
2
+ litellm
3
+
4
+ [dev]
@@ -0,0 +1 @@
1
+ llm_rsa
@@ -0,0 +1,11 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name="llm_rsa"
7
+ requires-python=">=3.9"
8
+ dynamic = [ "keywords", "description", "version", "dependencies", "optional-dependencies", "readme", "license", "authors", "classifiers", "entry-points", "scripts", "urls"]
9
+
10
+ [tool.uv]
11
+ cache-keys = [{ file = "pyproject.toml" }, { file = "settings.ini" }, { file = "setup.py" }]
@@ -0,0 +1,46 @@
1
+ [DEFAULT]
2
+ # All sections below are required unless otherwise specified.
3
+ # See https://github.com/AnswerDotAI/nbdev/blob/main/settings.ini for examples.
4
+
5
+ ### Python library ###
6
+ repo = llm_rsa
7
+ lib_name = %(repo)s
8
+ version = 0.0.1
9
+ min_python = 3.9
10
+ license = apache2
11
+ black_formatting = False
12
+
13
+ ### nbdev ###
14
+ doc_path = _docs
15
+ lib_path = llm_rsa
16
+ nbs_path = nbs
17
+ recursive = True
18
+ tst_flags = notest
19
+ put_version_in_init = True
20
+ update_pyproject = True
21
+
22
+ ### Docs ###
23
+ branch = main
24
+ custom_sidebar = False
25
+ doc_host = https://%(user)s.github.io
26
+ doc_baseurl = /%(repo)s
27
+ git_url = https://github.com/%(user)s/%(repo)s
28
+ title = %(lib_name)s
29
+
30
+ ### PyPI ###
31
+ audience = Developers
32
+ author = Risheek kumar B
33
+ author_email = b.risheekkumar@gmail.com
34
+ copyright = 2026 onwards, %(author)s
35
+ description = Recursive self aggregation
36
+ keywords = nbdev jupyter notebook python
37
+ language = English
38
+ status = 3
39
+ user = risheekkumarb
40
+
41
+ ### Optional ###
42
+ requirements = fastcore litellm
43
+ # dev_requirements =
44
+ # console_scripts =
45
+ # conda_user =
46
+ # package_data =
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
llm_rsa-0.0.1/setup.py ADDED
@@ -0,0 +1,63 @@
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-2.0',
18
+ 'mit': 'MIT',
19
+ 'gpl2': 'GPL-2.0-only',
20
+ 'gpl3': 'GPL-3.0-or-later',
21
+ 'bsd3': 'BSD-3-Clause',
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 3.11 3.12 3.13'.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
+ dev_requirements = (cfg.get('dev_requirements') or '').split()
31
+
32
+ package_data = dict()
33
+ pkg_data = cfg.get('package_data', None)
34
+ if pkg_data:
35
+ package_data[cfg['lib_name']] = pkg_data.split() # split as multiple files might be listed
36
+ # Add package data to setup_cfg for setuptools.setup(..., **setup_cfg)
37
+ setup_cfg['package_data'] = package_data
38
+
39
+ setuptools.setup(
40
+ name = cfg['lib_name'],
41
+ license = licenses.get(cfg['license'].lower(), cfg['license']),
42
+ classifiers = [
43
+ 'Development Status :: ' + statuses[int(cfg['status'])],
44
+ 'Intended Audience :: ' + cfg['audience'].title(),
45
+ 'Natural Language :: ' + cfg['language'].title(),
46
+ ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]],
47
+ url = cfg['git_url'],
48
+ packages = setuptools.find_packages(),
49
+ include_package_data = True,
50
+ install_requires = requirements,
51
+ extras_require={ 'dev': dev_requirements },
52
+ dependency_links = cfg.get('dep_links','').split(),
53
+ python_requires = '>=' + cfg['min_python'],
54
+ long_description = open('README.md', encoding='utf-8').read(),
55
+ long_description_content_type = 'text/markdown',
56
+ zip_safe = False,
57
+ entry_points = {
58
+ 'console_scripts': cfg.get('console_scripts','').split(),
59
+ 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d']
60
+ },
61
+ **setup_cfg)
62
+
63
+