forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha2a.py
More file actions
1571 lines (1380 loc) · 70.1 KB
/
Copy patha2a.py
File metadata and controls
1571 lines (1380 loc) · 70.1 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
"""
A2A protocol conversions for LangChain integration.
This module provides functions to convert between LangChain agents and A2A servers/agents.
"""
import logging
import asyncio
import inspect
from typing import Any, Dict, List, Optional, Union, Callable, Type, Protocol, runtime_checkable
logger = logging.getLogger(__name__)
# Import custom exceptions
from .exceptions import (
LangChainNotInstalledError,
LangChainAgentConversionError,
A2AAgentConversionError
)
# Check for LangChain availability without failing
try:
# Try to import LangChain components
try:
from langchain_core.language_models import BaseLanguageModel
from langchain_core.tools import BaseTool
from langchain_core.runnables import Runnable
from langchain.agents import AgentExecutor
except ImportError:
# Fall back to older LangChain structure
from langchain.base_language import BaseLanguageModel
from langchain.tools import BaseTool
try:
from langchain.chains import Chain as Runnable
except ImportError:
class Runnable:
pass
try:
from langchain.agents import AgentExecutor
except ImportError:
class AgentExecutor:
pass
HAS_LANGCHAIN = True
except ImportError:
HAS_LANGCHAIN = False
# Create stub classes for type hints
class BaseLanguageModel:
pass
class BaseTool:
pass
class Runnable:
pass
class AgentExecutor:
pass
@runtime_checkable
class Invocable(Protocol):
"""Protocol for components with an invoke method."""
def invoke(self, inputs: Any, **kwargs) -> Any: ...
@runtime_checkable
class RunnableProtocol(Protocol):
"""Protocol for components with a run method."""
def run(self, inputs: Any, **kwargs) -> Any: ...
@runtime_checkable
class LLM(Protocol):
"""Protocol for language model components."""
def generate(self, prompts: List[str], **kwargs) -> Any: ...
def predict(self, text: str, **kwargs) -> str: ...
@runtime_checkable
class ChainLike(Protocol):
"""Protocol for chain-like components."""
@property
def input_keys(self) -> List[str]: ...
@property
def output_keys(self) -> List[str]: ...
def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]: ...
class ComponentAdapter:
"""Base adapter for LangChain components."""
def __init__(self, component: Any):
"""Initialize with a component."""
self.component = component
self.name = self._get_component_name()
def _get_component_name(self) -> str:
"""Get the name of the component."""
if hasattr(self.component, "name"):
return getattr(self.component, "name")
return type(self.component).__name__
def can_adapt(self) -> bool:
"""Check if this adapter can adapt the component."""
raise NotImplementedError("Subclasses must implement this method")
async def process_message(self, text: str) -> str:
"""Process a message with the component."""
raise NotImplementedError("Subclasses must implement this method")
async def process_stream(self, text: str):
"""
Process a message with streaming support.
Args:
text: The text message to process
Yields:
Chunks of the response as they arrive
By default, falls back to non-streaming processing.
Subclasses should override this if they can provide streaming.
"""
# Default implementation: fall back to non-streaming
result = await self.process_message(text)
yield result
class InvocableAdapter(ComponentAdapter):
"""Adapter for components with invoke method."""
def can_adapt(self) -> bool:
"""Check if component has invoke method."""
# Check for Invocable protocol or invoke attribute
has_invoke = isinstance(self.component, Invocable) or hasattr(self.component, "invoke")
# Check for LCEL/pipe operator components (modern LangChain)
is_pipe_component = hasattr(self.component, "__or__") and hasattr(self.component, "__ror__")
return has_invoke or is_pipe_component
async def process_message(self, text: str) -> str:
"""Process message using the invoke method."""
try:
# Prepare input format
input_data = self._prepare_input(text)
# Call invoke with appropriate method
result = await self._invoke(input_data)
# Process output format
return self._process_output(result)
except Exception as e:
logger.exception(f"Error invoking component '{self.name}'")
return f"Error: {str(e)}"
async def process_stream(self, text: str):
"""
Process message using streaming capabilities if available.
Args:
text: The text message to process
Yields:
Chunks of the response as they arrive
"""
# 1. Try modern streaming interfaces in priority order
# Check for stream_invoke method (newest LangChain interface)
if hasattr(self.component, "stream_invoke") and callable(self.component.stream_invoke):
try:
# Prepare input format
input_data = self._prepare_input(text)
# Check if stream_invoke is async
if asyncio.iscoroutinefunction(self.component.stream_invoke):
try:
# Try with prepared input
async for chunk in self.component.stream_invoke(input_data):
yield self._process_chunk(chunk)
return # Successfully used stream_invoke
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for chunk in self.component.stream_invoke({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used stream_invoke
else:
# Sync stream_invoke
try:
# Try with prepared input
for chunk in self.component.stream_invoke(input_data):
yield self._process_chunk(chunk)
return # Successfully used stream_invoke
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
for chunk in self.component.stream_invoke({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used stream_invoke
except Exception as e:
logger.warning(f"Error using stream_invoke for '{self.name}': {e}")
# Continue to next method
# Check for astream_invoke method (async streaming in newer LangChain)
if hasattr(self.component, "astream_invoke") and callable(self.component.astream_invoke):
try:
# Prepare input format
input_data = self._prepare_input(text)
try:
# Try with prepared input
async for chunk in self.component.astream_invoke(input_data):
yield self._process_chunk(chunk)
return # Successfully used astream_invoke
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for chunk in self.component.astream_invoke({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used astream_invoke
except Exception as e:
logger.warning(f"Error using astream_invoke for '{self.name}': {e}")
# Continue to next method
# 2. Try standard stream methods
if hasattr(self.component, "stream") and callable(self.component.stream):
try:
# Prepare input format
input_data = self._prepare_input(text)
# Check if stream is async
if asyncio.iscoroutinefunction(self.component.stream):
try:
# Try with prepared input
async for chunk in self.component.stream(input_data):
yield self._process_chunk(chunk)
return # Successfully used stream
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for chunk in self.component.stream({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used stream
else:
# Sync stream
try:
# Try with prepared input
for chunk in self.component.stream(input_data):
yield self._process_chunk(chunk)
return # Successfully used stream
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
for chunk in self.component.stream({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used stream
except Exception as e:
logger.warning(f"Error using stream for '{self.name}': {e}")
# Continue to next method
# Check for astream method (older LangChain async streaming)
if hasattr(self.component, "astream") and callable(self.component.astream):
try:
# Prepare input format
input_data = self._prepare_input(text)
try:
# Try with prepared input
async for chunk in self.component.astream(input_data):
yield self._process_chunk(chunk)
return # Successfully used astream
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for chunk in self.component.astream({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used astream
except Exception as e:
logger.warning(f"Error using astream for '{self.name}': {e}")
# Continue to next method
# 3. Check older or custom interfaces
if hasattr(self.component, "invoke_stream") and callable(self.component.invoke_stream):
try:
# Prepare input format
input_data = self._prepare_input(text)
# Check if invoke_stream is async
if asyncio.iscoroutinefunction(self.component.invoke_stream):
try:
# Try with prepared input
async for chunk in self.component.invoke_stream(input_data):
yield self._process_chunk(chunk)
return # Successfully used invoke_stream
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for chunk in self.component.invoke_stream({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used invoke_stream
else:
# Sync invoke_stream
try:
# Try with prepared input
for chunk in self.component.invoke_stream(input_data):
yield self._process_chunk(chunk)
return # Successfully used invoke_stream
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
for chunk in self.component.invoke_stream({"input": input_data}):
yield self._process_chunk(chunk)
return # Successfully used invoke_stream
except Exception as e:
logger.warning(f"Error using invoke_stream for '{self.name}': {e}")
# Continue to next method
# 4. Try event-based streaming methods
# Check for astream_events method (event-based streaming in newer LangChain)
if hasattr(self.component, "astream_events") and callable(self.component.astream_events):
try:
# Prepare input format
input_data = self._prepare_input(text)
try:
# Try with prepared input
async for event in self.component.astream_events(input_data):
# Extract useful content from events
if hasattr(event, "event"):
if event.event == "on_llm_new_token":
# Token event - extract text
if hasattr(event, "data") and hasattr(event.data, "token"):
yield event.data.token
elif hasattr(event, "token"):
yield event.token
elif event.event in ["on_chat_model_stream", "on_llm_stream"]:
# Chunk event - extract content
if hasattr(event, "data") and hasattr(event.data, "chunk"):
yield self._process_chunk(event.data.chunk)
elif hasattr(event, "chunk"):
yield self._process_chunk(event.chunk)
elif hasattr(event, "data"):
# Generic event with data
yield self._process_chunk(event.data)
else:
# Unknown event type, convert to string
yield str(event)
return # Successfully used astream_events
except (TypeError, ValueError):
# Try with simple dictionary input
if not isinstance(input_data, dict):
async for event in self.component.astream_events({"input": input_data}):
# Extract useful content from events
if hasattr(event, "event"):
if event.event == "on_llm_new_token":
# Token event - extract text
if hasattr(event, "data") and hasattr(event.data, "token"):
yield event.data.token
elif hasattr(event, "token"):
yield event.token
elif event.event in ["on_chat_model_stream", "on_llm_stream"]:
# Chunk event - extract content
if hasattr(event, "data") and hasattr(event.data, "chunk"):
yield self._process_chunk(event.data.chunk)
elif hasattr(event, "chunk"):
yield self._process_chunk(event.chunk)
elif hasattr(event, "data"):
# Generic event with data
yield self._process_chunk(event.data)
else:
# Unknown event type, convert to string
yield str(event)
return # Successfully used astream_events
except Exception as e:
logger.warning(f"Error using astream_events for '{self.name}': {e}")
# Continue to next method
# Fall back to non-streaming if none of the methods worked
logger.info(f"No compatible streaming method found for '{self.name}', using non-streaming fallback")
result = await self.process_message(text)
yield result
def _process_chunk(self, chunk: Any) -> str:
"""
Process a streaming chunk to extract the text content.
Args:
chunk: A chunk from a streaming response
Returns:
The extracted text content as a string
"""
if chunk is None:
return ""
# String chunks
if isinstance(chunk, str):
return chunk
# Object with content attribute (common in LLM responses)
if hasattr(chunk, "content"):
return str(chunk.content) if chunk.content is not None else ""
# Dictionary format - check common keys in a sensible order
if isinstance(chunk, dict):
for key in ["output", "text", "content", "token", "result", "response", "answer"]:
if key in chunk:
value = chunk[key]
if value is None:
continue
# Handle nested content
if isinstance(value, dict) and "content" in value:
return str(value["content"])
elif isinstance(value, dict) and "text" in value:
return str(value["text"])
elif hasattr(value, "content"):
return str(value.content)
else:
return str(value)
# If no recognized keys are found, convert the whole dict
return str(chunk)
# Default to string representation for any other object
return str(chunk)
def _prepare_input(self, text: str) -> Any:
"""
Prepare input for the component based on its expected format.
Args:
text: The text input to process
Returns:
Input in the format expected by the component
"""
# Try to determine expected input format
if hasattr(self.component, "input_keys") and self.component.input_keys:
# Use the first input key for components with input_keys
return {self.component.input_keys[0]: text}
# Check method signature for invoke
try:
sig = inspect.signature(self.component.invoke)
first_param = next(iter(sig.parameters.values()), None)
# If first parameter is positional or doesn't have default, use text directly
if first_param and first_param.default == inspect.Parameter.empty:
return text
except (ValueError, TypeError, StopIteration):
pass
# Check for specific input formats based on component type
if hasattr(self.component, "__class__") and hasattr(self.component.__class__, "__name__"):
component_class = self.component.__class__.__name__
# Handle common LangChain components
if component_class in ["ChatPromptTemplate", "PromptTemplate"]:
return {"input": text}
elif component_class in ["ChatOpenAI", "OpenAI", "ChatAnthropic", "Anthropic"]:
return text
# Default to dict format with "input" key
return {"input": text}
async def _invoke(self, input_data: Any) -> Any:
"""
Invoke the component with appropriate async/sync handling.
Args:
input_data: The prepared input data for the component
Returns:
The result from the component
"""
# Check for ainvoke method first (async invoke)
if hasattr(self.component, "ainvoke") and asyncio.iscoroutinefunction(self.component.ainvoke):
# Try direct invocation
try:
return await self.component.ainvoke(input_data)
except (TypeError, ValueError):
# Fall back to dict format if direct invocation fails
if not isinstance(input_data, dict):
return await self.component.ainvoke({"input": input_data})
raise
# Fall back to synchronous invoke
if asyncio.iscoroutinefunction(self.component.invoke):
# Async invoke
try:
return await self.component.invoke(input_data)
except (TypeError, ValueError):
# Fall back to dict format if direct invocation fails
if not isinstance(input_data, dict):
return await self.component.invoke({"input": input_data})
raise
else:
# Run synchronously in executor
loop = asyncio.get_event_loop()
try:
return await loop.run_in_executor(
None, lambda: self.component.invoke(input_data)
)
except (TypeError, ValueError):
# Fall back to dict format if direct invocation fails
if not isinstance(input_data, dict):
return await loop.run_in_executor(
None, lambda: self.component.invoke({"input": input_data})
)
raise
def _process_output(self, result: Any) -> str:
"""
Process the output from the component to a string.
Args:
result: The result from the component
Returns:
The extracted text content as a string
"""
if result is None:
return ""
# String results
if isinstance(result, str):
return result
# Process dictionary results
if isinstance(result, dict):
# Check common keys in a sensible order
for key in ["output", "text", "result", "response", "answer", "content"]:
if key in result:
value = result[key]
if value is None:
continue
# Handle nested content
if isinstance(value, dict) and "content" in value:
return str(value["content"])
elif isinstance(value, dict) and "text" in value:
return str(value["text"])
elif hasattr(value, "content"):
return str(value.content)
else:
return str(value)
# If component has output_keys, try the first one
if hasattr(self.component, "output_keys") and self.component.output_keys:
key = self.component.output_keys[0]
if key in result:
value = result[key]
return str(value) if value is not None else ""
# Handle common LangChain output types
if hasattr(result, "content"):
return str(result.content)
# Default to string representation for any other object
return str(result)
class AgentAdapter(ComponentAdapter):
"""Adapter for LangChain agent executors."""
def can_adapt(self) -> bool:
"""Check if component is a LangChain agent executor."""
# Check if it's an AgentExecutor or has expected agent properties
agent_executor_type = False
try:
agent_executor_type = isinstance(self.component, AgentExecutor)
except Exception:
pass
# More strict check for agent properties to avoid false positives
has_agent_attrs = (
hasattr(self.component, 'agent') and
hasattr(self.component, 'tools') and
hasattr(self.component, 'run') and
# Additional check: must have the agent attribute actually set
getattr(self.component, 'agent', None) is not None and
# Additional check: must have tools as a list or tuple
isinstance(getattr(self.component, 'tools', None), (list, tuple))
)
return agent_executor_type or has_agent_attrs
async def process_message(self, text: str) -> str:
"""Process message using agent run method."""
try:
# AgentExecutor expects input in key-value format
# Get the input key
input_key = getattr(self.component, 'input_key', 'input')
# Run the agent with the proper input formatting
if asyncio.iscoroutinefunction(self.component.run):
result = await self.component.run(**{input_key: text})
else:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, lambda: self.component.run(**{input_key: text})
)
# Handle various result formats
if isinstance(result, str):
return result
elif isinstance(result, dict):
# Agent outputs often have an 'output' key
if 'output' in result:
return str(result['output'])
else:
# If no output key, convert the dict to string
return str(result)
else:
return str(result)
except Exception as e:
logger.exception(f"Error running agent '{self.name}'")
return f"Error: {str(e)}"
async def process_stream(self, text: str):
"""Process streaming with agent."""
# Check if the agent supports streaming
if hasattr(self.component, 'stream') and callable(self.component.stream):
try:
# Get the input key
input_key = getattr(self.component, 'input_key', 'input')
# Stream with proper input format
if asyncio.iscoroutinefunction(self.component.stream):
async for chunk in self.component.stream(**{input_key: text}):
yield self._extract_chunk_content(chunk)
else:
for chunk in self.component.stream(**{input_key: text}):
yield self._extract_chunk_content(chunk)
except Exception as e:
logger.exception(f"Error streaming from agent '{self.name}': {e}")
# Fall back to non-streaming
result = await self.process_message(text)
yield result
else:
# Fall back to non-streaming if stream method not available
result = await self.process_message(text)
yield result
def _extract_chunk_content(self, chunk):
"""Extract content from streaming chunks."""
if isinstance(chunk, str):
return chunk
elif hasattr(chunk, 'content'):
return chunk.content
elif isinstance(chunk, dict):
if 'output' in chunk:
return str(chunk['output'])
elif 'content' in chunk:
return str(chunk['content'])
elif 'text' in chunk:
return str(chunk['text'])
return str(chunk)
class RunnableAdapter(ComponentAdapter):
"""Adapter for components with run method."""
def can_adapt(self) -> bool:
"""Check if component has run method."""
return (
isinstance(self.component, RunnableProtocol) or
isinstance(self.component, Runnable) or
hasattr(self.component, "run")
)
async def process_message(self, text: str) -> str:
"""
Process message using the run method.
For Runnable objects, tries to use invoke or ainvoke methods first,
then falls back to run method.
"""
try:
# First try invoke/ainvoke for modern LangChain Runnables
if isinstance(self.component, Runnable) or hasattr(self.component, "invoke"):
if hasattr(self.component, "ainvoke") and asyncio.iscoroutinefunction(self.component.ainvoke):
try:
# Try with direct input
result = await self.component.ainvoke(text)
except (TypeError, ValueError):
# Try with dictionary input
result = await self.component.ainvoke({"input": text})
else:
# Use synchronous invoke
loop = asyncio.get_event_loop()
try:
result = await loop.run_in_executor(
None, lambda: self.component.invoke(text)
)
except (TypeError, ValueError):
# Try with dictionary input
result = await loop.run_in_executor(
None, lambda: self.component.invoke({"input": text})
)
# Extract result from various formats
if isinstance(result, str):
return result
elif isinstance(result, dict):
for key in ["output", "text", "result", "content", "answer"]:
if key in result:
return str(result[key])
return str(result)
# Fall back to run method
if asyncio.iscoroutinefunction(self.component.run):
try:
# Try direct run
result = await self.component.run(text)
except (TypeError, ValueError):
# Try with dictionary input
result = await self.component.run({"input": text})
else:
# Run synchronously
loop = asyncio.get_event_loop()
try:
result = await loop.run_in_executor(None, self.component.run, text)
except (TypeError, ValueError):
# Try with dictionary input
result = await loop.run_in_executor(
None, lambda: self.component.run({"input": text})
)
# Process result
if result is None:
return ""
# Extract text from result
if isinstance(result, str):
return result
elif isinstance(result, dict):
for key in ["output", "text", "result", "content", "answer"]:
if key in result:
return str(result[key])
return str(result)
except Exception as e:
logger.exception(f"Error running component '{self.name}'")
return f"Error: {str(e)}"
async def process_stream(self, text: str):
"""
Process message using streaming support if available.
Args:
text: The text message to process
Yields:
Chunks of the response as they arrive
"""
# Try all modern LangChain streaming interfaces in priority order
# 1. First check for modern Runnable streaming interfaces
if isinstance(self.component, Runnable) or hasattr(self.component, "stream"):
# astream is preferred for async streaming (modern LangChain)
if hasattr(self.component, "astream") and callable(self.component.astream):
try:
# Try various input formats
try:
# Direct input
async for chunk in self.component.astream(text):
yield self._extract_chunk_content(chunk)
except (TypeError, ValueError):
# Dictionary input
async for chunk in self.component.astream({"input": text}):
yield self._extract_chunk_content(chunk)
return # Successfully used astream
except Exception as e:
logger.warning(f"Error using astream for '{self.name}': {e}")
# Continue to next method
# Try stream method (synchronous streaming)
if hasattr(self.component, "stream") and callable(self.component.stream):
try:
# Try with direct input
try:
if asyncio.iscoroutinefunction(self.component.stream):
# Async implementation
async for chunk in self.component.stream(text):
yield self._extract_chunk_content(chunk)
else:
# Sync implementation
for chunk in self.component.stream(text):
yield self._extract_chunk_content(chunk)
return # Successfully used stream
except (TypeError, ValueError):
# Try with dictionary input
if asyncio.iscoroutinefunction(self.component.stream):
# Async implementation
async for chunk in self.component.stream({"input": text}):
yield self._extract_chunk_content(chunk)
else:
# Sync implementation
for chunk in self.component.stream({"input": text}):
yield self._extract_chunk_content(chunk)
return # Successfully used stream
except Exception as e:
logger.warning(f"Error using stream for '{self.name}': {e}")
# Continue to next method
# 2. Check for advanced streaming interfaces like astream_events and astream_log
if hasattr(self.component, "astream_events") and callable(self.component.astream_events):
try:
# Try with direct input
try:
async for event in self.component.astream_events(text):
# Process event types (end, tokens, etc.)
if hasattr(event, "event") and event.event == "on_llm_new_token":
if hasattr(event, "data") and hasattr(event.data, "token"):
yield event.data.token
elif hasattr(event, "token"):
yield event.token
elif hasattr(event, "data"):
yield str(event.data)
elif hasattr(event, "event") and event.event in ["on_chat_model_stream", "on_llm_stream"]:
if hasattr(event, "data") and hasattr(event.data, "chunk"):
yield self._extract_chunk_content(event.data.chunk)
elif hasattr(event, "chunk"):
yield self._extract_chunk_content(event.chunk)
elif hasattr(event, "data"):
yield str(event.data)
except (TypeError, ValueError):
# Try with dictionary input
async for event in self.component.astream_events({"input": text}):
# Process event types
if hasattr(event, "event") and event.event == "on_llm_new_token":
if hasattr(event, "data") and hasattr(event.data, "token"):
yield event.data.token
elif hasattr(event, "token"):
yield event.token
elif hasattr(event, "data"):
yield str(event.data)
elif hasattr(event, "event") and event.event in ["on_chat_model_stream", "on_llm_stream"]:
if hasattr(event, "data") and hasattr(event.data, "chunk"):
yield self._extract_chunk_content(event.data.chunk)
elif hasattr(event, "chunk"):
yield self._extract_chunk_content(event.chunk)
elif hasattr(event, "data"):
yield str(event.data)
return # Successfully used astream_events
except Exception as e:
logger.warning(f"Error using astream_events for '{self.name}': {e}")
# Continue to next method
# Check for astream_log method (contains full intermediate steps)
if hasattr(self.component, "astream_log") and callable(self.component.astream_log):
try:
# Try with direct input
try:
async for log_entry in self.component.astream_log(text):
# Extract text from log entries
if isinstance(log_entry, str):
yield log_entry
elif isinstance(log_entry, dict):
if "output" in log_entry:
# Yield the output field
yield self._extract_chunk_content(log_entry["output"])
elif "final_output" in log_entry:
# Yield the final output
yield self._extract_chunk_content(log_entry["final_output"])
elif "intermediate_steps" in log_entry:
# Try to get something useful from intermediate steps
for step in log_entry["intermediate_steps"]:
if hasattr(step, "output") or (isinstance(step, tuple) and len(step) > 1):
output = step.output if hasattr(step, "output") else step[1]
yield self._extract_chunk_content(output)
except (TypeError, ValueError):
# Try with dictionary input
async for log_entry in self.component.astream_log({"input": text}):
# Extract text from log entries
if isinstance(log_entry, str):
yield log_entry
elif isinstance(log_entry, dict):
if "output" in log_entry:
# Yield the output field
yield self._extract_chunk_content(log_entry["output"])
elif "final_output" in log_entry:
# Yield the final output
yield self._extract_chunk_content(log_entry["final_output"])
elif "intermediate_steps" in log_entry:
# Try to get something useful from intermediate steps
for step in log_entry["intermediate_steps"]:
if hasattr(step, "output") or (isinstance(step, tuple) and len(step) > 1):
output = step.output if hasattr(step, "output") else step[1]
yield self._extract_chunk_content(output)
return # Successfully used astream_log
except Exception as e:
logger.warning(f"Error using astream_log for '{self.name}': {e}")
# Continue to next method
# 3. Check for older or custom interfaces
# Check for run_stream method (used by some LangChain Runnables)
if hasattr(self.component, "run_stream") and callable(self.component.run_stream):
try:
# Check if run_stream is async
if asyncio.iscoroutinefunction(self.component.run_stream):
try:
# Try with direct text
async for chunk in self.component.run_stream(text):
yield self._extract_chunk_content(chunk)
except (TypeError, ValueError):
# Try with dictionary
async for chunk in self.component.run_stream({"input": text}):
yield self._extract_chunk_content(chunk)
else:
# Sync run_stream
try:
# Try with direct text
for chunk in self.component.run_stream(text):
yield self._extract_chunk_content(chunk)
except (TypeError, ValueError):
# Try with dictionary
for chunk in self.component.run_stream({"input": text}):
yield self._extract_chunk_content(chunk)
return # Successfully used run_stream
except Exception as e:
logger.warning(f"Error using run_stream for '{self.name}': {e}")
# Continue to next method
# If we get here, none of the streaming methods worked
# Fall back to non-streaming
logger.info(f"No compatible streaming method found for '{self.name}', using non-streaming fallback")
result = await self.process_message(text)
yield result
def _extract_chunk_content(self, chunk: Any) -> str:
"""
Extract text content from various chunk formats.
Args:
chunk: A chunk from a streaming response, could be string, dict, or object
Returns:
The extracted text content as a string
"""
# String chunks
if isinstance(chunk, str):
return chunk
# Object with content attribute
if hasattr(chunk, "content"):
return str(chunk.content)
# Dictionary format with content
if isinstance(chunk, dict):
if "content" in chunk:
return str(chunk["content"])
elif "text" in chunk:
return str(chunk["text"])
elif "token" in chunk:
return str(chunk["token"])
elif "output" in chunk:
# Try to extract output
if isinstance(chunk["output"], str):
return chunk["output"]
elif hasattr(chunk["output"], "content"):
return str(chunk["output"].content)
elif isinstance(chunk["output"], dict) and "content" in chunk["output"]:
return str(chunk["output"]["content"])
# If we can't extract specific fields, convert the whole dict to string
return str(chunk)
# Any other object, convert to string
return str(chunk)
class LLMAdapter(ComponentAdapter):
"""Adapter for language model components."""
def can_adapt(self) -> bool:
"""Check if component is a language model."""
return (isinstance(self.component, (BaseLanguageModel, LLM)) or
hasattr(self.component, "predict") or
hasattr(self.component, "generate") or
hasattr(self.component, "stream"))
async def process_message(self, text: str) -> str:
"""Process message using LLM methods."""
try:
# Try predict if available
if hasattr(self.component, "predict"):
if asyncio.iscoroutinefunction(self.component.predict):
result = await self.component.predict(text=text)
else:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, lambda: self.component.predict(text=text)
)
return result if result is not None else ""
# Fall back to generate
if hasattr(self.component, "generate"):
if asyncio.iscoroutinefunction(self.component.generate):
generation = await self.component.generate([text])
else: