simonbb 0.0.11__tar.gz → 0.0.12__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simonbb
3
- Version: 0.0.11
3
+ Version: 0.0.12
4
4
  Summary: A small package to facilitate teaching AI courses at business schools
5
5
  Project-URL: Homepage, https://simonbb.com
6
6
  Author-email: Huaxia Rui <huaxia.rui@simon.rochester.edu>
@@ -10,26 +10,32 @@ Classifier: Operating System :: OS Independent
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Requires-Python: >=3.9
12
12
  Requires-Dist: chromadb~=1.5.9
13
- Requires-Dist: gymnasium~=1.3.0
13
+ Requires-Dist: google-search-results
14
+ Requires-Dist: gymnasium[classic-control,other]
14
15
  Requires-Dist: langchain-chroma~=1.1.0
15
16
  Requires-Dist: langchain-community~=0.4.2
16
17
  Requires-Dist: langchain-core~=1.6.12
18
+ Requires-Dist: langchain-huggingface>=1.2.1
17
19
  Requires-Dist: langchain-openai~=1.7.2
18
20
  Requires-Dist: langchain-text-splitters~=1.1.3
19
21
  Requires-Dist: langchain[mcp]~=1.4.6
20
22
  Requires-Dist: langgraph~=1.2.16
21
- Requires-Dist: matplotlib~=3.10.9
23
+ Requires-Dist: matplotlib>=3.10.9
22
24
  Requires-Dist: numpy~=2.4.6
23
25
  Requires-Dist: opencv-python~=5.0.0.93
24
- Requires-Dist: pydantic~=2.14.1
25
- Requires-Dist: python-dotenv~=1.2.4
26
+ Requires-Dist: pandas
27
+ Requires-Dist: pillow>=11.3.0
28
+ Requires-Dist: pydantic
29
+ Requires-Dist: python-dotenv
26
30
  Requires-Dist: pytorch-ignite~=0.5.5
27
31
  Requires-Dist: pyyaml~=6.0.3
28
32
  Requires-Dist: ray~=2.56.1
33
+ Requires-Dist: scikit-learn
29
34
  Requires-Dist: stable-baselines3~=2.9.0
35
+ Requires-Dist: tensorboard
30
36
  Requires-Dist: torchvision~=0.24.1
31
37
  Requires-Dist: torch~=2.9.1
32
- Requires-Dist: transformers~=4.57.6
38
+ Requires-Dist: transformers>=4.57.6
33
39
  Description-Content-Type: text/markdown
34
40
 
35
41
  # Background
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "simonbb"
7
- version = "0.0.11"
7
+ version = "0.0.12"
8
8
  authors = [
9
9
  { name="Huaxia Rui", email="huaxia.rui@simon.rochester.edu" },
10
10
  ]
