forked from oracle/langchain-oracle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoci_generative_ai.py
More file actions
1726 lines (1488 loc) · 64.4 KB
/
Copy pathoci_generative_ai.py
File metadata and controls
1726 lines (1488 loc) · 64.4 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
# Copyright (c) 2023 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import importlib
import json
import re
import uuid
from abc import ABC, abstractmethod
from operator import itemgetter
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Literal,
Mapping,
Optional,
Sequence,
Set,
Type,
Union,
)
import httpx
from langchain_core.callbacks import CallbackManagerForLLMRun
from langchain_core.language_models import LanguageModelInput
from langchain_core.language_models.chat_models import (
BaseChatModel,
generate_from_stream,
)
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
BaseMessage,
HumanMessage,
SystemMessage,
ToolCall,
ToolMessage,
)
from langchain_core.messages.tool import ToolCallChunk, tool_call_chunk
from langchain_core.output_parsers import (
JsonOutputParser,
PydanticOutputParser,
)
from langchain_core.output_parsers.base import OutputParserLike
from langchain_core.output_parsers.openai_tools import (
JsonOutputKeyToolsParser,
PydanticToolsParser,
)
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
from langchain_core.tools import BaseTool
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain_openai import ChatOpenAI
from openai import DefaultHttpxClient
from pydantic import BaseModel, ConfigDict, SecretStr, model_validator
from langchain_oci.llms.oci_generative_ai import OCIGenAIBase
from langchain_oci.llms.utils import enforce_stop_tokens
CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
API_KEY = "<NOTUSED>"
COMPARTMENT_ID_HEADER = "opc-compartment-id"
CONVERSATION_STORE_ID_HEADER = "opc-conversation-store-id"
OUTPUT_VERSION = "responses/v1"
# Mapping of JSON schema types to Python types
JSON_TO_PYTHON_TYPES = {
"string": "str",
"number": "float",
"boolean": "bool",
"integer": "int",
"array": "List",
"object": "Dict",
"any": "any",
}
class OCIUtils:
"""Utility functions for OCI Generative AI integration."""
@staticmethod
def is_pydantic_class(obj: Any) -> bool:
"""Check if an object is a Pydantic BaseModel subclass."""
return isinstance(obj, type) and issubclass(obj, BaseModel)
@staticmethod
def remove_signature_from_tool_description(name: str, description: str) -> str:
"""
Remove the tool signature and Args section from a tool description.
The signature is typically prefixed to the description and followed
by an Args section.
"""
description = re.sub(rf"^{name}\(.*?\) -(?:> \w+? -)? ", "", description)
description = re.sub(r"(?s)(?:\n?\n\s*?)?Args:.*$", "", description)
return description
@staticmethod
def convert_oci_tool_call_to_langchain(tool_call: Any) -> ToolCall:
"""Convert an OCI tool call to a LangChain ToolCall."""
parsed = json.loads(tool_call.arguments)
# If the parsed result is a string, it means the JSON was escaped, so parse again # noqa: E501
if isinstance(parsed, str):
try:
parsed = json.loads(parsed)
except json.JSONDecodeError:
# If it's not valid JSON, keep it as a string
pass
return ToolCall(
name=tool_call.name,
args=parsed
if "arguments" in tool_call.attribute_map
else tool_call.parameters,
id=tool_call.id if "id" in tool_call.attribute_map else uuid.uuid4().hex[:],
)
@staticmethod
def resolve_schema_refs(schema: Dict[str, Any]) -> Dict[str, Any]:
"""
OCI Generative AI doesn't support $ref and $defs, so we inline all references.
"""
defs = schema.get("$defs", {}) # OCI Generative AI doesn't support $defs
def resolve(obj: Any) -> Any:
if isinstance(obj, dict):
if "$ref" in obj:
ref = obj["$ref"]
if ref.startswith("#/$defs/"):
key = ref.split("/")[-1]
return resolve(defs.get(key, obj))
return obj # Cannot resolve $ref, return unchanged
return {k: resolve(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [resolve(item) for item in obj]
return obj
resolved = resolve(schema)
if isinstance(resolved, dict):
resolved.pop("$defs", None)
return resolved
class Provider(ABC):
"""Abstract base class for OCI Generative AI providers."""
@property
@abstractmethod
def stop_sequence_key(self) -> str:
"""Return the stop sequence key for the provider."""
...
@abstractmethod
def chat_response_to_text(self, response: Any) -> str:
"""Extract chat text from a provider's response."""
...
@abstractmethod
def chat_stream_to_text(self, event_data: Dict) -> str:
"""Extract chat text from a streaming event."""
...
@abstractmethod
def is_chat_stream_end(self, event_data: Dict) -> bool:
"""Determine if the chat stream event marks the end of a stream."""
...
@abstractmethod
def chat_generation_info(self, response: Any) -> Dict[str, Any]:
"""Extract generation metadata from a provider's response."""
...
@abstractmethod
def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]:
"""Extract generation metadata from a chat stream event."""
...
@abstractmethod
def chat_tool_calls(self, response: Any) -> List[Any]:
"""Extract tool calls from a provider's response."""
...
@abstractmethod
def chat_stream_tool_calls(self, event_data: Dict) -> List[Any]:
"""Extract tool calls from a streaming event."""
...
@abstractmethod
def format_response_tool_calls(self, tool_calls: List[Any]) -> List[Any]:
"""Format response tool calls into LangChain's expected structure."""
...
@abstractmethod
def format_stream_tool_calls(self, tool_calls: List[Any]) -> List[Any]:
"""Format stream tool calls into LangChain's expected structure."""
...
@abstractmethod
def get_role(self, message: BaseMessage) -> str:
"""Map a LangChain message to the provider's role representation."""
...
@abstractmethod
def messages_to_oci_params(self, messages: Any, **kwargs: Any) -> Dict[str, Any]:
"""Convert LangChain messages to OCI API parameters."""
...
@abstractmethod
def convert_to_oci_tool(
self, tool: Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]
) -> Dict[str, Any]:
"""Convert a tool definition into the provider-specific OCI tool format."""
...
@abstractmethod
def process_tool_choice(
self,
tool_choice: Optional[
Union[dict, str, Literal["auto", "none", "required", "any"], bool]
],
) -> Optional[Any]:
"""Process tool choice parameter for the provider."""
...
@abstractmethod
def process_stream_tool_calls(
self,
event_data: Dict,
tool_call_ids: Set[str],
) -> List[ToolCallChunk]:
"""Process streaming tool calls from event data into chunks."""
...
@property
def supports_parallel_tool_calls(self) -> bool:
"""Whether this provider supports parallel tool calling.
Parallel tool calling allows the model to call multiple tools
simultaneously in a single response.
Returns:
bool: True if parallel tool calling is supported, False otherwise.
"""
return False
class CohereProvider(Provider):
"""Provider implementation for Cohere."""
stop_sequence_key: str = "stop_sequences"
def __init__(self) -> None:
from oci.generative_ai_inference import models
self.oci_chat_request = models.CohereChatRequest
self.oci_tool = models.CohereTool
self.oci_tool_param = models.CohereParameterDefinition
self.oci_tool_result = models.CohereToolResult
self.oci_tool_call = models.CohereToolCall
self.oci_chat_message = {
"USER": models.CohereUserMessage,
"CHATBOT": models.CohereChatBotMessage,
"SYSTEM": models.CohereSystemMessage,
"TOOL": models.CohereToolMessage,
}
self.oci_response_json_schema = models.ResponseJsonSchema
self.oci_json_schema_response_format = models.JsonSchemaResponseFormat
self.chat_api_format = models.BaseChatRequest.API_FORMAT_COHERE
def chat_response_to_text(self, response: Any) -> str:
"""Extract text from a Cohere chat response."""
return response.data.chat_response.text
def chat_stream_to_text(self, event_data: Dict) -> str:
"""Extract text from a Cohere chat stream event."""
if "text" in event_data:
# Return empty string if finish reason or tool calls are present in stream
if "finishReason" in event_data or "toolCalls" in event_data:
return ""
else:
return event_data["text"]
return ""
def is_chat_stream_end(self, event_data: Dict) -> bool:
"""Determine if the Cohere stream event indicates the end."""
return "finishReason" in event_data
def chat_generation_info(self, response: Any) -> Dict[str, Any]:
"""Extract generation information from a Cohere chat response."""
generation_info: Dict[str, Any] = {
"documents": response.data.chat_response.documents,
"citations": response.data.chat_response.citations,
"search_queries": response.data.chat_response.search_queries,
"is_search_required": response.data.chat_response.is_search_required,
"finish_reason": response.data.chat_response.finish_reason,
}
# Include token usage if available
if (
hasattr(response.data.chat_response, "usage")
and response.data.chat_response.usage
):
generation_info["total_tokens"] = (
response.data.chat_response.usage.total_tokens
)
# Include tool calls if available
if self.chat_tool_calls(response):
generation_info["tool_calls"] = self.format_response_tool_calls(
self.chat_tool_calls(response)
)
return generation_info
def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]:
"""Extract generation info from a Cohere chat stream event."""
generation_info: Dict[str, Any] = {
"documents": event_data.get("documents"),
"citations": event_data.get("citations"),
"finish_reason": event_data.get("finishReason"),
}
# Remove keys with None values
return {k: v for k, v in generation_info.items() if v is not None}
def chat_tool_calls(self, response: Any) -> List[Any]:
"""Retrieve tool calls from a Cohere chat response."""
return response.data.chat_response.tool_calls
def chat_stream_tool_calls(self, event_data: Dict) -> List[Any]:
"""Retrieve tool calls from Cohere stream event data."""
return event_data.get("toolCalls", [])
def format_response_tool_calls(
self,
tool_calls: Optional[List[Any]] = None,
) -> List[Dict]:
"""
Formats a OCI GenAI API Cohere response
into the tool call format used in Langchain.
"""
if not tool_calls:
return []
formatted_tool_calls: List[Dict] = []
for tool_call in tool_calls:
formatted_tool_calls.append(
{
"id": uuid.uuid4().hex[:],
"function": {
"name": tool_call.name,
"arguments": json.dumps(tool_call.parameters),
},
"type": "function",
}
)
return formatted_tool_calls
def format_stream_tool_calls(self, tool_calls: List[Any]) -> List[Dict]:
"""
Formats a OCI GenAI API Cohere stream response
into the tool call format used in Langchain.
"""
if not tool_calls:
return []
formatted_tool_calls: List[Dict] = []
for tool_call in tool_calls:
formatted_tool_calls.append(
{
"id": uuid.uuid4().hex[:],
"function": {
"name": tool_call["name"],
"arguments": json.dumps(tool_call["parameters"]),
},
"type": "function",
}
)
return formatted_tool_calls
def get_role(self, message: BaseMessage) -> str:
"""Map a LangChain message to Cohere's role representation."""
if isinstance(message, HumanMessage):
return "USER"
elif isinstance(message, AIMessage):
return "CHATBOT"
elif isinstance(message, SystemMessage):
return "SYSTEM"
elif isinstance(message, ToolMessage):
return "TOOL"
raise ValueError(f"Unknown message type: {type(message)}")
def messages_to_oci_params(
self, messages: Sequence[BaseMessage], **kwargs: Any
) -> Dict[str, Any]:
"""
Convert LangChain messages to OCI parameters for Cohere.
This includes conversion of chat history and tool call results.
"""
# Cohere models don't support parallel tool calls
if kwargs.get("is_parallel_tool_calls"):
raise ValueError(
"Parallel tool calls are not supported for Cohere models. "
"This feature is only available for models using GenericChatRequest "
"(Meta, Llama, xAI Grok, OpenAI, Mistral)."
)
is_force_single_step = kwargs.get("is_force_single_step", False)
oci_chat_history = []
# Process all messages except the last one for chat history
for msg in messages[:-1]:
role = self.get_role(msg)
if role in ("USER", "SYSTEM"):
oci_chat_history.append(
self.oci_chat_message[role](message=msg.content)
)
elif isinstance(msg, AIMessage):
# Skip tool calls if forcing single step
if msg.tool_calls and is_force_single_step:
continue
tool_calls = (
[
self.oci_tool_call(name=tc["name"], parameters=tc["args"])
for tc in msg.tool_calls
]
if msg.tool_calls
else None
)
msg_content = msg.content if msg.content else " "
oci_chat_history.append(
self.oci_chat_message[role](
message=msg_content, tool_calls=tool_calls
)
)
elif isinstance(msg, ToolMessage):
oci_chat_history.append(
self.oci_chat_message[self.get_role(msg)](
tool_results=[
self.oci_tool_result(
call=self.oci_tool_call(name=msg.name, parameters={}),
outputs=[{"output": msg.content}],
)
],
)
)
# Process current turn messages in reverse order until a HumanMessage
current_turn = []
for i, message in enumerate(messages[::-1]):
current_turn.append(message)
if isinstance(message, HumanMessage):
if len(messages) > i and isinstance(
messages[len(messages) - i - 2], ToolMessage
):
# add dummy message REPEATING the tool_result to avoid
# the error about ToolMessage needing to be followed
# by an AI message
oci_chat_history.append(
self.oci_chat_message["CHATBOT"](
message=messages[len(messages) - i - 2].content
)
)
break
current_turn = list(reversed(current_turn))
# Process tool results from the current turn
oci_tool_results: Optional[List[Any]] = []
for message in current_turn:
if isinstance(message, ToolMessage):
tool_msg = message
previous_ai_msgs = [
m for m in current_turn if isinstance(m, AIMessage) and m.tool_calls
]
if previous_ai_msgs:
previous_ai_msg = previous_ai_msgs[-1]
for lc_tool_call in previous_ai_msg.tool_calls:
if lc_tool_call["id"] == tool_msg.tool_call_id:
tool_result = self.oci_tool_result()
tool_result.call = self.oci_tool_call(
name=lc_tool_call["name"],
parameters=lc_tool_call["args"],
)
tool_result.outputs = [{"output": tool_msg.content}]
oci_tool_results.append(tool_result) # type: ignore[union-attr]
if not oci_tool_results:
oci_tool_results = None
# Use last message's content if no tool results are present
message_str = "" if oci_tool_results else messages[-1].content
oci_params = {
"message": message_str,
"chat_history": oci_chat_history,
"tool_results": oci_tool_results,
"api_format": self.chat_api_format,
}
# Remove keys with None values
return {k: v for k, v in oci_params.items() if v is not None}
def convert_to_oci_tool(
self,
tool: Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool],
) -> Dict[str, Any]:
"""
Convert a tool definition to an OCI tool for Cohere.
Supports BaseTool instances, JSON schema dictionaries,
or Pydantic models/callables.
"""
if isinstance(tool, BaseTool):
return self.oci_tool(
name=tool.name,
description=OCIUtils.remove_signature_from_tool_description(
tool.name, tool.description
),
parameter_definitions={
p_name: self.oci_tool_param(
description=p_def.get("description", ""),
type=JSON_TO_PYTHON_TYPES.get(
p_def.get("type"),
p_def.get("type", "any"),
),
is_required="default" not in p_def,
)
for p_name, p_def in tool.args.items()
},
)
elif isinstance(tool, dict):
if not all(k in tool for k in ("title", "description", "properties")):
raise ValueError(
"Unsupported dict type. Tool must be a BaseTool instance, JSON schema dict, or Pydantic model." # noqa: E501
)
return self.oci_tool(
name=tool.get("title"),
description=tool.get("description"),
parameter_definitions={
p_name: self.oci_tool_param(
description=p_def.get("description", ""),
type=JSON_TO_PYTHON_TYPES.get(
p_def.get("type"),
p_def.get("type", "any"),
),
is_required="default" not in p_def,
)
for p_name, p_def in tool.get("properties", {}).items()
},
)
elif (isinstance(tool, type) and issubclass(tool, BaseModel)) or callable(tool):
as_json_schema_function = convert_to_openai_function(tool)
parameters = as_json_schema_function.get("parameters", {})
properties = parameters.get("properties", {})
return self.oci_tool(
name=as_json_schema_function.get("name"),
description=as_json_schema_function.get(
"description",
as_json_schema_function.get("name"),
),
parameter_definitions={
p_name: self.oci_tool_param(
description=p_def.get("description", ""),
type=JSON_TO_PYTHON_TYPES.get(
p_def.get("type"),
p_def.get("type", "any"),
),
is_required=p_name in parameters.get("required", []),
)
for p_name, p_def in properties.items()
},
)
raise ValueError(
f"Unsupported tool type {type(tool)}. Must be BaseTool instance, JSON schema dict, or Pydantic model." # noqa: E501
)
def process_tool_choice(
self,
tool_choice: Optional[
Union[dict, str, Literal["auto", "none", "required", "any"], bool]
],
) -> Optional[Any]:
"""Cohere does not support tool choices."""
if tool_choice is not None:
raise ValueError(
"Tool choice is not supported for Cohere models."
"Please remove the tool_choice parameter."
)
return None
def process_stream_tool_calls(
self, event_data: Dict, tool_call_ids: Set[str]
) -> List[ToolCallChunk]:
"""
Process Cohere stream tool calls and return them as ToolCallChunk objects.
Args:
event_data: The event data from the stream
tool_call_ids: Set of existing tool call IDs for index tracking
Returns:
List of ToolCallChunk objects
"""
tool_call_chunks: List[ToolCallChunk] = []
tool_call_response = self.chat_stream_tool_calls(event_data)
if not tool_call_response:
return tool_call_chunks
for tool_call in self.format_stream_tool_calls(tool_call_response):
tool_id = tool_call.get("id")
if tool_id:
tool_call_ids.add(tool_id)
tool_call_chunks.append(
tool_call_chunk(
name=tool_call["function"].get("name"),
args=tool_call["function"].get("arguments"),
id=tool_id,
index=len(tool_call_ids) - 1, # index tracking
)
)
return tool_call_chunks
class GenericProvider(Provider):
"""Provider for models using generic API spec."""
stop_sequence_key: str = "stop"
@property
def supports_parallel_tool_calls(self) -> bool:
"""GenericProvider models support parallel tool calling."""
return True
def __init__(self) -> None:
from oci.generative_ai_inference import models
# Chat request and message models
self.oci_chat_request = models.GenericChatRequest
self.oci_chat_message = {
"USER": models.UserMessage,
"SYSTEM": models.SystemMessage,
"ASSISTANT": models.AssistantMessage,
"TOOL": models.ToolMessage,
}
# Content models
self.oci_chat_message_content = models.ChatContent
self.oci_chat_message_text_content = models.TextContent
self.oci_chat_message_image_content = models.ImageContent
self.oci_chat_message_image_url = models.ImageUrl
# Tool-related models
self.oci_function_definition = models.FunctionDefinition
self.oci_tool_choice_auto = models.ToolChoiceAuto
self.oci_tool_choice_function = models.ToolChoiceFunction
self.oci_tool_choice_none = models.ToolChoiceNone
self.oci_tool_choice_required = models.ToolChoiceRequired
self.oci_tool_call = models.FunctionCall
self.oci_tool_message = models.ToolMessage
# Response format models
self.oci_response_json_schema = models.ResponseJsonSchema
self.oci_json_schema_response_format = models.JsonSchemaResponseFormat
self.chat_api_format = models.BaseChatRequest.API_FORMAT_GENERIC
def chat_response_to_text(self, response: Any) -> str:
"""Extract text from Meta chat response."""
message = response.data.chat_response.choices[0].message
content = message.content[0] if message.content else None
return content.text if content else ""
def chat_stream_to_text(self, event_data: Dict) -> str:
"""Extract text from Meta chat stream event."""
content = event_data.get("message", {}).get("content", None)
if not content:
return ""
return content[0]["text"]
def is_chat_stream_end(self, event_data: Dict) -> bool:
"""Determine if Meta chat stream event indicates the end."""
return "finishReason" in event_data
def chat_generation_info(self, response: Any) -> Dict[str, Any]:
"""Extract generation metadata from Meta chat response."""
generation_info: Dict[str, Any] = {
"finish_reason": response.data.chat_response.choices[0].finish_reason,
"time_created": str(response.data.chat_response.time_created),
}
# Include token usage if available
if (
hasattr(response.data.chat_response, "usage")
and response.data.chat_response.usage
):
generation_info["total_tokens"] = (
response.data.chat_response.usage.total_tokens
)
if self.chat_tool_calls(response):
generation_info["tool_calls"] = self.format_response_tool_calls(
self.chat_tool_calls(response)
)
return generation_info
def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]:
"""Extract generation metadata from Meta chat stream event."""
return {"finish_reason": event_data["finishReason"]}
def chat_tool_calls(self, response: Any) -> List[Any]:
"""Retrieve tool calls from Meta chat response."""
return response.data.chat_response.choices[0].message.tool_calls
def chat_stream_tool_calls(self, event_data: Dict) -> List[Any]:
"""Retrieve tool calls from Meta stream event."""
return event_data.get("message", {}).get("toolCalls", [])
def format_response_tool_calls(self, tool_calls: List[Any]) -> List[Dict]:
"""
Formats a OCI GenAI API Meta response
into the tool call format used in Langchain.
"""
if not tool_calls:
return []
formatted_tool_calls: List[Dict] = []
for tool_call in tool_calls:
formatted_tool_calls.append(
{
"id": tool_call.id,
"function": {
"name": tool_call.name,
"arguments": json.loads(tool_call.arguments),
},
"type": "function",
}
)
return formatted_tool_calls
def format_stream_tool_calls(
self,
tool_calls: Optional[List[Any]] = None,
) -> List[Dict]:
"""
Formats a OCI GenAI API Meta stream response
into the tool call format used in Langchain.
"""
if not tool_calls:
return []
formatted_tool_calls: List[Dict] = []
for tool_call in tool_calls:
# empty string for fields not present in the tool call
formatted_tool_calls.append(
{
"id": tool_call.get("id", ""),
"function": {
"name": tool_call.get("name", ""),
"arguments": tool_call.get("arguments", ""),
},
"type": "function",
}
)
return formatted_tool_calls
def get_role(self, message: BaseMessage) -> str:
"""Map a LangChain message to Meta's role representation."""
if isinstance(message, HumanMessage):
return "USER"
elif isinstance(message, AIMessage):
return "ASSISTANT"
elif isinstance(message, SystemMessage):
return "SYSTEM"
elif isinstance(message, ToolMessage):
return "TOOL"
raise ValueError(f"Unknown message type: {type(message)}")
def messages_to_oci_params(
self, messages: List[BaseMessage], **kwargs: Any
) -> Dict[str, Any]:
"""Convert LangChain messages to OCI chat parameters.
Args:
messages: List of LangChain BaseMessage objects
**kwargs: Additional keyword arguments
Returns:
Dict containing OCI chat parameters
Raises:
ValueError: If message content is invalid
"""
oci_messages = []
for message in messages:
role = self.get_role(message)
if isinstance(message, ToolMessage):
# For tool messages, wrap the content in a text content object.
tool_content = [
self.oci_chat_message_text_content(text=str(message.content))
]
if message.tool_call_id:
oci_message = self.oci_chat_message[role](
content=tool_content,
tool_call_id=message.tool_call_id,
)
else:
oci_message = self.oci_chat_message[role](content=tool_content)
elif isinstance(message, AIMessage) and (
message.tool_calls or message.additional_kwargs.get("tool_calls")
):
# Process content and tool calls for assistant messages
content = self._process_message_content(message.content)
tool_calls = []
for tool_call in message.tool_calls:
tool_calls.append(
self.oci_tool_call(
id=tool_call["id"],
name=tool_call["name"],
arguments=json.dumps(tool_call["args"]),
)
)
oci_message = self.oci_chat_message[role](
content=content,
tool_calls=tool_calls,
)
else:
# For regular messages, process content normally.
content = self._process_message_content(message.content)
oci_message = self.oci_chat_message[role](content=content)
oci_messages.append(oci_message)
result = {
"messages": oci_messages,
"api_format": self.chat_api_format,
}
# BUGFIX: Intelligently manage tool_choice to prevent infinite loops
# while allowing legitimate multi-step tool orchestration.
# This addresses a known issue with Meta Llama models that
# continue calling tools even after receiving results.
def _should_allow_more_tool_calls(
messages: List[BaseMessage], max_tool_calls: int
) -> bool:
"""
Determine if the model should be allowed to call more tools.
Returns False (force stop) if:
- Tool call limit exceeded
- Infinite loop detected (same tool called repeatedly with same args)
Returns True otherwise to allow multi-step tool orchestration.
Args:
messages: Conversation history
max_tool_calls: Maximum number of tool calls before forcing stop
"""
# Count total tool calls made so far
tool_call_count = sum(1 for msg in messages if isinstance(msg, ToolMessage))
# Safety limit: prevent runaway tool calling
if tool_call_count >= max_tool_calls:
return False
# Detect infinite loop: same tool called with same arguments in succession
recent_calls: list = []
for msg in reversed(messages):
if hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
# Create signature: (tool_name, sorted_args)
try:
args_str = json.dumps(tc.get("args", {}), sort_keys=True)
signature = (tc.get("name", ""), args_str)
# Check if this exact call was made in last 2 calls
if signature in recent_calls[-2:]:
return False # Infinite loop detected
recent_calls.append(signature)
except Exception:
# If we can't serialize args, be conservative and continue
pass
# Only check last 4 AI messages (last 4 tool call attempts)
if len(recent_calls) >= 4:
break
return True
has_tool_results = any(isinstance(msg, ToolMessage) for msg in messages)
if has_tool_results and "tools" in kwargs and "tool_choice" not in kwargs:
max_tool_calls = kwargs.get("max_sequential_tool_calls", 8)
if not _should_allow_more_tool_calls(messages, max_tool_calls):
# Force model to stop and provide final answer
result["tool_choice"] = self.oci_tool_choice_none()
# else: Allow model to decide (default behavior)
# Add parallel tool calls support (GenericChatRequest models)
if "is_parallel_tool_calls" in kwargs:
result["is_parallel_tool_calls"] = kwargs["is_parallel_tool_calls"]
return result
def _process_message_content(
self, content: Union[str, List[Union[str, Dict]]]
) -> List[Any]:
"""Process message content into OCI chat content format.
Args:
content: Message content as string or list
Returns:
List of OCI chat content objects
Raises:
ValueError: If content format is invalid
"""
if isinstance(content, str):
return [self.oci_chat_message_text_content(text=content)]
if not isinstance(content, list):
raise ValueError("Message content must be a string or a list of items.")
processed_content = []
for item in content:
if isinstance(item, str):
processed_content.append(self.oci_chat_message_text_content(text=item))
elif isinstance(item, dict):
if "type" not in item:
raise ValueError("Dict content item must have a 'type' key.")
if item["type"] == "image_url":
processed_content.append(
self.oci_chat_message_image_content(
image_url=self.oci_chat_message_image_url(
url=item["image_url"]["url"]
)
)
)
elif item["type"] == "text":
processed_content.append(
self.oci_chat_message_text_content(text=item["text"])
)
else:
raise ValueError(f"Unsupported content type: {item['type']}")
else:
raise ValueError(
f"Content items must be str or dict, got: {type(item)}"
)
return processed_content
def convert_to_oci_tool(
self,
tool: Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool],
) -> Dict[str, Any]:
"""Convert a BaseTool instance, TypedDict or BaseModel type
to a OCI tool in Meta's format.
Args:
tool: The tool to convert, can be a BaseTool instance, TypedDict,
or BaseModel type.
Returns:
Dict containing the tool definition in Meta's format.
Raises:
ValueError: If the tool type is not supported.
"""
# Check BaseTool first since it's callable but needs special handling
if isinstance(tool, BaseTool):
return self.oci_function_definition(
name=tool.name,
description=OCIUtils.remove_signature_from_tool_description(
tool.name, tool.description
),
parameters={
"type": "object",
"properties": {
p_name: {
"type": p_def.get("type", "any"),
"description": p_def.get("description", ""),
}
for p_name, p_def in tool.args.items()
},
"required": [
p_name
for p_name, p_def in tool.args.items()
if "default" not in p_def
],
},
)
if (isinstance(tool, type) and issubclass(tool, BaseModel)) or callable(tool):
as_json_schema_function = convert_to_openai_function(tool)
parameters = as_json_schema_function.get("parameters", {})
return self.oci_function_definition(
name=as_json_schema_function.get("name"),