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 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
---
title: Chatbot
emoji: ๐Ÿ’ป
colorFrom: yellow
colorTo: green
sdk: gradio
sdk_version: 6.6.0
app_file: app.py
pinned: false
short_description: Chatbot
---

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

# Multi-User Memory Chatbot with LangChain, Tools, and Gradio

A conversational AI chatbot built with **LangChain**, **Gradio**, and multiple custom tools.  
This project supports:

- **multi-user chat sessions**
- **multiple threads per user**
- **memory-aware conversations**
- **tool calling**
- optional **tool activity display in the UI**

It is useful for experimenting with AI agents that can search, calculate, scrape websites, fetch weather, read files, and more.

---

## Features

- ๐Ÿ‘ค **Multiple users**
- ๐Ÿงต **Multiple chat threads per user**
- ๐Ÿง  **Conversation memory using `thread_id` and `user_id`**
- ๐Ÿ›  **Tool-enabled chatbot**
- ๐ŸŒ **Web search using Tavily**
- ๐Ÿ“š **Wikipedia search**
- โ˜๏ธ **Weather lookup**
- ๐Ÿงฎ **Calculator**
- ๐Ÿ **Python code execution**
- ๐Ÿ“„ **Read local files**
- ๐Ÿ”Ž **Scrape webpage text**
- ๐Ÿงพ **Pretty-print JSON**
- ๐Ÿ’พ **Save user preferences**
- ๐Ÿ–ฅ **System info tool**
- ๐ŸŽจ **Gradio web interface**
- โœ… Optional **tool activity panel** to show which tools were called

---

## Project Structure

A recommended project structure:

```text
project/
โ”‚
โ”œโ”€โ”€ tools.py               # All tool definitions
โ”œโ”€โ”€ memory_chatbot.py      # Chatbot / LangChain agent backend
โ”œโ”€โ”€ app.py                 # Gradio UI
โ”œโ”€โ”€ .env                   # Environment variables
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ””โ”€โ”€ README.md
```

> **Important:**  
> If your UI file imports `chatbot` like this:

```python
from memory_chatbot import chatbot
```

then your UI file should **not** also be named `memory_chatbot.py`, otherwise you may get a **circular import error**.  
Use a separate file name such as `app.py` for the Gradio interface.

---

## Tools Included

The project currently includes the following tools:

### 1. `time_date`
Returns todayโ€™s date in `yyyy-mm-dd` format.

### 2. `calculator`
Evaluates mathematical expressions.

### 3. `python_exec`
Executes Python code and returns local variables.

### 4. `get_weather`
Fetches current weather for a city using `wttr.in`.

### 5. `wikipedia_search`
Searches Wikipedia and returns a short summary.

### 6. `scrape_website`
Extracts text content from a webpage.

### 7. `read_file`
Reads the contents of a local file.

### 8. `format_json`
Formats and prettifies a JSON string.

### 9. `generate_sql`
Converts natural language into a placeholder SQL query.

### 10. `system_info`
Returns system/platform information.

### 11. `save_user_preference`
Stores user preference text (currently mocked).

### 12. `tool_tavily`
Performs web search using Tavily.

---

## Installation

## 1. Clone the repository

```bash
git clone https://github.com/your-username/your-repo-name.git
cd your-repo-name
```

## 2. Create a virtual environment

### Windows

```bash
python -m venv venv
venv\Scripts\activate
```

### macOS / Linux

```bash
python3 -m venv venv
source venv/bin/activate
```

## 3. Install dependencies

```bash
pip install -r requirements.txt
```

If you do not already have a `requirements.txt`, you can use something like this:

```txt
gradio
langchain
langchain-core
langchain-tavily
python-dotenv
requests
wikipedia
beautifulsoup4
```

Depending on your chatbot backend, you may also need your model provider package, such as:

- `langchain-openai`
- `langchain-google-genai`
- `langchain-groq`
- or another LLM integration

---

## Environment Variables

Create a `.env` file in the root directory.

Example:

```env
TAVILY_API_KEY=your_tavily_api_key
OPENAI_API_KEY=your_openai_api_key
```

If you are using another model provider, replace `OPENAI_API_KEY` with the correct key for your setup.

---

## Running the App

Start the Gradio interface with:

```bash
python app.py
```

Then open the local Gradio URL shown in the terminal, usually:

```text
http://127.0.0.1:7860
```

---

## How It Works

### User and Thread Management

Each conversation is identified using:

- `user_id`
- `thread_id`

This allows the chatbot to maintain separate memory for:

- different users
- different chat sessions for the same user

### Chat Flow

When the user sends a message:

