-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlangextract_example.py
More file actions
275 lines (225 loc) Β· 8.55 KB
/
langextract_example.py
File metadata and controls
275 lines (225 loc) Β· 8.55 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
"""
Langextract Tool Example
This example demonstrates how to use the langextract tools for
interactive text visualization and analysis with PraisonAI agents.
Prerequisites:
pip install praisonai-tools[langextract]
# or
pip install praisonai-tools langextract
Features demonstrated:
- Text analysis with highlighted extractions
- File-based document analysis
- Integration with PraisonAI agents
- Interactive HTML generation
"""
import os
import tempfile
from pathlib import Path
from praisonai_tools import langextract_extract, langextract_render_file
def basic_text_analysis():
"""Demonstrate basic text analysis with highlighted extractions."""
print("π Basic Text Analysis with Langextract")
print("=" * 50)
# Sample contract text
contract_text = """
CONSULTING AGREEMENT
This Agreement is entered into on March 15, 2024, between TechCorp Inc.
(the "Client") and Jane Smith (the "Consultant"). The Consultant will
provide AI development services for a period of 6 months starting
April 1, 2024.
Payment terms: $5,000 per month, payable within 15 days of invoice date.
Confidentiality obligations remain in effect for 2 years after termination.
"""
# Key terms to highlight
key_terms = [
"TechCorp Inc.",
"Jane Smith",
"March 15, 2024",
"April 1, 2024",
"$5,000 per month",
"15 days",
"2 years",
"AI development services"
]
# Extract and visualize
result = langextract_extract(
text=contract_text,
extractions=key_terms,
document_id="consulting-agreement",
output_path="contract_analysis.html",
auto_open=False # Set to True to open in browser automatically
)
if result.get("success"):
print(f"β
Analysis complete!")
print(f" Document ID: {result['document_id']}")
print(f" Output file: {result['output_path']}")
print(f" Extractions: {result['extractions_count']} terms highlighted")
print(f" Text length: {result['text_length']} characters")
print()
print(f"π‘ Open {result['output_path']} in your browser to view the interactive visualization!")
else:
print(f"β Error: {result.get('error')}")
if "langextract not installed" in result.get("error", ""):
print("π‘ Install with: pip install langextract")
def file_analysis_example():
"""Demonstrate file-based document analysis."""
print("π File-based Document Analysis")
print("=" * 50)
# Create a sample document
document_content = """
TECHNICAL SPECIFICATION DOCUMENT
Project: AI-Powered Analytics Dashboard
Version: 2.1.0
Date: April 17, 2026
REQUIREMENTS:
- Python 3.10+ runtime environment
- PostgreSQL 14+ database
- Redis for caching layer
- Docker for containerization
- Kubernetes for orchestration
SECURITY CONSIDERATIONS:
- JWT authentication with 24-hour expiry
- Rate limiting: 1000 requests per hour per API key
- HTTPS-only communication
- Data encryption at rest using AES-256
PERFORMANCE TARGETS:
- API response time: < 200ms for 95th percentile
- Database query optimization required
- Concurrent user support: 10,000+ users
"""
# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write(document_content)
temp_file_path = f.name
try:
# Technical terms to highlight
tech_terms = [
"Python 3.10+",
"PostgreSQL 14+",
"Redis",
"Docker",
"Kubernetes",
"JWT authentication",
"24-hour expiry",
"1000 requests per hour",
"AES-256",
"< 200ms",
"10,000+ users"
]
# Analyze the file
result = langextract_render_file(
file_path=temp_file_path,
extractions=tech_terms,
output_path="tech_spec_analysis.html",
auto_open=False
)
if result.get("success"):
print(f"β
File analysis complete!")
print(f" Source file: {temp_file_path}")
print(f" Document ID: {result['document_id']}")
print(f" Output file: {result['output_path']}")
print(f" Extractions: {result['extractions_count']} terms highlighted")
print(f" Text length: {result['text_length']} characters")
print()
print(f"π‘ Open {result['output_path']} in your browser to view the interactive visualization!")
else:
print(f"β Error: {result.get('error')}")
finally:
# Clean up temporary file
try:
os.unlink(temp_file_path)
except OSError:
pass
def agent_integration_example():
"""Demonstrate integration with PraisonAI agents."""
print("π€ PraisonAI Agent Integration")
print("=" * 50)
# This is how you would integrate with agents
agent_code = '''
from praisonaiagents import Agent
from praisonai_tools import langextract_extract, langextract_render_file
# Create an agent that analyzes documents
document_analyzer = Agent(
name="DocumentAnalyzer",
instructions="""
You are a document analysis expert. When given text or documents,
identify key entities, dates, financial figures, and important terms.
Use langextract tools to create interactive visualizations highlighting
your findings.
""",
tools=[langextract_extract, langextract_render_file]
)
# Agent workflow example
def analyze_document(text_or_file_path):
"""Agent analyzes document and creates visualization."""
if text_or_file_path.endswith('.txt'):
# File-based analysis
response = document_analyzer.start(
f"Analyze this document file and highlight key terms: {text_or_file_path}"
)
else:
# Text-based analysis
response = document_analyzer.start(
f"Analyze this text and highlight important information: {text_or_file_path}"
)
return response
# Example usage:
# result = analyze_document("contract.txt")
# result = analyze_document("The quarterly report shows revenue of $1.2M...")
'''
print("π» Example agent integration code:")
print(agent_code)
print()
print("π§ Key integration points:")
print(" - Import tools: langextract_extract, langextract_render_file")
print(" - Add to agent tools list")
print(" - Agent can automatically use tools based on instructions")
print(" - Interactive HTML files created for human review")
def error_handling_example():
"""Demonstrate graceful error handling."""
print("β οΈ Error Handling and Graceful Degradation")
print("=" * 50)
# Test without langextract installed (simulated)
print("Testing graceful degradation when langextract is not installed:")
result = langextract_extract(
text="Sample text for analysis",
extractions=["Sample"],
document_id="test"
)
if "error" in result:
print(f"β
Graceful error handling: {result['error']}")
print("π‘ Users get clear installation instructions")
else:
print("β
Langextract is available and working!")
print()
print("Common error scenarios handled:")
print(" - β langextract not installed β Clear installation message")
print(" - β Invalid file path β File not found error")
print(" - β Empty text input β Parameter validation")
print(" - β Browser auto-open fails β Graceful fallback")
def main():
"""Run all examples."""
print("π Langextract Tool Examples for PraisonAI")
print("=" * 70)
print()
try:
basic_text_analysis()
print()
file_analysis_example()
print()
agent_integration_example()
print()
error_handling_example()
print()
print("π All examples completed!")
print()
print("π Next Steps:")
print(" 1. Install langextract: pip install langextract")
print(" 2. Run your own text analysis")
print(" 3. Integrate with your PraisonAI agents")
print(" 4. Open generated HTML files to see interactive visualizations")
except Exception as e:
print(f"β Example error: {e}")
print("π‘ This is expected if langextract is not installed")
if __name__ == "__main__":
main()