Skip to content

Commit e9e264d

Browse files
Merge pull request #10 from PinsaraPerera/dev
Dev
2 parents 852c914 + 4f80c4a commit e9e264d

12 files changed

Lines changed: 434 additions & 32 deletions

File tree

README.md

Lines changed: 297 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,297 @@
1-
# ai system
1+
# AI Legal & Cardano Blockchain Assistant System
2+
3+
A comprehensive AI-powered assistant system that combines legal expertise with Cardano blockchain integration. This system provides intelligent assistance for legal queries across multiple domains (Civil Law, Corporate Law, Property Law) and real-time Cardano blockchain data analysis.
4+
5+
## 🏗️ System Architecture
6+
7+
### Core Components
8+
9+
1. **FastAPI Backend** - RESTful API with security middleware and rate limiting
10+
2. **Multi-Agent System** - Specialized AI agents for different domains
11+
3. **Cardano Blockchain Integration** - Real-time data from Cardano network via BlockFrost API
12+
4. **Vector Database** - ChromaDB for semantic search and knowledge retrieval
13+
5. **Legal Knowledge Base** - Specialized legal document processing and search
14+
15+
### Agent Architecture
16+
17+
- **Cardano Agent**: Handles blockchain queries, transaction analysis, and address information
18+
- **Legal Assistant Agent**: Provides expertise in civil, corporate, and property law
19+
20+
## 🚀 Features
21+
22+
### Cardano Blockchain Capabilities
23+
- **Transaction Analysis**: Retrieve and analyze transaction details using transaction hashes
24+
- **Address Information**: Get comprehensive address data including balance and transaction history
25+
- **Transaction Flow Analysis**: Analyze asset flow between addresses with detailed input/output tracking
26+
- **Real-time Data**: Live connection to Cardano Preview Testnet via BlockFrost API
27+
- **CBOR Decoding**: Support for Cardano-specific data formats
28+
29+
### Legal Assistant Capabilities
30+
- **Multi-Domain Expertise**: Civil Law, Corporate Law, Property Law
31+
- **Document Search**: Semantic search across legal documents and precedents
32+
- **Context-Aware Responses**: Intelligent responses based on legal domain context
33+
- **Markdown Formatting**: Web-ready formatted responses
34+
35+
### API Security & Performance
36+
- **Authentication**: Custom security token middleware
37+
- **Rate Limiting**: Configurable request rate limiting
38+
- **CORS Support**: Cross-origin resource sharing for web applications
39+
- **Health Monitoring**: Health check endpoints for system monitoring
40+
41+
## 📁 Project Structure
42+
43+
```
44+
AI-system/
45+
├── app/
46+
│ ├── api/endpoints/ # API route definitions
47+
│ │ ├── query.py # Cardano blockchain queries
48+
│ │ ├── legal_query.py # Legal assistance queries
49+
│ │ └── training.py # Vector database setup
50+
│ ├── core/
51+
│ │ └── config.py # Environment configuration
52+
│ ├── crud/ # Business logic layer
53+
│ ├── schemas/ # Pydantic data models
54+
│ └── utils/ # Utility functions
55+
├── workflow/
56+
│ ├── agents/ # AI agent implementations
57+
│ │ ├── cardano_agent.py # Cardano blockchain agent
58+
│ │ └── legal_assistant.py # Legal domain agent
59+
│ └── tools/ # Agent tools and integrations
60+
│ ├── blockfrost_tool.py # Cardano blockchain tools
61+
│ ├── knowledge_base_tool.py # Knowledge search tools
62+
│ └── legal_data_tool.py # Legal document tools
63+
├── data/ # Raw document storage
64+
│ ├── cardano/ # Cardano documentation
65+
│ ├── civil_law/ # Civil law documents
66+
│ ├── corporate_law/ # Corporate law documents
67+
│ └── property_law/ # Property law documents
68+
├── db/ # Vector database storage
69+
└── test/ # Testing and development scripts
70+
```
71+
72+
## 🛠️ Installation & Setup
73+
74+
### Prerequisites
75+
- Python 3.10+
76+
- OpenAI API Key
77+
- BlockFrost API Key (Cardano)
78+
79+
### Installation
80+
81+
1. **Clone the repository**
82+
```bash
83+
git clone <repository-url>
84+
cd Cardano-AI-system
85+
```
86+
87+
2. **Install dependencies**
88+
```bash
89+
pip install -r requirements.txt
90+
```
91+
92+
3. **Environment Configuration**
93+
Create a `.env` file in the root directory:
94+
```env
95+
OPENAI_API_KEY=your_openai_api_key
96+
BLOCKFROST_PROJECT_ID=your_blockfrost_project_id
97+
BLOCKFROST_BASE_URL=https://cardano-preview.blockfrost.io/api/v0
98+
CHROMA_DB_PATH=./chroma_data
99+
```
100+
101+
4. **Setup Vector Databases**
102+
```bash
103+
# Start the FastAPI server
104+
uvicorn app.main:app --reload
105+
106+
# Setup all knowledge bases (one-time setup)
107+
curl -X GET "http://localhost:8000/training/setup_all_vector_dbs" \
108+
-H "Secret-token: unihack25"
109+
```
110+
111+
### Docker Deployment
112+
113+
```bash
114+
# Build the Docker image
115+
docker build -t ai-legal-cardano-system .
116+
117+
# Run the container
118+
docker run -p 8000:8000 --env-file .env ai-legal-cardano-system
119+
```
120+
121+
## 📚 API Documentation
122+
123+
### Authentication
124+
All API endpoints require a security token header:
125+
```
126+
Secret-token: unihack25
127+
```
128+
129+
### Core Endpoints
130+
131+
#### Cardano Blockchain Queries
132+
```http
133+
POST /query/
134+
Content-Type: application/json
135+
136+
{
137+
"thread_id": 1,
138+
"user_input": "What is the balance of addr_test1wryf65umuw5nuh8m4sjh9dka0mx7pwsmle0uyex8pf7f4ycj7y6tp?",
139+
"lang": "en"
140+
}
141+
```
142+
143+
#### Legal Assistance Queries
144+
```http
145+
POST /legalquery/
146+
Content-Type: application/json
147+
148+
{
149+
"thread_id": 1,
150+
"domain": "corporate_law",
151+
"user_input": "What are the requirements for company registration?",
152+
"lang": "en"
153+
}
154+
```
155+
156+
#### Vector Database Setup
157+
```http
158+
GET /training/setup_cardano_vector_db
159+
GET /training/setup_civil_law_vector_db
160+
GET /training/setup_corporate_law_vector_db
161+
GET /training/setup_property_law_vector_db
162+
GET /training/setup_all_vector_dbs
163+
```
164+
165+
### Available Tools
166+
167+
#### Cardano Tools
168+
- `get_address_details(address)` - Get comprehensive address information
169+
- `get_transactions_for_address(address)` - Retrieve transaction history
170+
- `get_single_transaction_details(tx_hash)` - Detailed transaction analysis
171+
- `search_cardano_knowledge(query)` - Search Cardano documentation
172+
173+
#### Legal Tools
174+
- `search_civil_law_knowledge(query)` - Civil law document search
175+
- `search_corporate_law_knowledge(query)` - Corporate law expertise
176+
- `search_legal_property_law_knowledge(query)` - Property law assistance
177+
178+
## 🔧 Usage Examples
179+
180+
### Cardano Blockchain Queries
181+
182+
**Transaction Analysis:**
183+
```
184+
"Analyze transaction 4bcba01d2c775b545c783bbd49a9443bb0ac071c743c86eeddd6a814852288e5"
185+
```
186+
187+
**Address Information:**
188+
```
189+
"What is the current balance and transaction history for addr_test1wryf65umuw5nuh8m4sjh9dka0mx7pwsmle0uyex8pf7f4ycj7y6tp?"
190+
```
191+
192+
**General Cardano Questions:**
193+
```
194+
"How does Cardano's proof-of-stake consensus work?"
195+
```
196+
197+
### Legal Assistance Queries
198+
199+
**Corporate Law:**
200+
```
201+
Domain: "corporate_law"
202+
Query: "What are the legal requirements for forming a corporation?"
203+
```
204+
205+
**Property Law:**
206+
```
207+
Domain: "property_law"
208+
Query: "What are the steps involved in property transfer?"
209+
```
210+
211+
**Civil Law:**
212+
```
213+
Domain: "civil_law"
214+
Query: "What constitutes a valid contract under civil law?"
215+
```
216+
217+
## 🧪 Development & Testing
218+
219+
### Running Tests
220+
```bash
221+
# Run the test script for Cardano integration
222+
python test/blockFrostApi.py
223+
224+
# Run the agent test
225+
python test/agent.py
226+
```
227+
228+
### Development Mode
229+
```bash
230+
# Start with auto-reload
231+
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
232+
```
233+
234+
### Adding New Legal Documents
235+
1. Place PDF documents in the appropriate `data/` subdirectory
236+
2. Run the corresponding vector database setup endpoint
237+
3. The system will automatically process and index the documents
238+
239+
## 🔐 Security Features
240+
241+
- **Token-based Authentication**: Custom middleware for API security
242+
- **Rate Limiting**: Configurable request throttling
243+
- **CORS Configuration**: Secure cross-origin request handling
244+
- **Input Validation**: Pydantic schema validation for all requests
245+
246+
## 🌐 Integration Capabilities
247+
248+
### Cardano Network
249+
- **BlockFrost API**: Production-ready Cardano data access
250+
- **Preview Testnet**: Safe testing environment
251+
- **Real-time Data**: Live blockchain information
252+
- **CBOR Support**: Native Cardano data format handling
253+
254+
### AI/ML Stack
255+
- **LangChain**: Advanced agent orchestration
256+
- **OpenAI GPT-4**: High-quality language understanding
257+
- **ChromaDB**: Efficient vector similarity search
258+
- **Embeddings**: Semantic document understanding
259+
260+
## 📊 Monitoring & Health
261+
262+
```http
263+
GET /health
264+
```
265+
266+
Returns system health status and availability.
267+
268+
## 🤝 Contributing
269+
270+
1. Fork the repository
271+
2. Create a feature branch
272+
3. Implement your changes
273+
4. Add appropriate tests
274+
5. Submit a pull request
275+
276+
## 📄 License
277+
278+
This project is licensed under the terms specified in the LICENSE file.
279+
280+
## 🚨 Important Notes
281+
282+
- **Testnet Usage**: Currently configured for Cardano Preview Testnet
283+
- **API Keys**: Ensure proper security for API keys in production
284+
- **Rate Limits**: Respect BlockFrost API rate limitations
285+
- **Legal Disclaimer**: This system provides informational assistance only, not legal advice
286+
287+
## 🆘 Support
288+
289+
For technical support or questions:
290+
1. Check the API documentation at `/docs` when the server is running
291+
2. Review the logs for debugging information
292+
3. Ensure all environment variables are properly configured
293+
4. Verify vector databases are properly initialized
294+
295+
---
296+
297+
**Built for UniHack 2025** - An intelligent assistant system combining legal expertise with blockchain technology.
296 KB
Binary file not shown.
-373 KB
Binary file not shown.

