simonbb 0.0.10__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.10
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>
@@ -9,17 +9,33 @@ License-File: LICENSE
9
9
  Classifier: Operating System :: OS Independent
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Requires-Python: >=3.9
12
- Requires-Dist: gymnasium>=1.3.0
13
- Requires-Dist: matplotlib>=3.10.8
14
- Requires-Dist: numpy>=2.4.0
15
- Requires-Dist: opencv-python>=5.0.0.93
16
- Requires-Dist: pytorch-ignite>=0.5.4
17
- Requires-Dist: pyyaml>=6.0.3
18
- Requires-Dist: ray>=2.56.0
19
- Requires-Dist: stable-baselines3>=2.9.0
20
- Requires-Dist: torch>=2.9.1
21
- Requires-Dist: torchvision>=0.24.1
22
- Requires-Dist: transformers>=4.57.3
12
+ Requires-Dist: chromadb~=1.5.9
13
+ Requires-Dist: google-search-results
14
+ Requires-Dist: gymnasium[classic-control,other]
15
+ Requires-Dist: langchain-chroma~=1.1.0
16
+ Requires-Dist: langchain-community~=0.4.2
17
+ Requires-Dist: langchain-core~=1.6.12
18
+ Requires-Dist: langchain-huggingface>=1.2.1
19
+ Requires-Dist: langchain-openai~=1.7.2
20
+ Requires-Dist: langchain-text-splitters~=1.1.3
21
+ Requires-Dist: langchain[mcp]~=1.4.6
22
+ Requires-Dist: langgraph~=1.2.16
23
+ Requires-Dist: matplotlib>=3.10.9
24
+ Requires-Dist: numpy~=2.4.6
25
+ Requires-Dist: opencv-python~=5.0.0.93
26
+ Requires-Dist: pandas
27
+ Requires-Dist: pillow>=11.3.0
28
+ Requires-Dist: pydantic
29
+ Requires-Dist: python-dotenv
30
+ Requires-Dist: pytorch-ignite~=0.5.5
31
+ Requires-Dist: pyyaml~=6.0.3
32
+ Requires-Dist: ray~=2.56.1
33
+ Requires-Dist: scikit-learn
34
+ Requires-Dist: stable-baselines3~=2.9.0
35
+ Requires-Dist: tensorboard
36
+ Requires-Dist: torchvision~=0.24.1
37
+ Requires-Dist: torch~=2.9.1
38
+ Requires-Dist: transformers>=4.57.6
23
39
  Description-Content-Type: text/markdown
24
40
 
25
41
  # Background
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["hatchling >= 1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "simonbb"
7
+ version = "0.0.12"
8
+ authors = [
9
+ { name="Huaxia Rui", email="huaxia.rui@simon.rochester.edu" },
10
+ ]
11
+ description = "A small package to facilitate teaching AI courses at business schools"
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ license = "MIT"
19
+ license-files = ["LICEN[CS]E*"]
20
+ dependencies = [
21
+ "matplotlib >= 3.10.9",
22
+ "numpy ~= 2.4.6",
23
+ "torch ~= 2.9.1",
24
+ "torchvision ~= 0.24.1",
25
+ "transformers >= 4.57.6",
26
+ "gymnasium[classic-control, other]",
27
+ "tensorboard",
28
+ "pytorch-ignite ~= 0.5.5",
29
+ "stable_baselines3 ~= 2.9.0",
30
+ "ray ~= 2.56.1",
31
+ "opencv-python ~= 5.0.0.93",
32
+ "pyyaml ~= 6.0.3",
33
+ "langchain-core ~= 1.6.12",
34
+ "langchain[mcp] ~= 1.4.6",
35
+ "langgraph ~= 1.2.16",
36
+ "langchain-community ~= 0.4.2",
37
+ "langchain-chroma ~= 1.1.0",
38
+ "langchain-openai ~= 1.7.2",
39
+ "langchain-huggingface >= 1.2.1",
40
+ "langchain_text_splitters ~= 1.1.3",
41
+ "chromadb ~= 1.5.9",
42
+ "Pillow >= 11.3.0",
43
+ "python-dotenv",
44
+ "pydantic",
45
+ "pandas",
46
+ "scikit-learn",
47
+ "google-search-results",
48
+ ]
49
+ [project.urls]
50
+ Homepage = "https://simonbb.com"
@@ -1,11 +1,11 @@
1
1
  import re
2
2
  import torch
3
3
  import torch.nn as nn
4
- from transformers import BertTokenizer, BertModel, BertConfig
4
+ from transformers import AutoTokenizer, BertModel, BertConfig
5
5
 
6
6
  #%%
7
7
 
8
- tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
8
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
9
9
 
10
10
  class BertClassifier( nn.Module ):
11
11
  def __init__(self, freeze_bert=False):
@@ -33,7 +33,7 @@ def BertPreprocessor( txt ):
33
33
  for s in txt:
34
34
  s = re.sub(r'(@.*?)[\s]', ' ', s)
35
35
  s = re.sub(r'\s+', ' ', s).strip()
36
- encoded = tokenizer.encode_plus( text=s, add_special_tokens=True, max_length=128, padding='max_length', truncation=True, return_attention_mask=True )
36
+ encoded = tokenizer( text=s, add_special_tokens=True, max_length=128, padding='max_length', truncation=True, return_attention_mask=True, return_tensors="pt" )
37
37
  input_ids.append( encoded.get('input_ids') ) # Add the outputs to the lists
38
38
  attention_masks.append( encoded.get('attention_mask') )
39
39
  return torch.tensor( input_ids ), torch.tensor( attention_masks )
@@ -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):
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
- from typing import Annotated, TypedDict, get_args, Any, Protocol, Sequence
4
+ from typing import Annotated, TypedDict, get_args, Any, Sequence
5
5
  from dataclasses import dataclass
