-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathllms.txt
More file actions
2359 lines (1839 loc) · 67.2 KB
/
Copy pathllms.txt
File metadata and controls
2359 lines (1839 loc) · 67.2 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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# JAF (Juspay Agent Framework) - Python Implementation - Comprehensive Documentation
JAF is a purely functional agent framework with immutable state and composable tools, professionally converted from TypeScript to Python. It enables building production-ready AI agent systems with built-in security, observability, and error handling.
## Project Overview
- **Framework Type**: Functional AI agent framework with immutable state
- **Language**: Python 3.10+ (Python 3.11+ recommended for optimal performance)
- **Architecture**: Immutable state machine, pure functions, composable tools
- **License**: MIT
- **Version**: 2.2.4
- **Repository**: https://github.com/xynehq/jaf-py
- **Documentation**: https://xynehq.github.io/jaf-py/
## Core Philosophy and Architecture
### Functional Programming at the Core
JAF treats agent execution as a pure function: given an initial state and configuration, it produces a deterministic result. This approach brings several benefits:
- **Predictability**: Same inputs always produce the same outputs
- **Testability**: Easy to test individual components in isolation
- **Debuggability**: State transitions are explicit and traceable
- **Scalability**: Stateless design enables horizontal scaling
### Immutability First
All core data structures in JAF are immutable. When state changes, new objects are created rather than modifying existing ones:
```python
# Mutable approach (not JAF)
state.messages.append(new_message) # Modifies existing state
# Immutable approach (JAF way)
new_state = replace(state, messages=[*state.messages, new_message])
```
This ensures:
- **Thread Safety**: Multiple agents can safely share state
- **Time Travel**: Previous states remain accessible for debugging
- **Reproducibility**: Exact state at any point can be recreated
## Core Types and Components
### 1. RunState - The Heart of JAF
`RunState` represents the complete state of an agent execution at any point in time:
```python
@dataclass(frozen=True)
class RunState(Generic[Ctx]):
"""Immutable state of an agent run."""
run_id: RunId # Unique identifier for this run
trace_id: TraceId # Trace identifier for observability
messages: List[Message] # Conversation history
current_agent_name: str # Currently active agent
context: Ctx # User-defined context data
turn_count: int # Number of turns taken
final_response: Optional[str] = None # Final agent response
```
**Key Properties:**
- **Frozen**: Cannot be modified after creation
- **Generic**: Type-safe context with `Ctx` type parameter
- **Complete**: Contains all information needed to reproduce the run
**State Transitions:**
```python
# Every operation creates a new state
from dataclasses import replace
async def add_message(state: RunState[Ctx], message: Message) -> RunState[Ctx]:
return replace(state,
messages=[*state.messages, message],
turn_count=state.turn_count + 1
)
```
### 2. Agent - Behavior Definition
Agents define how to respond to messages and what tools are available:
```python
@dataclass(frozen=True)
class Agent(Generic[Ctx]):
"""Agent definition with instructions and capabilities."""
name: str
instructions: Callable[[RunState[Ctx]], str] # Dynamic instructions
tools: List[Tool[Ctx]] = field(default_factory=list)
handoffs: Optional[List[str]] = None # Allowed handoff targets
output_codec: Optional[type] = None # Expected output codec
```
**Dynamic Instructions:**
Instructions are functions that receive the current state, enabling context-aware behavior:
```python
def math_tutor_instructions(state: RunState[StudentContext]) -> str:
problem_count = len([m for m in state.messages if 'calculate' in m.content])
base = "You are a patient math tutor."
if problem_count > 3:
return base + " The student has solved several problems. Offer encouragement!"
elif state.context.difficulty_level == "beginner":
return base + " Use simple explanations and encourage step-by-step thinking."
else:
return base + " Challenge the student with follow-up questions."
```
### 3. Tool System - Executable Capabilities
JAF provides multiple ways to create tools, with the modern `@function_tool` decorator being the recommended approach:
#### Modern Tool Creation with @function_tool
```python
from jaf import function_tool
@function_tool
async def calculate(expression: str, context=None) -> str:
"""Safely evaluate mathematical expressions.
Args:
expression: Mathematical expression to evaluate (e.g., '2 + 2', '10 * 5')
"""
# Input validation
if not expression or len(expression.strip()) == 0:
return "Error: Expression cannot be empty"
# Security: Only allow safe mathematical characters
allowed_chars = set('0123456789+-*/(). ')
if not all(c in allowed_chars for c in expression):
return "Error: Expression contains invalid characters"
try:
# Safe evaluation using eval (in production, use a proper math parser)
result = eval(expression)
return f"Result: {expression} = {result}"
except Exception as e:
return f"Error: Failed to evaluate expression: {str(e)}"
```
#### Tool Timeouts
JAF provides comprehensive timeout support to prevent tools from running indefinitely:
```python
# Tool with specific timeout (10 seconds)
@function_tool(timeout=10.0)
async def quick_operation(data: str, context=None) -> str:
"""Fast operation that should complete within 10 seconds."""
return f"Processed: {data}"
# Tool with longer timeout for heavy operations
@function_tool(timeout=300.0) # 5 minutes
async def heavy_computation(dataset: str, context=None) -> str:
"""Heavy computation that may take up to 5 minutes."""
return f"Computed: {dataset}"
```
#### Tool Parameter Definition with Pydantic
JAF uses Pydantic models to define tool parameters, providing automatic validation and type safety:
```python
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Union
from enum import Enum
class Color(str, Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
class AdvancedToolArgs(BaseModel):
# Required string parameter
text: str = Field(description="Text to process")
# Optional parameters with defaults
count: int = Field(default=1, description="Number of times to repeat")
enabled: bool = Field(default=True, description="Whether to enable processing")
# Constrained parameters
rating: int = Field(ge=1, le=10, description="Rating from 1 to 10")
email: str = Field(pattern=r'^[^@]+@[^@]+\\.[^@]+$', description="Valid email address")
# Collections
tags: List[str] = Field(default=[], description="List of tags")
metadata: Dict[str, Any] = Field(default={}, description="Additional metadata")
# Enums
color: Color = Field(default=Color.BLUE, description="Color choice")
# Union types
value: Union[str, int] = Field(description="String or integer value")
# Optional fields
optional_field: Optional[str] = Field(None, description="Optional parameter")
```
### 4. RunConfig - Execution Parameters
Configuration object that controls how agents execute:
```python
@dataclass
class RunConfig(Generic[Ctx]):
"""Configuration for agent execution."""
agent_registry: Dict[str, Agent[Ctx]] # Available agents
model_provider: ModelProvider # LLM integration
memory_provider: Optional[MemoryProvider] = None # Conversation storage
max_turns: int = 100 # Safety limit
on_event: Optional[Callable[[TraceEvent], None]] = None # Observability
initial_input_guardrails: List[Guardrail] = field(default_factory=list)
final_output_guardrails: List[Guardrail] = field(default_factory=list)
default_tool_timeout: Optional[float] = None # Default timeout for tools
```
## The Execution Flow
### Pure Function at the Core
The main `run` function is a pure function that transforms state:
```python
async def run(
initial_state: RunState[Ctx],
config: RunConfig[Ctx]
) -> RunResult[Out]:
"""
Pure function: RunState + RunConfig → RunResult
No side effects in core logic - all effects happen in providers.
"""
```
### Step-by-Step Execution
1. **Initialization**: Validate state and configuration
2. **Guard Rails**: Apply input validation policies
3. **Agent Selection**: Get current agent from registry
4. **Instruction Generation**: Call agent's instruction function with current state
5. **LLM Call**: Send messages and instructions to model provider
6. **Response Processing**: Parse LLM response for tool calls or final answer
7. **Tool Execution**: If tool calls present, execute them with context
8. **State Update**: Create new state with response and tool results
9. **Loop Check**: If not complete and under turn limit, continue
10. **Final Guards**: Apply output validation policies
11. **Memory Storage**: Persist conversation if memory provider configured
### Error Handling
JAF uses a Result-style approach for error handling:
```python
@dataclass(frozen=True)
class RunResult(Generic[Out]):
"""Result of an agent run."""
final_state: RunState
outcome: Union[CompletedOutcome[Out], ErrorOutcome]
# Usage
result = await run(state, config)
if result.outcome.status == 'completed':
print(f"Success: {result.outcome.output}")
else:
print(f"Error: {result.outcome.error}")
```
## Model Provider Integration
### LiteLLM Provider
JAF integrates with 100+ LLM models through LiteLLM, providing a unified interface:
```python
from jaf import make_litellm_provider
# Connect to LiteLLM proxy for 100+ model support
model_provider = make_litellm_provider(
'http://localhost:4000', # LiteLLM proxy URL
'your-api-key' # Optional API key
)
# OpenAI API
provider = make_litellm_provider(
"https://api.openai.com/v1",
api_key="your-openai-api-key"
)
# Custom LiteLLM deployment
provider = make_litellm_provider(
"https://your-litellm-server.com/v1",
api_key="your-api-key"
)
```
### LiteLLM Proxy Setup
#### Development Configuration
```bash
# Install LiteLLM with proxy support
pip install litellm[proxy]
# Create development configuration
cat > litellm_config.yaml << EOF
model_list:
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_key: ${OPENAI_API_KEY}
max_tokens: 4096
temperature: 0.1
- model_name: claude-3-sonnet
litellm_params:
model: anthropic/claude-3-sonnet-20240229
api_key: ${ANTHROPIC_API_KEY}
max_tokens: 4096
temperature: 0.1
- model_name: gemini-pro
litellm_params:
model: google/gemini-pro
api_key: ${GOOGLE_API_KEY}
general_settings:
master_key: "your-proxy-master-key"
database_url: "sqlite:///litellm_proxy.db"
router_settings:
routing_strategy: "least-busy"
model_group_alias:
"gpt-4": ["gpt-4o", "gpt-4-turbo"]
"claude": ["claude-3-sonnet", "claude-3-haiku"]
EOF
# Start LiteLLM proxy with enhanced configuration
litellm --config litellm_config.yaml --port 4000 --num_workers 4
```
## Memory System
JAF provides a robust conversation memory system that enables persistent conversations across sessions.
### Core Concepts
#### ConversationMemory
The `ConversationMemory` dataclass represents a complete conversation:
```python
from jaf.memory import ConversationMemory
from jaf.core.types import Message
# Immutable conversation object
conversation = ConversationMemory(
conversation_id="user-123-session-1",
user_id="user-123",
messages=[
Message(role="user", content="Hello!"),
Message(role="assistant", content="Hi there! How can I help you?")
],
metadata={"session_start": "2024-01-15T10:00:00Z"}
)
```
#### MemoryProvider Protocol
All memory providers implement the `MemoryProvider` protocol:
```python
from jaf.memory import MemoryProvider, MemoryQuery, ConversationMemory
from typing import List, Optional, Dict, Any
class MyCustomProvider:
async def store_messages(
self,
conversation_id: str,
messages: List[Message],
metadata: Optional[Dict[str, Any]] = None
) -> Result:
"""Store messages for a conversation."""
async def get_conversation(self, conversation_id: str) -> Optional[ConversationMemory]:
"""Retrieve complete conversation history."""
async def append_messages(
self,
conversation_id: str,
messages: List[Message],
metadata: Optional[Dict[str, Any]] = None
) -> Result:
"""Add new messages to existing conversation."""
async def get_recent_messages(
self,
conversation_id: str,
limit: int = 50
) -> List[Message]:
"""Get recent messages from conversation."""
async def delete_conversation(self, conversation_id: str) -> bool:
"""Delete conversation and return success status."""
async def health_check(self) -> Dict[str, Any]:
"""Check provider health and connectivity."""
```
### Available Providers
#### In-Memory Provider
Perfect for development and testing. Conversations are lost when the application restarts.
```python
from jaf.memory import create_in_memory_provider, InMemoryConfig
# Create provider with configuration
config = InMemoryConfig(
max_conversations=1000, # Maximum conversations to store
max_messages=1000 # Maximum messages per conversation
)
provider = create_in_memory_provider(config)
```
**Environment Variables:**
```bash
JAF_MEMORY_TYPE=memory
JAF_MEMORY_MAX_CONVERSATIONS=1000
JAF_MEMORY_MAX_MESSAGES=1000
```
#### Redis Provider
High-performance, in-memory storage with optional persistence.
```python
from jaf.memory import create_redis_provider, RedisConfig
import redis.asyncio as redis
# Method 1: Create with config and client
redis_client = redis.Redis(host="localhost", port=6379, db=0)
config = RedisConfig(
host="localhost",
port=6379,
db=0,
key_prefix="jaf:memory:",
ttl=86400 # 24 hours
)
provider = await create_redis_provider(config, redis_client)
# Method 2: Create from URL
config = RedisConfig(url="redis://localhost:6379/0")
provider = await create_redis_provider(config)
```
**Environment Variables:**
```bash
JAF_MEMORY_TYPE=redis
# Option 1: Full URL
JAF_REDIS_URL=redis://localhost:6379/0
# Option 2: Individual parameters
JAF_REDIS_HOST=localhost
JAF_REDIS_PORT=6379
JAF_REDIS_PASSWORD=your-password
JAF_REDIS_DB=0
JAF_REDIS_KEY_PREFIX=jaf:memory:
JAF_REDIS_TTL=86400
```
#### PostgreSQL Provider
Robust, ACID-compliant relational database storage.
```python
from jaf.memory import create_postgres_provider, PostgresConfig
import asyncpg
# Method 1: Create with config and connection
connection = await asyncpg.connect("postgresql://user:pass@localhost/jaf_memory")
config = PostgresConfig(
host="localhost",
port=5432,
database="jaf_memory",
username="postgres",
password="your-password",
table_name="conversations"
)
provider = await create_postgres_provider(config, connection)
# Method 2: Create from connection string
config = PostgresConfig(
connection_string="postgresql://user:pass@localhost/jaf_memory"
)
provider = await create_postgres_provider(config)
```
**Environment Variables:**
```bash
JAF_MEMORY_TYPE=postgres
# Option 1: Connection string
JAF_POSTGRES_CONNECTION_STRING=postgresql://user:pass@localhost/jaf_memory
# Option 2: Individual parameters
JAF_POSTGRES_HOST=localhost
JAF_POSTGRES_PORT=5432
JAF_POSTGRES_DATABASE=jaf_memory
JAF_POSTGRES_USERNAME=postgres
JAF_POSTGRES_PASSWORD=your-password
JAF_POSTGRES_SSL=false
JAF_POSTGRES_TABLE_NAME=conversations
JAF_POSTGRES_MAX_CONNECTIONS=10
```
### Environment-Based Configuration
JAF provides automatic provider creation from environment variables:
```python
from jaf.memory import create_memory_provider_from_env, MemoryConfig
# Create provider based on JAF_MEMORY_TYPE
provider = await create_memory_provider_from_env()
# Create memory config for engine
memory_config = MemoryConfig(
provider=provider,
auto_store=True, # Automatically store conversations
max_messages=1000, # Limit messages per conversation
ttl=86400 # Time to live in seconds
)
```
## Observability and Tracing
JAF provides comprehensive observability through its advanced tracing system with support for multiple backends.
### Basic Tracing
Simple event-based tracing for development:
```python
def trace_handler(event: TraceEvent) -> None:
"""Handle trace events for monitoring."""
if event.type == "llm_call_start":
print(f"LLM call: {event.data['model']}")
elif event.type == "tool_call_start":
print(f"Tool call: {event.data['tool_name']}")
elif event.type == "error":
print(f"Error: {event.data['error_type']}")
config = RunConfig(
# ...
on_event=trace_handler
)
```
### Production-Ready Tracing
JAF supports multiple trace collectors for comprehensive observability:
```python
from jaf.core.tracing import (
ConsoleTraceCollector,
LangfuseTraceCollector,
OtelTraceCollector,
FileTraceCollector,
create_composite_trace_collector
)
# Console tracing for development
console_collector = ConsoleTraceCollector()
# File-based tracing for debugging
file_collector = FileTraceCollector("traces/agent_traces.jsonl")
# Composite collector with multiple backends
trace_collector = create_composite_trace_collector(
console_collector,
file_collector
# OpenTelemetry and Langfuse auto-added based on environment variables
)
config = RunConfig(
agent_registry=agents,
model_provider=model_provider,
on_event=trace_collector.collect
)
```
### Auto-Configuration
JAF automatically enables tracing backends based on environment variables:
```bash
# Enable OpenTelemetry tracing
export TRACE_COLLECTOR_URL=http://localhost:4318/v1/traces
# Enable Langfuse tracing
export LANGFUSE_PUBLIC_KEY=pk-lf-your-public-key
export LANGFUSE_SECRET_KEY=sk-lf-your-secret-key
export LANGFUSE_HOST=https://cloud.langfuse.com
```
```python
# Auto-configured tracing includes all available backends
trace_collector = create_composite_trace_collector()
```
### Trace Events
JAF emits detailed trace events throughout execution:
- `run_start` / `run_end` - Agent run lifecycle
- `llm_call_start` / `llm_call_end` - LLM interactions with timing and usage
- `tool_call_start` / `tool_call_end` - Tool executions
- `handoff` - Agent transitions
- `error` - Error conditions and failures
Events provide insights into:
- **Agent execution flow** and decision patterns
- **Tool usage patterns** and performance
- **LLM call patterns** with token usage and costs
- **Performance metrics** and bottlenecks
- **Error conditions** and failure modes
- **State transitions** and data flow
## Agent-as-Tool Pattern
JAF enables sophisticated hierarchical agent architectures where specialized agents can be used as tools by other agents:
```python
from jaf import Agent, ModelConfig
# Create specialized translation agents
spanish_agent = Agent(
name="spanish_translator",
instructions=lambda state: "Translate text to Spanish. Reply only with the translation.",
model_config=ModelConfig(name="gpt-4", temperature=0.3)
)
french_agent = Agent(
name="french_translator",
instructions=lambda state: "Translate text to French. Reply only with the translation.",
model_config=ModelConfig(name="gpt-4", temperature=0.3)
)
# Convert agents to tools with custom configuration
spanish_tool = spanish_agent.as_tool(
tool_name="translate_to_spanish",
tool_description="Translate any text to Spanish",
max_turns=3,
timeout=30.0
)
french_tool = french_agent.as_tool(
tool_name="translate_to_french",
tool_description="Translate any text to French",
max_turns=3,
is_enabled=lambda ctx, agent: "french" in ctx.target_languages
)
# Create orchestrator agent that uses other agents as tools
orchestrator = Agent(
name="translation_coordinator",
instructions=lambda state: (
"You coordinate translations using your specialized translation tools. "
"Always use the appropriate tools for the requested languages."
),
tools=[spanish_tool, french_tool],
model_config=ModelConfig(name="gpt-4", temperature=0.1)
)
```
**Key Benefits of Agent-as-Tool Pattern:**
- **Modular Expertise**: Delegate specialized tasks to expert agents
- **Hierarchical Reasoning**: Create supervisor-worker agent patterns
- **Conditional Execution**: Enable/disable agent tools based on context
- **Session Management**: Control memory sharing between parent and child agents
- **Reusable Components**: Build complex systems from composable agent components
## Validation and Security
### Input/Output Guardrails
```python
from jaf.policies.validation import create_length_guardrail, create_content_filter
# Create length validation
length_guard = create_length_guardrail(max_length=1000, min_length=10)
# Create content filtering
content_filter = create_content_filter(['spam', 'inappropriate'])
config = RunConfig(
# ... other config
initial_input_guardrails=[length_guard, content_filter]
)
```
### JSON Validation
```python
from jaf.policies.validation import create_json_validation_guardrail
from pydantic import BaseModel
class OrderOutput(BaseModel):
order_id: str
total: float
items: List[str]
json_validator = create_json_validation_guardrail(OrderOutput)
config = RunConfig(
# ... other config
final_output_guardrails=[json_validator]
)
```
### Handoff Policies
```python
from jaf.policies.handoff import create_role_based_handoff_policy
# Define roles
agent_roles = {
"TriageAgent": "triage",
"TechnicalAgent": "technical",
"BillingAgent": "billing"
}
# Define permissions (which roles can handoff to which)
role_permissions = {
"triage": ["technical", "billing"],
"technical": ["triage"],
"billing": ["triage"]
}
handoff_policy = create_role_based_handoff_policy(agent_roles, role_permissions)
```
## Server Implementation
### FastAPI Server
JAF includes a built-in FastAPI server for exposing agents via HTTP:
```python
from jaf.server import run_server
from jaf.providers.model import make_litellm_provider
def create_my_agent():
def instructions(state):
return 'You are a helpful assistant'
return Agent(
name='MyAgent',
instructions=instructions,
tools=[calculator_tool, greeting_tool]
)
model_provider = make_litellm_provider('http://localhost:4000')
# Start server on port 3000
await run_server(
[create_my_agent()],
{'model_provider': model_provider},
{'port': 3000}
)
```
Server provides RESTful endpoints:
- `GET /health` - Health check
- `GET /agents` - List available agents
- `POST /chat` - General chat endpoint
- `POST /agents/{name}/chat` - Agent-specific endpoint
- `GET /docs` - Interactive API documentation
## Advanced Features
### Performance Monitoring
JAF provides comprehensive performance monitoring with metrics collection:
```python
from jaf.core.performance import PerformanceMonitor, monitor_performance
# Create performance monitor
monitor = PerformanceMonitor()
# Monitor agent performance
@monitor_performance(monitor)
async def my_agent_function():
# Agent logic here
pass
# Get performance summary
summary = monitor.get_performance_summary()
print(f"Average response time: {summary.avg_response_time}ms")
print(f"Total requests: {summary.total_requests}")
```
### Workflow Orchestration
Create complex multi-step workflows:
```python
from jaf.core.workflows import (
create_workflow,
AgentStep,
ToolStep,
ConditionalStep,
execute_workflow_stream
)
# Define workflow steps
steps = [
AgentStep(agent_name="DataValidator", input_key="raw_data"),
ConditionalStep(
condition=lambda ctx: ctx.validation_passed,
if_true=ToolStep(tool_name="process_data"),
if_false=AgentStep(agent_name="ErrorHandler")
),
AgentStep(agent_name="Summarizer", input_key="processed_data")
]
# Create and execute workflow
workflow = create_workflow("DataProcessingWorkflow", steps)
async for result in execute_workflow_stream(workflow, initial_data):
print(f"Step completed: {result.step_name}")
```
### Plugin System
Extend JAF with custom plugins:
```python
from jaf.plugins import JAFPlugin, PluginMetadata, get_plugin_registry
class MyCustomPlugin(JAFPlugin):
metadata = PluginMetadata(
name="custom_plugin",
version="1.0.0",
description="My custom JAF plugin"
)
async def initialize(self):
# Plugin initialization logic
pass
async def on_agent_start(self, agent_name: str, context: Any):
# Hook into agent lifecycle
pass
# Register and use plugin
registry = get_plugin_registry()
await registry.register_plugin(MyCustomPlugin())
```
### Analytics System
Built-in analytics for conversation quality and agent performance:
```python
from jaf.core.analytics import (
AnalyticsEngine,
analyze_conversation_quality,
get_analytics_report
)
# Analyze conversation quality
quality_score = await analyze_conversation_quality(conversation_messages)
print(f"Conversation quality: {quality_score.overall_score}")
# Get comprehensive analytics report
report = await get_analytics_report(time_period="last_7_days")
print(f"Total conversations: {report.total_conversations}")
print(f"Average satisfaction: {report.avg_satisfaction}")
```
## Installation and Setup
### Production Installation
```bash
# Complete installation with all features
pip install "jaf-py[all] @ git+https://github.com/xynehq/jaf-py.git"
# Verify installation
python -c "import jaf; print('JAF installed successfully')"
```
### Feature-Specific Installation
```bash
# Core framework only
pip install git+https://github.com/xynehq/jaf-py.git
# Server capabilities (FastAPI, uvicorn)
pip install "jaf-py[server] @ git+https://github.com/xynehq/jaf-py.git"
# Memory providers (Redis, PostgreSQL)
pip install "jaf-py[memory] @ git+https://github.com/xynehq/jaf-py.git"
# Visualization tools (Graphviz, diagrams)
pip install "jaf-py[visualization] @ git+https://github.com/xynehq/jaf-py.git"
# Tracing and observability (OpenTelemetry, Langfuse)
pip install "jaf-py[tracing] @ git+https://github.com/xynehq/jaf-py.git"
# Development tools (testing, linting, type checking)
pip install "jaf-py[dev] @ git+https://github.com/xynehq/jaf-py.git"
```
### Development Environment Setup
```bash
# Clone the repository
git clone https://github.com/xynehq/jaf-py.git
cd jaf-py
# Make virtual environment
python -m venv .venv
source .venv/bin/activate
# Install in development mode with all dependencies
pip install -e ".[dev,server,memory,visualization,tracing]"
# Verify development setup
python -m pytest tests/ --tb=short
```
## Environment Configuration
### Development Environment
Create a `.env` file for local development:
```bash
# LiteLLM Provider Configuration (Required)
LITELLM_URL=http://localhost:4000/
LITELLM_API_KEY=your-litellm-api-key
LITELLM_MODEL=gpt-4
PORT=3000
HOST=127.0.0.1
DEMO_MODE=development
VERBOSE_LOGGING=true
# Model Provider API Keys
OPENAI_API_KEY=your-openai-api-key
ANTHROPIC_API_KEY=your-anthropic-api-key
GOOGLE_API_KEY=your-google-api-key
# Memory Provider Configuration
JAF_MEMORY_TYPE=memory # Options: memory, redis, postgres
# Redis Provider Configuration
JAF_REDIS_HOST=localhost
JAF_REDIS_PORT=6379
JAF_REDIS_PASSWORD=your-redis-password
JAF_REDIS_DB=0
JAF_REDIS_PREFIX=JAF:memory:
JAF_REDIS_TTL=86400
# PostgreSQL Provider Configuration
JAF_POSTGRES_HOST=localhost
JAF_POSTGRES_PORT=5432
JAF_POSTGRES_DB=jaf_test
JAF_POSTGRES_USER=postgres
JAF_POSTGRES_PASSWORD=your-postgres-password
JAF_POSTGRES_SSL=false
JAF_POSTGRES_TABLE=conversations
JAF_POSTGRES_MAX_CONNECTIONS=10
# Tracing Configuration
TRACE_COLLECTOR_URL=http://localhost:4318/v1/traces
LANGFUSE_PUBLIC_KEY=pk-lf-your-public-key
LANGFUSE_SECRET_KEY=sk-lf-your-secret-key
LANGFUSE_HOST=https://cloud.langfuse.com
```
### Production Environment
```bash
# LiteLLM Provider Configuration
LITELLM_URL=https://api.your-company.com/llm/
LITELLM_API_KEY=${LITELLM_MASTER_KEY}
LITELLM_MODEL=gpt-4o
PORT=8000
HOST=0.0.0.0
DEMO_MODE=production
VERBOSE_LOGGING=false
# Memory Provider (Production Redis)