data/civil_law/civil_law.pdf

64.6 KB
Binary file not shown.

db/cardano/chroma.sqlite3

0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.

db/civil_law/chroma.sqlite3

444 KB
Binary file not shown.

db/corporate_law/chroma.sqlite3

0 Bytes
Binary file not shown.

db/property_law/chroma.sqlite3

0 Bytes
Binary file not shown.

test/blockFrostApi.py

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,44 +22,46 @@ def namespace_to_dict(ns):
2222
from langchain_core.tools import tool
2323

2424
@tool
25-
def get_transactions_for_address(address: str) -> str:
26-
"""
27-
Get transactions for a given Cardano address.
28-
25+
def get_transaction_details(tx_hash: str) -> dict:
26+
"""Get transaction details from Blockfrost API.
27+
Retrieves details of a specific transaction using its hash.
28+
example like hash, quantity, time, fees etc.
29+
2930
Args:
30-
address (str): The Cardano address to query.
31-
31+
tx_hash (str): The hash of the transaction to retrieve details for.
3232
Returns:
33-
str: A string representation of the transactions.
33+
dict: A dictionary containing the transaction details or an error message.
34+
3435
"""
3536
try:
36-
details = get_transaction_details(address)
37-
return details
37+
tx_details = get_transactions_details_with_format(tx_hash)
38+
return f"transaction details: {tx_details}"
3839
except ApiError as e:
39-
return f"Error fetching transactions: {e}"
40+
return {"error": f"Failed to fetch transaction details: {str(e)}"}
4041

41-
def get_transaction_details(address: str) -> str:
42-
output = ""
43-
42+
def get_transactions_details_with_format(tx_hash: str) -> dict:
43+
"""Get formatted transaction details from Blockfrost API."""
4444
try:
45-
transactions = api.address_transactions(address=address)
46-
transactions = namespace_to_dict(transactions)
45+
tx = api.transaction(tx_hash)
46+
tx_dict = namespace_to_dict(tx)
4747

48-
for tx in transactions:
49-
tx_hash = tx['tx_hash']
50-
timestamp = tx['block_time']
51-
readable_time = datetime.fromtimestamp(timestamp)
52-
output += f"Transaction Hash: {tx_hash}\n"
53-
output += f"Timestamp: {readable_time}\n"
54-
output += "-" * 50 + "\n"
55-
56-
return output if output else "No transactions found for this address."
48+
format_data = {
49+
"hash": tx_dict.get("hash"),
50+
"time": datetime.fromtimestamp(tx_dict.get("block_time")).isoformat(),
51+
"fee": tx_dict.get("fees"),
52+
"Change ADA amount": float(tx_dict.get("output_amount")[0].get("quantity"))/1000000
53+
}
54+
return format_data
5755
except ApiError as e:
58-
return f"Error fetching transactions: {e}"
56+
return {"error": f"Failed to fetch transaction details: {str(e)}"}
57+
58+
5959

6060
if __name__ == "__main__":
6161
# Example usage
6262
address = "addr_test1wryf65umuw5nuh8m4sjh9dka0mx7pwsmle0uyex8pf7f4ycj7y6tp"
63-
print(get_transactions_for_address(address))
63+
tx_hash = "bcb8a9e84bacb3606756ecd93ebdf31fca671849bd7fb6eddcea16fac69c68a3"
64+
print(get_transaction_details(tx_hash))
65+
6466

6567

0 commit comments

Comments
 (0)