@@ -18,12 +18,13 @@ classifiers = [
18
18
  license = "MIT"
19
19
  license-files = ["LICEN[CS]E*"]
20
20
  dependencies = [
21
- "matplotlib ~= 3.10.9",
21
+ "matplotlib >= 3.10.9",
22
22
  "numpy ~= 2.4.6",
23
23
  "torch ~= 2.9.1",
24
24
  "torchvision ~= 0.24.1",
25
- "transformers ~= 4.57.6",
26
- "gymnasium ~= 1.3.0",
25
+ "transformers >= 4.57.6",
26
+ "gymnasium[classic-control, other]",
27
+ "tensorboard",
27
28
  "pytorch-ignite ~= 0.5.5",
28
29
  "stable_baselines3 ~= 2.9.0",
29
30
  "ray ~= 2.56.1",
@@ -35,10 +36,15 @@ dependencies = [
35
36
  "langchain-community ~= 0.4.2",
36
37
  "langchain-chroma ~= 1.1.0",
37
38
  "langchain-openai ~= 1.7.2",
39
+ "langchain-huggingface >= 1.2.1",
38
40
  "langchain_text_splitters ~= 1.1.3",
39
41
  "chromadb ~= 1.5.9",
40
- "python-dotenv ~= 1.2.4",
41
- "pydantic ~= 2.14.1"
42
+ "Pillow >= 11.3.0",
43
+ "python-dotenv",
44
+ "pydantic",
45
+ "pandas",
46
+ "scikit-learn",
47
+ "google-search-results",
42
48
  ]
43
49
  [project.urls]
44
50
  Homepage = "https://simonbb.com"
@@ -214,8 +214,7 @@ def setup_ignite(
214
214
  trainer.should_terminate = True
215
215
  trainer.state.solved = False
216
216
  if trainer.should_terminate:
217
- print(f"Episode {trainer.state.episode}, "
218
- f"avg_reward {avg_reward:.2f}, terminating")
217
+ print(f"Episode {trainer.state.episode}, avg_reward {avg_reward:.2f}, terminating")
219
218
 
220
219
 
221
220
  # hyperparams tuner
@@ -262,14 +261,7 @@ def tune_params(
262
261
  print(best.metrics)
263
262
 
264
263
 
265
- def train_or_tune(
266
- args: argparse.Namespace,
267
- train_func: TrainFunc,
268
- device: torch.device,
269
- best_params: Hyperparams,
270
- extra_params: tt.Optional[dict] = None,
271
- extra_space: tt.Optional[dict] = None,
272
- ):
264
+ def train_or_tune( args: argparse.Namespace, train_func: TrainFunc, device: torch.device, best_params: Hyperparams, extra_params: tt.Optional[dict] = None, extra_space: tt.Optional[dict] = None ):
273
265
  random.seed(SEED)
274
266
  torch.manual_seed(SEED)
275
267
  if args.params == "common":
@@ -280,9 +272,9 @@ def train_or_tune(
280
272
  if extra_params is None:
281
273
  extra_params = {}
282
274
  if args.tune is None:
283
- train_func(params, device, extra_params)
275
+ train_func( params, device, extra_params )
284
276
  else:
285
- tune_params(params, train_func, device, samples=args.tune, extra_space=extra_space)
277
+ tune_params( params, train_func, device, samples=args.tune, extra_space=extra_space )
286
278
 
287
279
 
288
280
  def save_model(model, path, global_step, start_iteration):
@@ -91,6 +91,22 @@ Snippet 2: <text content>
91
91
 
92
92
  {context}"""
93
93
 
94
+ domain_prompt = """You are a helpful assistant answering questions based on provided document snippets relating to {domain}.
95
+
96
+ IMPORTANT INSTRUCTIONS:
97
+ 1. Base your answer ONLY on the provided context snippets below.
98
+ 2. Synthesize information from multiple snippets if needed.
99
+ 3. If the snippets contain partial information, provide the best answer you can with what's available.
100
+ 4. Only say "There wasn't enough information to answer the question" if the snippets truly contain NO relevant information.
101
+ 5. Always cite your sources using the snippet numbers in parentheses, like (1), (2), etc.
102
+
103
+ The snippets are provided in this format:
104
+ Snippet 1: <text content>
105
+ Snippet 2: <text content>
106
+ ...
107
+
108
+ {context}"""
109
+
94
110
  def format_documents(documents: Sequence[Document]) -> str:
95
111
  snippets = []
96
112
  for i, doc in enumerate(documents, start=1):
@@ -112,7 +128,6 @@ def rag_basic(retriever: BaseRetriever, model: BaseChatModel) -> Runnable:
112
128
  }
113
129
  return inputs | prompt | model | StrOutputParser()
114
130
 
115
-
116
131
  def rag_main(retriever: BaseRetriever, model: BaseChatModel) -> Runnable:
117
132
  """Return an LCEL chain accepting a question string and producing an dic with 4 keys/values
118
133
  -- 'sources': original list of Documents from retriever
@@ -132,14 +147,100 @@ def rag_main(retriever: BaseRetriever, model: BaseChatModel) -> Runnable:
132
147
  | RunnablePassthrough.assign( answer=prompt | model | StrOutputParser() )
133
148
  )
134
149
 
135
- build_rag = rag_main
150
+
151
+ def rag_router( router_llm, router_prompt, domain_literals, retrievers, rag_llm=None ):
152
+ """
153
+ domain_literals: the last one is a placeholder if the router finds no domain matches the query
154
+ """
155
+ domains = get_args(domain_literals)[:-1] # exclude the placeholder
156
+ nodomain = get_args(domain_literals)[-1]
157
+ if rag_llm is None:
158
+ rag_llm = router_llm
159
+ # use the functional form of TypedDict instead of the class form to accommodate Python 3.14
160
+ State = TypedDict(
161
+ "State",
162
+ {
163
+ "messages": Annotated[list, add_messages],
164
+ "query": str,
165
+ "domain": domain_literals,
166
+ "documents": list[Document],
167
+ "answer": str,
168
+ }
169
+ )
170
+ class Input(TypedDict):
171
+ query: str
172
+
173
+ Output = TypedDict(
174
+ "Output",
175
+ {
176
+ "domain": domain_literals,
177
+ "documents": list[Document],
178
+ "answer": str
179
+ }
180
+ )
181
+
182
+ def router_node(state) -> State:
183
+ user_message = HumanMessage( state["query"] )
184
+ messages = [ SystemMessage(router_prompt), *state["messages"], user_message ]
185
+ res = router_llm.invoke(messages)
186
+ return {
187
+ "domain": res.content.strip(),
188
+ "messages": [user_message, res], # update conversation history
189
+ }
190
+
191
+ def pick_retriever( state ):
192
+ for domain in domains:
193
+ if re.search( domain, state['domain'] ):
194
+ return domain
195
+ return 'generate_answer'
196
+
197
+ def generate_answer(state) -> State:
198
+ snippets = []
199
+ for i, doc in enumerate(state.get('documents', []), start=1):
200
+ snippets.append(f"Snippet {i}: {doc.page_content}")
201
+ context = "\n".join(snippets)
202
+ if state.get('domain', '')!=nodomain:
203
+ prompt = ChatPromptTemplate.from_messages( [ ("system", domain_prompt), ("human", "{query}") ])
204
+ messages = prompt.format_messages( domain=state.get('domain', ''), context=context, query=state["query"] )
205
+ else:
206
+ prompt = ChatPromptTemplate.from_messages( [ ("system", 'You are a helpful assistant.'), ("human", "{query}") ])
207
+ messages = prompt.format_messages( query=state["query"] )
208
+ res = rag_llm.invoke(messages)
209
+ return {
210
+ "answer": res.content,
211
+ "messages": res, # update conversation history
212
+ }
213
+
214
+ def retriever_node( domain, state):
215
+ query = re.sub(domain, 'this class', state["query"] ) # using the course code hurts RAG since the course code is rarely used in documents.
216
+ #print( f"domain={domain}; query={query}")
217
+ documents = retrievers[domain].invoke( query )
218
+ return { "documents": documents, 'query': query }
219
+
220
+ builder = StateGraph(State, input_schema=Input, output_schema=Output)
221
+ builder.add_node("router", router_node)
222
+ builder.add_edge(START, "router")
223
+ builder.add_conditional_edges("router", pick_retriever)
224
+
225
+ retriever_nodes = {}
226
+ for domain in domains:
227
+ retriever_nodes[domain] = partial( retriever_node, domain ) # the 1st argument is the partial function. the rest are frozen arguments passed positionally to fill the leftmost parameters of the original function.
228
+ builder.add_node(domain, retriever_nodes[domain])
229
+ builder.add_edge(domain, "generate_answer")
230
+
231
+ builder.add_node("generate_answer", generate_answer)
232
+ builder.add_edge("generate_answer", END)
233
+ return builder
136
234
 
137
235
 
236
+ build_rag = rag_main
237
+
138
238
  """
139
239
  Retrievers are subclasses of LangChain's BaseRetriever which inherits from Pydantic's BaseModel.
140
240
  Unlike ordinary Python classes where attributes declared in the class body are class attributes shared by all instances,
141
241
  Pydantic model fields declared with type annotations are instance attributes, not shared class attributes, even though they are declared in the class body.
142
242
  """
243
+
143
244
  #%% MultiQueryRerankRetriever
144
245
 
145
246
  class MultiQueryRerankRetriever(BaseRetriever):
@@ -217,7 +318,7 @@ class MultiQueryRerankRetriever(BaseRetriever):
217
318
  unique_docs = self._unique_union(doc_lists)
218
319
  return self._rerank(query, unique_docs)
219
320
 
220
- #%%
321
+ #%% ParentDocumentRetriever
221
322
 
222
323
  class DummyEmbeddings(Embeddings):
223
324
  """Return constant 1-dimensional embeddings without using an LLM."""
@@ -441,24 +542,7 @@ class HypotheticalQuestionRetriever(BaseRetriever):
441
542
  return [ records_by_id[chunk_id] for chunk_id in chunk_ids if chunk_id in records_by_id ]
442
543
 
443
544
 
444
-
445
- #%% RAG with Routing
446
-
447
- domain_prompt = """You are a helpful assistant answering questions based on provided document snippets relating to {domain}.
448
-
449
- IMPORTANT INSTRUCTIONS:
450
- 1. Base your answer ONLY on the provided context snippets below.
451
- 2. Synthesize information from multiple snippets if needed.
452
- 3. If the snippets contain partial information, provide the best answer you can with what's available.
453
- 4. Only say "There wasn't enough information to answer the question" if the snippets truly contain NO relevant information.
454
- 5. Always cite your sources using the snippet numbers in parentheses, like (1), (2), etc.
455
-
456
- The snippets are provided in this format:
457
- Snippet 1: <text content>
458
- Snippet 2: <text content>
459
- ...
460
-
461
- {context}"""
545
+ #%% legacy: to be removed in v1
462
546
 
463
547
  def multiRagBuilder( persist_directory, domain_literals, router_prompt, llm, embeddings, reranker, query_llm=None, k=3):
464
548
  """
@@ -535,7 +619,7 @@ def multiRagBuilder( persist_directory, domain_literals, router_prompt, llm, emb
535
619
 
536
620
  retrievers = {}
537
621
  retriever_nodes = {}
538
- for domain in domains:
622
+ for domain in domains:
539
623
  retrievers[domain] = MultiQueryRerankRetriever( persist_directory=persist_directory, collection_name=domain, embeddings=embeddings, query_llm=query_llm, reranker=reranker, k=k)
540
624
  retriever_nodes[domain] = partial( retriever_node, domain ) # the 1st argument is the partial function. the rest are frozen arguments passed positionally to fill the leftmost parameters of the original function.
541
625
  builder.add_node(domain, retriever_nodes[domain])
File without changes
File without changes
File without changes