6
6
  from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
7
7
 
@@ -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
136
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
234
+
235
+
236
+ build_rag = rag_main
137
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):
@@ -199,6 +300,7 @@ class MultiQueryRerankRetriever(BaseRetriever):
199
300
  )
200
301
  return [doc for _, doc in scored_docs[:self.top_n]]
201
302
 
303
+ # override _get_relevant_documents() method from BaseRetriever
202
304
  def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> list[Document]:
203
305
  """Retrieve documents using simple or multi-query retrieval."""
204
306
  # Simple retrieval
@@ -216,7 +318,7 @@ class MultiQueryRerankRetriever(BaseRetriever):
216
318
  unique_docs = self._unique_union(doc_lists)
217
319
  return self._rerank(query, unique_docs)
218
320
 
219
- #%%
321
+ #%% ParentDocumentRetriever
220
322
 
221
323
  class DummyEmbeddings(Embeddings):
222
324
  """Return constant 1-dimensional embeddings without using an LLM."""
@@ -269,6 +371,7 @@ class ParentDocumentRetriever(BaseRetriever):
269
371
  if child_docs:
270
372
  self._child_store.add_documents( documents=child_docs )
271
373
 
374
+ # override _get_relevant_documents() method from BaseRetriever
272
375
  def _get_relevant_documents(
273
376
  self,
274
377
  query: str,
@@ -429,34 +532,17 @@ class HypotheticalQuestionRetriever(BaseRetriever):
429
532
  if not chunk_ids:
430
533
  return []
431
534
 
432
- records = self._chunk_collection.get(ids=chunk_ids, include=["documents", "metadatas"])
433
- by_id = {
535
+ records = self._chunk_collection.get( ids=chunk_ids, include=["documents", "metadatas"] )
536
+ records_by_id = {
434
537
  record_id: Document(page_content=text, metadata=metadata or {})
435
538
  for record_id, text, metadata in zip(
436
539
  records["ids"], records["documents"], records["metadatas"], strict=True
437
540
  )
438
541
  }
439
- return [by_id[chunk_id] for chunk_id in chunk_ids if chunk_id in by_id]
440
-
542
+ return [ records_by_id[chunk_id] for chunk_id in chunk_ids if chunk_id in records_by_id ]
441
543
 
442
544
 
443
- #%% RAG with Routing
444
-
445
- domain_prompt = """You are a helpful assistant answering questions based on provided document snippets relating to {domain}.
446
-
447
- IMPORTANT INSTRUCTIONS:
448
- 1. Base your answer ONLY on the provided context snippets below.
449
- 2. Synthesize information from multiple snippets if needed.
450
- 3. If the snippets contain partial information, provide the best answer you can with what's available.
451
- 4. Only say "There wasn't enough information to answer the question" if the snippets truly contain NO relevant information.
452
- 5. Always cite your sources using the snippet numbers in parentheses, like (1), (2), etc.
453
-
454
- The snippets are provided in this format:
455
- Snippet 1: <text content>
456
- Snippet 2: <text content>
457
- ...
458
-
459
- {context}"""
545
+ #%% legacy: to be removed in v1
460
546
 
461
547
  def multiRagBuilder( persist_directory, domain_literals, router_prompt, llm, embeddings, reranker, query_llm=None, k=3):
462
548
  """
@@ -533,7 +619,7 @@ def multiRagBuilder( persist_directory, domain_literals, router_prompt, llm, emb
533
619
 
534
620
  retrievers = {}
535
621
  retriever_nodes = {}
536
- for domain in domains:
622
+ for domain in domains:
537
623
  retrievers[domain] = MultiQueryRerankRetriever( persist_directory=persist_directory, collection_name=domain, embeddings=embeddings, query_llm=query_llm, reranker=reranker, k=k)
538
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.
539
625
  builder.add_node(domain, retriever_nodes[domain])
@@ -1,34 +0,0 @@
1
- [build-system]
2
- requires = ["hatchling >= 1.26"]
3
- build-backend = "hatchling.build"
4
-
5
- [project]
6
- name = "simonbb"
7
- version = "0.0.10"
8
- authors = [
9
- { name="Huaxia Rui", email="huaxia.rui@simon.rochester.edu" },
10
- ]
11
- description = "A small package to facilitate teaching AI courses at business schools"
12
- readme = "README.md"
13
- requires-python = ">=3.9"
14
- classifiers = [
15
- "Programming Language :: Python :: 3",
16
- "Operating System :: OS Independent",
17
- ]
18
- license = "MIT"
19
- license-files = ["LICEN[CS]E*"]
20
- dependencies = [
21
- "matplotlib >= 3.10.8",
22
- "torch >= 2.9.1",
23
- "torchvision >=0.24.1",
24
- "numpy >=2.4.0",
25
- "transformers >= 4.57.3",
26
- "gymnasium >= 1.3.0",
27
- "pytorch-ignite >= 0.5.4",
28
- "stable_baselines3 >= 2.9.0",
29
- "ray >= 2.56.0",
30
- "opencv-python >= 5.0.0.93",
31
- "pyyaml >= 6.0.3"
32
- ]
33
- [project.urls]
34
- Homepage = "https://simonbb.com"
File without changes
File without changes
File without changes