Skip to content

Commit 3cd6b1e

Browse files
w3ijierobot-ux
andauthored
feat: Chatbot UI integration with Langchain AI example (bnb-chain#69)
* added new example of chatbot with ui * chore: Update dependencies and improve README instructions for environment variables * updated the requirements (remove duplicates) and updated readme with more information * added screenshot of the ui to the readme --------- Co-authored-by: robot-ux <[email protected]>
1 parent 1e073b1 commit 3cd6b1e

File tree

10 files changed

+2644
-0
lines changed

10 files changed

+2644
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
BSC_PROVIDER_URL=https://bsc-dataseed.bnbchain.org
2+
OPBNB_PROVIDER_URL=https://opbnb-mainnet-rpc.bnbchain.org
3+
PRIVATE_KEY=
4+
OPENAI_API_KEY=
5+
# Optional
6+
BSCSCAN_API_KEY

python/chatbot-with-ui/.gitignore

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Python virtual environment
2+
.venv/
3+
venv/
4+
ENV/
5+
6+
# Python bytecode
7+
__pycache__/
8+
*.py[cod]
9+
*$py.class
10+
11+
# Distribution / packaging
12+
dist/
13+
build/
14+
*.egg-info/
15+
16+
# Environment variables
17+
.env
18+
.env.local
19+
.env.*.local
20+
21+
# IDE specific files
22+
.idea/
23+
.vscode/
24+
*.swp
25+
*.swo
26+
.DS_Store
27+
28+
# Logs
29+
*.log
30+
logs/
31+
32+
# Local development settings
33+
local_settings.py
34+
35+
# Coverage reports
36+
htmlcov/
37+
.tox/
38+
.coverage
39+
.coverage.*
40+
.cache
41+
coverage.xml
42+
*.cover
43+
44+
# Jupyter Notebook
45+
.ipynb_checkpoints
46+
47+
# pyenv
48+
.python-version
49+
50+
# mypy
51+
.mypy_cache/
52+
.dmypy.json
53+
dmypy.json
54+
55+
# pytest
56+
.pytest_cache/
57+
58+
# uv
59+
.uv/

python/chatbot-with-ui/README.md

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
# BNB Chain Chatbot with UI
2+
3+
This project demonstrates how to create a web interface for the BNB Chain Example Hub's Python chatbot, showcasing how to integrate AI agents into decentralized applications (dApps) through API wrappers.
4+
5+
## Overview
6+
7+
This project combines:
8+
9+
- The powerful Python-based chatbot from [BNB Chain Example Hub](https://github.com/bnb-chain/example-hub)
10+
- A modern web interface
11+
- FastAPI for API wrapping and static file serving
12+
13+
The chatbot can assist with various BNB Chain operations provided by the agent kit, including:
14+
15+
- Bridging tokens between BSC and opBNB
16+
- Contract deployment
17+
- Faucet requests
18+
- Balance inquiries
19+
- Staking operations
20+
- Token swaps
21+
- Token transfers
22+
- Gas fee analysis
23+
- Transaction details and history
24+
- Market information
25+
26+
![Screenshot of UI](./ui_screenshot.png)
27+
28+
## Prerequisites
29+
30+
- Python 3.12+
31+
- Uv for package management and tooling
32+
- [Uv installation instructions](https://docs.astral.sh/uv/getting-started/installation/)
33+
- [OpenAI API Key](https://platform.openai.com/docs/quickstart#create-and-export-an-api-key)
34+
35+
36+
## Setup
37+
38+
1. Clone the repository:
39+
40+
```bash
41+
git clone <your-repo-url>
42+
cd chatbot-with-ui
43+
```
44+
45+
2. Create and activate a virtual environment using uv:
46+
47+
**For macOS/Linux:**
48+
49+
```bash
50+
uv venv
51+
source .venv/bin/activate # For bash/zsh
52+
```
53+
54+
**For Windows:**
55+
56+
```batch
57+
uv venv
58+
.venv\Scripts\activate.bat
59+
```
60+
61+
3. Install dependencies:
62+
63+
```bash
64+
uv sync
65+
```
66+
67+
4. Set up environment variables:
68+
Create a `.env` file in the root directory and copy over the contents of `.env.example`:
69+
70+
```env
71+
# Required
72+
PRIVATE_KEY=your_private_key_here
73+
OPENAI_API_KEY=your_openai_api_key_here
74+
75+
# Optional
76+
BSCSCAN_API_KEY=your_bscscan_api_key_here
77+
```
78+
79+
You can get these values from:
80+
81+
- Private Key: Your BNB Chain wallet's private key
82+
- OpenAI API Key: [OpenAI Platform](https://platform.openai.com/api-keys)
83+
- BSCScan API Key: [BSCScan API Portal](https://bscscan.com/apidashboard)
84+
85+
Purpose:
86+
87+
- Private Key: To utilise BNB Agent Kit
88+
- OpenAI API Key: To utilise openAI API for chatbot
89+
- BSCScan API Key: To access BSCScan data
90+
91+
## Running the Application
92+
93+
1. Activate the virtual environment (if not already activated):
94+
95+
**For macOS/Linux:**
96+
97+
```bash
98+
source .venv/bin/activate
99+
```
100+
101+
**For Windows:**
102+
103+
```batch
104+
.venv\Scripts\activate.bat
105+
```
106+
107+
2. Start the FastAPI server:
108+
109+
```bash
110+
uv run uvicorn api-wrapper:app --reload
111+
```
112+
113+
3. Open your browser and navigate to (default port:8000):
114+
```
115+
http://localhost:8000
116+
```
117+
118+
The application will serve both the API endpoints and the web interface from the same server.
119+
120+
## Project Structure
121+
122+
```
123+
newchatbot/
124+
├── api-wrapper.py # FastAPI backend and API wrapper
125+
├── chatbot.py # Core chatbot logic (from BNB Chain Example Hub)
126+
├── frontend/
127+
│ ├── index.html # Main HTML file
128+
│ └── app.js # React application
129+
├── pyproject.toml # Project configuration
130+
├── .env # Environment keys and variables
131+
└── README.md # This file
132+
133+
```
134+
135+
## API Usage
136+
137+
The chatbot exposes a single endpoint:
138+
139+
```http
140+
POST /api/chat
141+
Content-Type: application/json
142+
143+
{
144+
"message": "Your message here"
145+
}
146+
```
147+
148+
Response:
149+
150+
```json
151+
{
152+
"reply": "Chatbot's response"
153+
}
154+
```
155+
156+
## Integration with dApps
157+
158+
To integrate this chatbot into your dApp:
159+
160+
1. **API Integration**:
161+
162+
- Use the `/api/chat` endpoint in your application
163+
- Handle the responses in your frontend code
164+
165+
2. **Custom Frontend**:
166+
167+
- The current implementation uses React, but you can use any frontend framework
168+
- The API is framework-agnostic
169+
170+
3. **Extending Functionality**:
171+
- Add new endpoints in `api-wrapper.py`
172+
- Modify the chatbot logic in `chatbot.py`
173+
- Customize the UI in the `frontend` directory
174+
175+
## Features
176+
177+
### Modern User Interface
178+
179+
- Clean, responsive design with BNB Chain branding
180+
- Real-time chat interface with message history
181+
- Mobile-friendly layout
182+
183+
### Rich Text Support
184+
185+
- Markdown rendering for bot responses
186+
- Support for:
187+
- Headers (h1, h2, h3)
188+
- Lists (ordered and unordered)
189+
- Code blocks with syntax highlighting
190+
- Inline code
191+
- Blockquotes
192+
- Links
193+
- Tables
194+
195+
## Troubleshooting
196+
197+
### Common Issues
198+
199+
1. **Uv Installation Fails**
200+
201+
- Ensure you have Python 3.12+ installed
202+
- Try running the installation command with administrator privileges
203+
- Check the [official uv installation documentation](https://docs.astral.sh/uv/getting-started/installation/) for alternative installation methods
204+
205+
2. **Virtual Environment Issues**
206+
207+
- If activation fails, try creating a new terminal window
208+
- On Windows, ensure you're using the correct activation script for your shell
209+
210+
3. **Port Already in Use**
211+
- If port 8000 is already in use, you can specify a different port:
212+
```bash
213+
uv run uvicorn api-wrapper:app --reload --port 8001
214+
```
215+
216+
## Credits
217+
218+
This project is built upon the Python chatbot from the [BNB Chain Example Hub](https://github.com/bnb-chain/example-hub). The original chatbot provides the core functionality for interacting with the BNB Chain ecosystem.
219+
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from fastapi import FastAPI, Request
2+
from fastapi.staticfiles import StaticFiles
3+
from fastapi.middleware.cors import CORSMiddleware
4+
from pydantic import BaseModel
5+
import asyncio
6+
7+
from chatbot import initialize_agent
8+
9+
app = FastAPI()
10+
11+
# Add CORS middleware
12+
app.add_middleware(
13+
CORSMiddleware,
14+
allow_origins=["*"], # In production, replace with your frontend domain
15+
allow_credentials=True,
16+
allow_methods=["*"],
17+
allow_headers=["*"],
18+
)
19+
20+
21+
class ChatRequest(BaseModel):
22+
message: str
23+
24+
25+
agent_executor, config = initialize_agent()
26+
27+
28+
@app.post("/api/chat")
29+
async def chat_endpoint(chat_request: ChatRequest):
30+
user_message = chat_request.message
31+
32+
# Run agent for the input message and collect output
33+
responses = []
34+
async for event in agent_executor.astream(
35+
{"messages": [{"role": "user", "content": user_message}]},
36+
config,
37+
stream_mode="values",
38+
):
39+
# Assuming last message is agent response
40+
last_msg = event["messages"][-1].content
41+
responses.append(last_msg)
42+
43+
# Return concatenated or last response
44+
reply = responses[-1] if responses else "No response"
45+
return {"reply": reply}
46+
47+
48+
# Mount the frontend directory after defining all routes
49+
app.mount("/", StaticFiles(directory="frontend", html=True), name="frontend")

0 commit comments

Comments
 (0)