1. the message is wrapped as a `HumanMessage`
2. the chatbot is invoked with `thread_id` and `user_id`
3. the agent may call one or more tools
4. the final AI response is displayed in the chat UI
5. the conversation is stored under that user/thread pair

---

## Gradio UI Features

The Gradio app includes:

- **User selector**
- **New user button**
- **Thread selector**
- **New chat button**
- **Chat area**
- **Message input box**

This makes it easy to simulate multiple users and sessions in one interface.

---

## Showing Tool Calls in the UI

Yes โ€” this project can be extended to show:

- which tool was called
- tool arguments
- tool output

For example, if the chatbot uses `get_weather("Delhi")`, the UI can display something like:

```text
Calling tool: get_weather
Arguments: {"city": "Delhi"}
Output: Delhi: +34ยฐC, Sunny
```

This is useful for:

- debugging
- understanding agent behavior
- teaching/demo purposes

A good way to display this is by adding a `gr.Markdown()` or `gr.Textbox()` panel in the UI and parsing:

- `AIMessage.tool_calls`
- `ToolMessage.content`

---

## Example Use Cases

- Ask todayโ€™s date
- Calculate expressions like `25 * 12`
- Execute small Python snippets
- Look up weather in a city
- Search Wikipedia topics
- Scrape a webpage summary
- Read a local file
- Format JSON data
- Save user preferences

---

## Example Prompts

Try asking:

```text
What is today's date?
```

```text
Calculate 125 * 48
```

```text
What is the weather in London?
```

```text
Search Wikipedia for Artificial Intelligence
```

```text
Read the contents of sample.txt
```

```text
Format this JSON: {"name":"John","age":25}
```

---

## Security Warning

This project includes some tools that are **unsafe for public deployment** without restrictions.

### Risky tools

- `calculator` uses `eval()`
- `python_exec` uses `exec()`
- `read_file` can access local files
- `scrape_website` can fetch arbitrary URLs

### Why this matters

If exposed publicly, users may be able to:

- run arbitrary Python code
- read sensitive local files
- access internal resources
- misuse the server

### Recommendation

Use this project:

- for **local development**
- for **learning**
- for **internal testing only**

Before deploying publicly, you should:

- remove `eval()` and `exec()`
- restrict file access
- validate URLs
- sandbox execution
- add authentication and rate limiting

Tiny chatbot, big chaos potential. Better to keep the chaos leashed.

---

## Known Notes

### 1. Circular Import Risk

If your UI file is named `memory_chatbot.py` and also contains:

```python
from memory_chatbot import chatbot
```

you will likely get an import issue.

### Fix

Rename the Gradio UI file to something like:

```text
app.py
```

and keep the chatbot backend in:

```text
memory_chatbot.py
```

---

### 2. Tool Results May Differ

Some tools depend on external services:

- `wttr.in`
- `Wikipedia`
- `Tavily`
- websites being scraped

If those services are unavailable, the tool may fail or return unexpected results.

---

## Future Improvements

Possible enhancements for this project:

- real memory store integration
- persistent database for chat history
- streaming responses
- live tool-call updates in the UI
- better error handling
- authentication
- safer code execution sandbox
- SQL generation using LLM
- file upload support
- improved styling for the chat interface

---

## Sample `tools.py`

This file contains all your custom tools used by the chatbot agent.

It includes tools for:

- date/time
- calculator
- Python execution
- weather
- Wikipedia
- web scraping
- file reading
- JSON formatting
- SQL generation
- system information
- user preference saving
- Tavily search

---

## Sample Workflow

1. Start app
2. Select or create a user
3. Create a new thread
4. Ask a question
5. Agent decides whether to use tools
6. Tool result is returned
7. Final AI answer is shown
8. Conversation history is stored per user/thread

---

## Requirements Summary

Main libraries used:

- `gradio`
- `langchain`
- `langchain-core`
- `langchain-tavily`
- `requests`
- `wikipedia`
- `beautifulsoup4`
- `python-dotenv`

---

## License

This project is for educational and development use.  
Add your preferred license here, for example:

```text
MIT License
```

---

## Author

Built with LangChain, Gradio, and a healthy amount of agent curiosity.

If you want, you can customize this section with your name, GitHub profile, or portfolio link.

---

## Contributing

Contributions are welcome.

You can improve this project by:

- adding safer tool implementations
- improving UI design
- adding persistent memory
- improving tool logging
- integrating streaming
- adding tests

---

## Final Notes

This project is a great starting point if you want to learn:

- LangChain tools
- agent-based workflows
- memory-aware chat apps
- multi-thread chat management
- Gradio interfaces

If you are planning to deploy it publicly, please review the security concerns carefully before doing so.