-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
275 lines (224 loc) · 9.51 KB
/
Copy pathindex.html
File metadata and controls
275 lines (224 loc) · 9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LogicAI - Structuring Thought with Generative AI</title>
<style>
body {
font-family: 'Helvetica Neue', sans-serif;
line-height: 1.6;
margin: 40px auto;
max-width: 800px;
padding: 0 20px;
color: #333;
}
h1, h2, h3 {
color: #2c3e50;
}
code {
background-color: #f4f4f4;
padding: 2px 4px;
border-radius: 4px;
font-family: monospace;
}
pre {
background-color: #f4f4f4;
padding: 15px;
overflow-x: auto;
border-radius: 5px;
}
.author {
font-style: italic;
color: #555;
}
</style>
</head>
<body>
<h1>LogicAI: Structuring Thought with Generative AI</h1>
<p class="author">By Olivia Chan</p>
<h2>💡 Problem: How Can We Think More Clearly?</h2>
<p>
In today's world of overwhelming decisions—"Where should I live?", "What career should I pursue?", "How can I improve my team?"—clear thinking is more important than ever. Logic trees, like those used by McKinsey consultants, help break problems into structured, MECE (Mutually Exclusive, Collectively Exhaustive) branches. But what if AI could build these trees for us?
</p>
<h2>🤖 AI Solution: LogicAI</h2>
<p>
LogicAI is a generative AI assistant that turns any complex problem into a visual logic tree. Powered by Gemini 2.0 Flash and presented through a simple Gradio interface, it:
<ul>
<li>Takes a user’s problem statement</li>
<li>Uses LLM reasoning to break it into structured logic trees</li>
<li>Visualizes the tree with <code>Graphviz</code></li>
<li>Evaluates the logic with MECE principles</li>
</ul>
</p>
<h2>🛠️ How It Works</h2>
<h3>1. Import neccessary packages</h3>
<pre><code>!pip install -q -U gradio graphviz(...)</code></pre>
<h3>2.Initialize clients</h3>
<pre><code>def initialize_client():
user_secrets = UserSecretsClient()
google_api_key = user_secrets.get_secret("GOOGLE_API_KEY")
return genai.Client(api_key=google_api_key)
)</code></pre>
<h3>3. Generate Logic Tree using Gemini</h3>
<pre><code> prompt = f"""You're an expert in structured thinking and logic trees (like McKinsey's MECE framework).
Create a clean logic tree for the problem below.
Requirements:
- Start with the core problem
- Use a top-down tree format with indentation (max 3 levels)
- Keep node labels short (max 5-6 words)
- Avoid long explanations
- Output only the logic tree
-The tree structure, there should be a hierarchical relationship where items labeled with Roman numerals (I, II, etc.) are parent nodes,
and their corresponding lettered items (a, b, c) should be child nodes beneath them.
So, the output should look like:
I. Workload Issues
a. Excessive Hours
b. Unrealistic Deadlines
c. Constant Context Switching
II. Lack of Control
a. Limited Decision-Making Authority
b. Micromanagement
III. Insufficient Rewards
a. Inadequate Compensation
b. Lack of Recognition
c. Limited Career Growth
IV. Workplace Dynamics
a. Poor Management Practices
b. Toxic Culture
c. Ineffective Communication
Problem: "{problem_statement}"
"""
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=prompt)
return response.text
)</code></pre>
<p>
Give few-shots example for the model to learn how to structure the answer.
</p>
<h3>4. Evaluate the logic tree</h3>
<pre><code>eval_prompt = f""" Evaluate the following logic tree for the problem: "{problem_statement}"
Criteria: 1. Is the logic tree mutually exclusive and collectively exhaustive (MECE)?
2. Does it provide clear, actionable branches?
3. Is it logically sound and helpful for problem-solving?
Rating Rubric:
5 (Very Good): MECE, actionable, and logically sound
4 (Good): Mostly MECE and actionable with minor issues
3 (OK): Reasonable structure but lacks clarity or exhaustiveness
2 (Bad): Major logic or structure flaws
1 (Very Bad): Not usable or logically broken
Logic Tree: {tree_text}
Please rate each criteria from 1-5 according to the rating rubic and give brief feedback. """
response = client.models.generate_content(
model="gemini-2.0-flash", contents=eval_prompt)
return response.text
)</code></pre>
<p>
Here we again instruct the model how to evaluate the prompt, and rate each prompts and give feedback.
We can rephrase the prompt if the result is not satisfying.
</p>
<h3>5. Parse Output into Structured Format</h3>
<pre><code>def parse_logic_tree(tree_text):
lines = tree_text.strip().split('\n')
... # extract Roman and lettered items into nested dict</code></pre>
<h3>6. Create static logic tree image</h3>
<pre><code> dot = Digraph(comment='Logic Tree Mindmap', format='svg')</code></pre>
<h3>7. Set up for Gradio Interface</h3>
<pre><code>with gr.Blocks(title="Logic Tree Generator") as demo:(...)</code></pre>
<h2>📷 Demo</h2>
<p>
Try it live on Kaggle: <br>
<a href="https://www.kaggle.com/code/kaggleoc/genai-2025q1-capstone-project-final" target="_blank">
🧠 Launch Logic Tree Generator
</a>
</p>
<p>Enter your problem statement and click Generate Logic Tree</p>
<img src="assets/img2.png" alt="Screenshot1" width="500">
<p>A sneak peek at the logic tree generated</p>
<img src="assets/img1.png" alt="Screenshot2" width="500">
<p> To thoroughly analyze each node, we'll implement a RAG-based Q&A system, enriching our insights with direct document referencing.</p>
<h3>8. Set up simple Document Q&A with RAG</h3>
<h3> Install necessary packages </h3>
<pre><code>
from chromadb import Documents, EmbeddingFunction, Embeddings</code></pre>
<h3>9. Fill in the documents</h3>
<pre><code>DOCUMENT1="""Taiwan offers a vibrant and convenient lifestyle(...)"""</code></pre>
<p> We copy and paste what we want the model to know here.</p>
<h3>10. Covert the documents into embeddings</h3>
<pre><code>class GeminiEmbeddingFunction(EmbeddingFunction):
# Specify whether to generate embeddings for documents, or queries
document_mode = True
(...)
</code></pre>
<p> Turning documents into embeddings in RAG lets the model quickly find relevant info by comparing semantic meaning, not just keywords.
Retrieval: How the RAG system fetches relevant documents for the query.</p>
<h3>11. Set up vector databases using chromadb</h3>
<pre><code>
import chromadb
DB_NAME = "googlecardb"
embed_fn = GeminiEmbeddingFunction()
embed_fn.document_mode = True
chroma_client = chromadb.Client()
db = chroma_client.get_or_create_collection(name=DB_NAME, embedding_function=embed_fn)
db.add(documents=documents, ids=[str(i) for i in range(len(documents))])
</code></pre>
<p>Chroma DB enables efficient semantic search and retrieval of information, crucial for advanced RAG applications and knowledge management.</p>
<h3>12. Switch to query mode when generating embeddings</h3>
<pre><code>embed_fn.document_mode = False
# Search the Chroma DB using the specified query.
query = "Is Taiwan a good place to live?"
result = db.query(query_texts=[query], n_results=3)
[all_passages] = result["documents"]
Markdown(all_passages[1])
#for passage in result["documents"][0]: # result["documents"] is a list of lists
#display(Markdown(passage))
from IPython.display import Markdown, display
# Get the passages and their distances
passages = result["documents"][0]
scores = result["distances"][0] # Same index structure: list of scores per query
for i, (passage, score) in enumerate(zip(passages, scores), start=1):
display(Markdown(f"### Passage {i} (Similarity Score: {1 - score:.4f})\n\n{passage}"))
</code></pre>
<h3>13. Make query using Gemini Models</h3>
<pre><code>query_oneline = query.replace("\n", " ")
# This prompt is where you can specify any guidance on tone, or what topics the model should stick to, or avoid.
prompt = f"""You are a knowlegeable consultant that answers questions using text from the reference passage included below.
Remember you have guided the audience with bullet points like:
I. Affordability
a. Housing Costs
b. Taxes and Utilities
II. Career Opportunities
a. Job Market Availability
b. Salary Potential
III. Lifestyle Preferences
a. Urban vs. Rural
b. Climate Preferences
c. Recreational Activities
Based on the content you have generated, provide strong reasoning for your answers according to the above structure.
If the passage is irrelevant to the answer, you may ignore it.
QUESTION: {query_oneline}
"""
# Add the retrieved documents to the prompt.
for passage in all_passages:
passage_oneline = passage.replace("\n", " ")
prompt += f"PASSAGE: {passage_oneline}\n"
print(prompt)
answer = client.models.generate_content(
model="gemini-2.0-flash",
contents=prompt)
</code></pre>
<h2>⚠️ Limitations</h2>
<ul>
<li>Deep branching is still linear; more levels may confuse users</li>
<li>Limited logic validation—some outputs may not be truly MECE</li>
</ul>
<h2>🚀 What's next</h2>
<ul>
<li>Support for document uploads to enhance RAG and grounding capabilities.</li>
<li>Enable function calling to dynamically expand or edit logic tree nodes.</li>
<li>Add vector store for persistent knowledge integration and retrieval.</li>
</ul>
<p><em>LogicAI empowers structured thinking—one tree at a time.</em></p>
</body>
</html>