-
Notifications
You must be signed in to change notification settings - Fork 24.3k
Expand file tree
/
Copy pathchat_models.py
More file actions
1687 lines (1461 loc) · 63.9 KB
/
Copy pathchat_models.py
File metadata and controls
1687 lines (1461 loc) · 63.9 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
"""Fireworks chat wrapper."""
from __future__ import annotations
import contextlib
import json
import logging
import os
from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
from operator import itemgetter
from typing import (
Any,
Literal,
NoReturn,
cast,
)
import httpx
from fireworks import (
APIConnectionError,
AsyncFireworks,
BadRequestError,
Fireworks,
FireworksError,
InternalServerError,
RateLimitError,
)
from langchain_core.callbacks import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain_core.exceptions import ContextOverflowError
from langchain_core.language_models import (
LanguageModelInput,
ModelProfile,
ModelProfileRegistry,
)
from langchain_core.language_models.chat_models import (
BaseChatModel,
LangSmithParams,
agenerate_from_stream,
generate_from_stream,
)
from langchain_core.language_models.llms import create_base_retry_decorator
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
FunctionMessageChunk,
HumanMessage,
HumanMessageChunk,
InvalidToolCall,
SystemMessage,
SystemMessageChunk,
ToolCall,
ToolMessage,
ToolMessageChunk,
is_data_content_block,
)
from langchain_core.messages.block_translators.openai import (
convert_to_openai_data_block,
)
from langchain_core.messages.tool import (
ToolCallChunk,
)
from langchain_core.messages.tool import (
tool_call_chunk as create_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,
make_invalid_tool_call,
parse_tool_call,
)
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 import (
get_pydantic_field_names,
)
from langchain_core.utils.function_calling import (
convert_to_json_schema,
convert_to_openai_tool,
)
from langchain_core.utils.langsmith_gateway import LangSmithGatewayOAuth
from langchain_core.utils.pydantic import is_basemodel_subclass
from langchain_core.utils.utils import _build_model_kwargs, from_env, secret_from_env
from pydantic import (
BaseModel,
ConfigDict,
Field,
PrivateAttr,
SecretStr,
model_validator,
)
from typing_extensions import Self
from langchain_fireworks._compat import _convert_from_v1_to_chat_completions
from langchain_fireworks._version import __version__
from langchain_fireworks.data._profiles import _PROFILES
logger = logging.getLogger(__name__)
_MODEL_PROFILES = cast("ModelProfileRegistry", _PROFILES)
_LANGSMITH_GATEWAY_DEFAULT_URL = "https://gateway.smith.langchain.com/fireworks"
def _resolve_gateway_base_url() -> str | None:
raw = os.getenv("LANGSMITH_GATEWAY")
if raw is None or raw.lower() in ("false", "0", "no"):
return None
if raw.lower() in ("true", "1", "yes"):
return _LANGSMITH_GATEWAY_DEFAULT_URL
return raw
def _get_default_model_profile(model_name: str) -> ModelProfile:
default = _MODEL_PROFILES.get(model_name) or {}
return default.copy()
def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
"""Convert a dictionary to a LangChain message.
Args:
_dict: The dictionary.
Returns:
The LangChain message.
"""
role = _dict.get("role")
if role == "user":
return HumanMessage(content=_dict.get("content", ""))
if role == "assistant":
# Fix for azure
# Also Fireworks returns None for tool invocations
content = _dict.get("content", "") or ""
additional_kwargs: dict = {}
if reasoning_content := _dict.get("reasoning_content"):
additional_kwargs["reasoning_content"] = reasoning_content
if function_call := _dict.get("function_call"):
additional_kwargs["function_call"] = dict(function_call)
tool_calls = []
invalid_tool_calls = []
if raw_tool_calls := _dict.get("tool_calls"):
additional_kwargs["tool_calls"] = raw_tool_calls
for raw_tool_call in raw_tool_calls:
try:
tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
except Exception as e:
invalid_tool_calls.append(
dict(make_invalid_tool_call(raw_tool_call, str(e)))
)
return AIMessage(
content=content,
additional_kwargs=additional_kwargs,
tool_calls=tool_calls,
invalid_tool_calls=invalid_tool_calls,
)
if role == "system":
return SystemMessage(content=_dict.get("content", ""))
if role == "function":
return FunctionMessage(
content=_dict.get("content", ""), name=_dict.get("name", "")
)
if role == "tool":
additional_kwargs = {}
if "name" in _dict:
additional_kwargs["name"] = _dict["name"]
return ToolMessage(
content=_dict.get("content", ""),
tool_call_id=_dict.get("tool_call_id", ""),
additional_kwargs=additional_kwargs,
)
return ChatMessage(content=_dict.get("content", ""), role=role or "")
def _allowed_content_part_keys() -> frozenset[str]:
"""Allowlist of wire-valid keys on a Fireworks content part.
Derived at import time from the stainless-generated TypedDict so the
allowlist tracks the upstream OpenAPI spec as `fireworks-ai` is bumped:
new fields widen the allowlist for free, removed/renamed fields shrink it
in lockstep. If the SDK reshuffles its module layout the import falls back
to a conservative hand-coded set and emits a warning, and the layout test
(`test_fireworks_sdk_request_layout_stable`) fails to surface the drift.
"""
try:
from typing import get_type_hints
from fireworks.types.shared_params.chat_message import (
ContentUnionMember1,
)
return frozenset(get_type_hints(ContentUnionMember1))
except ImportError:
logger.warning(
"Could not import `fireworks.types.shared_params.chat_message."
"ContentUnionMember1`; falling back to a conservative content-part "
"key allowlist. Bump `fireworks-ai` or update "
"`_allowed_content_part_keys` if the SDK has moved this type.",
)
return frozenset({"type", "text", "image_url", "video_url"})
_ALLOWED_CONTENT_PART_KEYS: frozenset[str] = _allowed_content_part_keys()
def _sanitize_chat_completions_content(content: Any) -> Any:
"""Strip non-wire keys from content blocks before serializing to Fireworks.
Fireworks's chat completions endpoint rejects unknown fields on message
content parts with `Extra inputs are not permitted, field: 'messages[N]
.content.list[ChatMessageContent][i].<key>'`. This surfaces when a
conversation accumulates AIMessages from a different provider (e.g.
Anthropic's v1 streaming-reassembly `index` marker on text blocks, or the
LangChain-internal `caller` key on `tool_use` blocks) and that history is
later forwarded to a Fireworks-hosted model.
For list content:
- each block dict is filtered down to keys in
`_ALLOWED_CONTENT_PART_KEYS` (sourced from the SDK TypedDict, so it
stays in sync with the upstream spec).
- if the result is a list of exactly one block that, post-strip, is
`{"type": "text", "text": <str>}` and nothing else, it is coerced to
a plain string. Fireworks's `content` union lists `str` first
(`Input should be a valid string, field: 'messages[N].content.str'`),
and the stricter shape avoids the union-validation noise on the
server side.
Non-list content (strings, None) passes through unchanged.
"""
if not isinstance(content, list):
return content
sanitized: list[Any] = []
for block in content:
if isinstance(block, dict):
sanitized.append(
{k: v for k, v in block.items() if k in _ALLOWED_CONTENT_PART_KEYS}
)
else:
sanitized.append(block)
if (
len(sanitized) == 1
and isinstance(sanitized[0], dict)
and set(sanitized[0]) == {"type", "text"}
and sanitized[0]["type"] == "text"
and isinstance(sanitized[0]["text"], str)
):
return sanitized[0]["text"]
return sanitized
def _format_message_content(content: Any) -> Any:
"""Format message content for the Fireworks chat completions wire format.
Adapted from `langchain_openai.chat_models.base._format_message_content`,
scoped to the chat completions API: drops content block types the wire
format does not carry, translates canonical v0/v1 multimodal data blocks
via `convert_to_openai_data_block(block, api="chat/completions")`, and
converts legacy Anthropic-shape image blocks (`{"type": "image",
"source": {...}}`) to OpenAI `image_url` blocks. String and non-list
content are returned unchanged.
Args:
content: The message content. Strings and non-list values are
returned as-is; lists are walked block by block.
Returns:
The formatted content, ready to be placed on the chat completions
wire. List inputs return a new list with translations applied; other
inputs are returned unchanged.
"""
if not isinstance(content, list):
return content
formatted: list[Any] = []
for block in content:
if isinstance(block, dict) and "type" in block:
btype = block["type"]
if btype in (
"tool_use",
"thinking",
"reasoning_content",
"function_call",
"code_interpreter_call",
):
continue
if is_data_content_block(block):
formatted.append(
convert_to_openai_data_block(block, api="chat/completions")
)
continue
if (
btype == "image"
and (source := block.get("source"))
and isinstance(source, dict)
):
if (
source.get("type") == "base64"
and (media_type := source.get("media_type"))
and (data := source.get("data"))
):
formatted.append(
{
"type": "image_url",
"image_url": {"url": f"data:{media_type};base64,{data}"},
}
)
continue
if source.get("type") == "url" and (url := source.get("url")):
formatted.append({"type": "image_url", "image_url": {"url": url}})
continue
continue
formatted.append(block)
return formatted
def _convert_message_to_dict(message: BaseMessage) -> dict:
"""Convert a LangChain message to a dictionary.
Args:
message: The LangChain message.
Returns:
The dictionary.
"""
message_dict: dict[str, Any]
if isinstance(message, ChatMessage):
message_dict = {
"role": message.role,
"content": _sanitize_chat_completions_content(
_format_message_content(message.content)
),
}
elif isinstance(message, HumanMessage):
message_dict = {
"role": "user",
"content": _sanitize_chat_completions_content(
_format_message_content(message.content)
),
}
elif isinstance(message, AIMessage):
# Translate v1 content
if message.response_metadata.get("output_version") == "v1":
message = _convert_from_v1_to_chat_completions(message)
message_dict = {
"role": "assistant",
"content": _sanitize_chat_completions_content(
_format_message_content(message.content)
),
}
if "function_call" in message.additional_kwargs:
message_dict["function_call"] = message.additional_kwargs["function_call"]
# If function call only, content is None not empty string
if message_dict["content"] == "":
message_dict["content"] = None
if message.tool_calls or message.invalid_tool_calls:
message_dict["tool_calls"] = [
_lc_tool_call_to_fireworks_tool_call(tc) for tc in message.tool_calls
] + [
_lc_invalid_tool_call_to_fireworks_tool_call(tc)
for tc in message.invalid_tool_calls
]
elif "tool_calls" in message.additional_kwargs:
message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
# If tool calls only, content is None not empty string
if "tool_calls" in message_dict and message_dict["content"] == "":
message_dict["content"] = None
else:
pass
elif isinstance(message, SystemMessage):
message_dict = {
"role": "system",
"content": _sanitize_chat_completions_content(
_format_message_content(message.content)
),
}
elif isinstance(message, FunctionMessage):
message_dict = {
"role": "function",
"content": message.content,
"name": message.name,
}
elif isinstance(message, ToolMessage):
message_dict = {
"role": "tool",
"content": _sanitize_chat_completions_content(
_format_message_content(message.content)
),
"tool_call_id": message.tool_call_id,
}
else:
msg = f"Got unknown type {message}"
raise TypeError(msg)
if "name" in message.additional_kwargs:
message_dict["name"] = message.additional_kwargs["name"]
return message_dict
def _usage_to_metadata(usage: Mapping[str, Any]) -> dict[str, int]:
input_tokens = usage.get("prompt_tokens", 0)
output_tokens = usage.get("completion_tokens", 0)
return {
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": usage.get("total_tokens", input_tokens + output_tokens),
}
def _convert_chunk_to_message_chunk(
chunk: Mapping[str, Any], default_class: type[BaseMessageChunk]
) -> BaseMessageChunk:
choices = chunk.get("choices") or []
response_metadata: dict[str, Any] = {"model_provider": "fireworks"}
if service_tier := chunk.get("service_tier"):
response_metadata["service_tier"] = service_tier
if not choices:
# Final chunk emitted when `stream_options.include_usage=True`:
# `choices` is empty and the chunk carries only `usage`.
usage = chunk.get("usage")
if not usage:
logger.debug(
"Received stream chunk with no choices and no usage: %s", chunk
)
usage_metadata = _usage_to_metadata(usage) if usage else None
return AIMessageChunk(
content="",
usage_metadata=usage_metadata, # type: ignore[arg-type]
response_metadata=response_metadata,
)
choice = choices[0]
_dict = choice["delta"]
role = cast(str, _dict.get("role"))
content = cast(str, _dict.get("content") or "")
additional_kwargs: dict = {}
tool_call_chunks: list[ToolCallChunk] = []
if _dict.get("function_call"):
function_call = dict(_dict["function_call"])
if "name" in function_call and function_call["name"] is None:
function_call["name"] = ""
additional_kwargs["function_call"] = function_call
if raw_tool_calls := _dict.get("tool_calls"):
additional_kwargs["tool_calls"] = raw_tool_calls
for rtc in raw_tool_calls:
with contextlib.suppress(KeyError):
tool_call_chunks.append(
create_tool_call_chunk(
name=rtc["function"].get("name"),
args=rtc["function"].get("arguments"),
id=rtc.get("id"),
index=rtc.get("index"),
)
)
if role == "user" or default_class == HumanMessageChunk:
return HumanMessageChunk(content=content)
if role == "assistant" or default_class == AIMessageChunk:
usage = chunk.get("usage")
usage_metadata = _usage_to_metadata(usage) if usage else None
return AIMessageChunk(
content=content,
additional_kwargs=additional_kwargs,
tool_call_chunks=tool_call_chunks,
usage_metadata=usage_metadata, # type: ignore[arg-type]
response_metadata=response_metadata,
)
if role == "system" or default_class == SystemMessageChunk:
return SystemMessageChunk(content=content)
if role == "function" or default_class == FunctionMessageChunk:
return FunctionMessageChunk(content=content, name=_dict["name"])
if role == "tool" or default_class == ToolMessageChunk:
return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
if role or default_class == ChatMessageChunk:
return ChatMessageChunk(content=content, role=role)
return default_class(content=content) # type: ignore[call-arg]
class _RetryableHTTPStatusError(FireworksError):
"""Internal marker for 5xx `httpx.HTTPStatusError` responses.
The 1.x SDK wraps every status response into a typed `APIStatusError`
subclass, so this path is defense-in-depth: it only fires when a raw
`httpx.HTTPStatusError` escapes the SDK (e.g., a custom `http_client` or
monkey-patched transport raises one directly). Promoting it here keeps the
retryable set expressible as a list of classes for
`create_base_retry_decorator`.
"""
_RETRYABLE_ERRORS: tuple[type[BaseException], ...] = (
APIConnectionError,
InternalServerError,
RateLimitError,
httpx.TimeoutException,
httpx.TransportError,
_RetryableHTTPStatusError,
)
def _promote_http_status_error(exc: httpx.HTTPStatusError) -> NoReturn:
"""Re-raise 5xx `httpx.HTTPStatusError` as a retryable marker."""
if exc.response.status_code >= 500:
msg = f"Retryable {exc.response.status_code} from Fireworks: {exc}"
raise _RetryableHTTPStatusError(msg) from exc
raise exc
class FireworksContextOverflowError(BadRequestError, ContextOverflowError):
"""`BadRequestError` raised when input exceeds Fireworks's context limit."""
def _handle_fireworks_invalid_request(e: BadRequestError) -> NoReturn:
"""Promote prompt-too-long errors to `FireworksContextOverflowError`."""
if "prompt is too long" in str(e):
raise FireworksContextOverflowError(
str(e), response=e.response, body=e.body
) from e
raise e
def _raise_empty_stream() -> NoReturn:
"""Raise a descriptive error when the SDK returns a zero-chunk stream."""
msg = "Received empty stream from Fireworks"
raise FireworksError(msg)
def _create_retry_decorator(
llm: ChatFireworks,
run_manager: AsyncCallbackManagerForLLMRun | CallbackManagerForLLMRun | None = None,
) -> Callable[[Any], Any]:
"""Return a tenacity retry decorator for Fireworks SDK calls.
Retries live here rather than in the SDK so each attempt is visible to the
LangChain `run_manager.on_retry` callback. The SDK's own retry layer is
suppressed via `max_retries=0` on the client; see `validate_environment`.
"""
# `max_retries` counts retries *after* the initial attempt (default lives on
# the `ChatFireworks.max_retries` field). `create_base_retry_decorator`
# forwards its `max_retries` to `stop_after_attempt`, which counts total
# attempts — so offset by 1. `None` and `0` both mean "single attempt, no
# retries".
attempts = (llm.max_retries + 1) if llm.max_retries else 1
return create_base_retry_decorator(
error_types=list(_RETRYABLE_ERRORS),
max_retries=attempts,
run_manager=run_manager,
)
def _prepare_sdk_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
"""Move fields the 1.x SDK does not model into `extra_body`.
The Stainless-generated `chat.completions.create` signature has a fixed set
of typed parameters. Fireworks accepts additional fields on the wire (notably
`stream_options.include_usage`) that the SDK schema does not declare. The
SDK exposes `extra_body` precisely for this — merge anything that looks
extra-body-shaped into it so it lands in the JSON request body.
If a caller supplies both `extra_body={"stream_options": ...}` and a
top-level `stream_options=...`, the value already in `extra_body` wins
(callers using `extra_body` are presumed to want explicit control); the
discarded top-level value is logged.
"""
extra_body = dict(kwargs.pop("extra_body", None) or {})
top_level_stream_options = kwargs.pop("stream_options", None)
if top_level_stream_options is not None:
if "stream_options" in extra_body:
logger.warning(
"Both `extra_body['stream_options']` and a top-level "
"`stream_options` were supplied; using `extra_body`'s value "
"and discarding the top-level value.",
)
else:
extra_body["stream_options"] = top_level_stream_options
if extra_body:
kwargs["extra_body"] = extra_body
return kwargs
def _completion_with_retry(
llm: ChatFireworks,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> Any:
"""Retry the sync completion call, including stream setup."""
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
kwargs = _prepare_sdk_kwargs(kwargs)
@retry_decorator
def _call() -> Any:
try:
result = llm.client.create(**kwargs)
except httpx.HTTPStatusError as e:
_promote_http_status_error(e)
if kwargs.get("stream"):
# The streaming generator is lazy — advance once so the HTTP
# connection and any transport error happen inside the retry
# boundary. `_prepend_chunk` then re-yields the consumed chunk
# ahead of the rest so callers still see every event.
try:
iterator = iter(result)
first = next(iterator)
except StopIteration:
_raise_empty_stream()
except httpx.HTTPStatusError as e:
_promote_http_status_error(e)
return _prepend_chunk(first, iterator)
return result
return _call()
async def _acompletion_with_retry(
llm: ChatFireworks,
run_manager: AsyncCallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> Any:
"""Retry the async completion call, including stream setup."""
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
kwargs = _prepare_sdk_kwargs(kwargs)
@retry_decorator
async def _call() -> Any:
if kwargs.get("stream"):
try:
# 1.x async `create()` is a coroutine that resolves to an
# `AsyncStream` when `stream=True`. Await it, then advance the
# async iterator once inside the retry boundary so transport
# errors surface here rather than at first downstream consumer.
result = await llm.async_client.create(**kwargs)
agen = result.__aiter__()
first = await agen.__anext__()
except StopAsyncIteration:
_raise_empty_stream()
except httpx.HTTPStatusError as e:
_promote_http_status_error(e)
return _aprepend_chunk(first, agen)
try:
return await llm.async_client.create(**kwargs)
except httpx.HTTPStatusError as e:
_promote_http_status_error(e)
return await _call()
def _prepend_chunk(first: Any, rest: Iterator[Any]) -> Iterator[Any]:
yield first
yield from rest
async def _aprepend_chunk(first: Any, rest: AsyncIterator[Any]) -> AsyncIterator[Any]:
yield first
async for item in rest:
yield item
class ChatFireworks(BaseChatModel):
"""`Fireworks` Chat large language models API.
To use, you should have the
environment variable `FIREWORKS_API_KEY` set with your API key.
Any parameters that are valid to be passed to the fireworks.create call
can be passed in, even if not explicitly saved on this class.
Example:
```python
from langchain_fireworks.chat_models import ChatFireworks
model = ChatFireworks(model_name="accounts/fireworks/models/gpt-oss-120b")
```
Fireworks request headers can be passed with `extra_headers`. For prompt
caching, `x-session-affinity` pins requests to a replica so related calls can
reuse the same prompt-cache session:
```python
model.invoke(
"Hello",
extra_headers={"x-session-affinity": "user-42"},
)
```
The Fireworks SDK also accepts a typed `prompt_cache_key` field (passed as a
regular keyword argument), which it treats as the preferred alternative to
the raw `x-session-affinity` header:
```python
model.invoke("Hello", prompt_cache_key="user-42")
```
"""
@property
def lc_secrets(self) -> dict[str, str]:
return {"fireworks_api_key": "FIREWORKS_API_KEY"}
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "chat_models", "fireworks"]`
"""
return ["langchain", "chat_models", "fireworks"]
@property
def lc_attributes(self) -> dict[str, Any]:
attributes: dict[str, Any] = {}
if self.fireworks_api_base:
attributes["fireworks_api_base"] = self.fireworks_api_base
return attributes
@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this model can be serialized by LangChain."""
return True
client: Any = Field(default=None, exclude=True)
"""Internal `fireworks.Fireworks().chat.completions` resource.
Constructed with `max_retries=0` so retries are owned by
`_create_retry_decorator` (which surfaces each attempt to the LangChain
`run_manager`). Callers reaching for this directly should set their own
retry layer.
"""
async_client: Any = Field(default=None, exclude=True)
"""Internal `fireworks.AsyncFireworks().chat.completions` resource.
Constructed with `max_retries=0`; see `client`.
"""
_sdk_client: Any = PrivateAttr(default=None)
"""Owning `fireworks.Fireworks` instance, retained so `close()` can call
into the underlying HTTPX client. The 1.x SDK does not expose lifecycle
methods on the `chat.completions` resource itself.
"""
_async_sdk_client: Any = PrivateAttr(default=None)
"""Owning `fireworks.AsyncFireworks` instance; see `_sdk_client`."""
model_name: str = Field(alias="model")
"""Model name to use."""
@property
def model(self) -> str:
"""Same as model_name."""
return self.model_name
temperature: float | None = None
"""What sampling temperature to use."""
stop: str | list[str] | None = Field(default=None, alias="stop_sequences")
"""Default stop sequences."""
model_kwargs: dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
fireworks_api_key: SecretStr = Field(
alias="api_key",
default_factory=lambda: SecretStr(
(
os.getenv("LANGSMITH_GATEWAY_API_KEY")
if _resolve_gateway_base_url() is not None
else None
)
or (
"langsmith-gateway-oauth"
if _resolve_gateway_base_url() is not None
and os.getenv("LANGSMITH_GATEWAY_OAUTH_TOKEN") is not None
else None
)
or secret_from_env(
"FIREWORKS_API_KEY",
error_message=(
"You must specify an api key. "
"You can pass it an argument as `api_key=...` or "
"set the environment variable `FIREWORKS_API_KEY`."
),
)().get_secret_value()
),
)
"""Fireworks API key.
Automatically read from env variable `FIREWORKS_API_KEY` if not provided.
If `LANGSMITH_GATEWAY` is enabled, `LANGSMITH_GATEWAY_API_KEY` takes precedence.
"""
fireworks_api_base: str | None = Field(
alias="base_url",
default_factory=lambda: (
_resolve_gateway_base_url()
or from_env("FIREWORKS_API_BASE", default=None)()
),
)
"""Base URL path for API requests, leave blank if not using a proxy or service
emulator.
If `LANGSMITH_GATEWAY` is set, it takes precedence over `FIREWORKS_API_BASE`.
"""
langsmith_gateway_oauth_token: SecretStr | None = Field(
default_factory=secret_from_env("LANGSMITH_GATEWAY_OAUTH_TOKEN", default=None),
exclude=True,
)
"""OAuth token used to authenticate this client to LangSmith Gateway.
When set, the token is sent as an `Authorization` bearer credential and is
never passed to Fireworks as an API key.
"""
request_timeout: float | tuple[float, float] | Any | None = Field(
default=None, alias="timeout"
)
"""Timeout for requests to Fireworks completion API. Can be `float`,
`httpx.Timeout` or `None`.
"""
streaming: bool = False
"""Whether to stream the results or not."""
stream_usage: bool = True
"""Whether to include usage metadata in streaming output.
If `True`, a final empty-content chunk carrying `usage_metadata` is emitted
during the stream. Set to `False` if the upstream model/proxy rejects
`stream_options`, or pass `stream_options` explicitly via `model_kwargs` or
a runtime kwarg to override.
!!! version-added "Added in `langchain-fireworks` 1.2.0"
!!! warning "Behavior changed in `langchain-fireworks` 1.2.0"
Streaming now opts into `stream_options.include_usage` by default, and
the final empty-`choices` chunk is surfaced as an `AIMessageChunk` with
`usage_metadata` instead of being silently dropped.
"""
n: int = 1
"""Number of chat completions to generate for each prompt."""
max_tokens: int | None = None
"""Maximum number of tokens to generate."""
max_retries: int | None = 2
"""Maximum number of retries after the initial attempt when generating.
Retries use exponential backoff and trigger on transient errors:
`RateLimitError`, `APIConnectionError` (including its `APITimeoutError`
subclass), 5xx responses (including those that surface as
`httpx.HTTPStatusError` rather than typed SDK errors), and underlying
transport errors (`httpx.TimeoutException`, `httpx.TransportError`).
A value of `None` or `0` disables retries.
"""
service_tier: str | None = None
"""Service tier for the request.
Forwarded as the `service_tier` field on the Fireworks chat completions
request when set. Pass `'priority'` to opt into Fireworks' priority tier;
leave as `None` to use the default tier.
To use Fireworks' fast mode instead, select a fast-routed `model`; fast mode
is not controlled by this field. See Fireworks'
[serverless product docs](https://docs.fireworks.ai/guides/serverless-products)
for the current list of fast routers and tiers.
!!! version-added "Added in `langchain-fireworks` 1.3.0"
"""
model_config = ConfigDict(
populate_by_name=True,
)
@model_validator(mode="before")
@classmethod
def build_extra(cls, values: dict[str, Any]) -> Any:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = get_pydantic_field_names(cls)
return _build_model_kwargs(values, all_required_field_names)
@model_validator(mode="after")
def _set_fireworks_chat_version(self) -> Self:
"""Set package version in metadata."""
self._add_version("langchain-fireworks", __version__)
return self
@model_validator(mode="after")
def validate_environment(self) -> Self:
"""Validate that api key and python package exists in environment."""
if self.n < 1:
msg = "n must be at least 1."
raise ValueError(msg)
if self.n > 1 and self.streaming:
msg = "n must be 1 when streaming."
raise ValueError(msg)
api_key = self.fireworks_api_key.get_secret_value()
base_url = self.fireworks_api_base
# 0.x accepted a `(connect, read)` tuple. 1.x's SDK only accepts a
# float, `httpx.Timeout`, or `None` — normalize so existing user code
# keeps working.
if isinstance(self.request_timeout, tuple):
connect, read = self.request_timeout
timeout: Any = httpx.Timeout(read, connect=connect)
else:
timeout = self.request_timeout
# `langchain-fireworks` owns retry/backoff via `_create_retry_decorator`
# so the LangChain `run_manager` sees each attempt. Suppress the
# SDK's built-in retry layer to avoid double-retrying.
if not self.client:
http_client = self._gateway_oauth_http_client()
self._sdk_client = Fireworks(
api_key=api_key,
base_url=base_url,
timeout=timeout,
max_retries=0,
http_client=http_client,
)
self.client = self._sdk_client.chat.completions
if not self.async_client:
http_async_client = self._gateway_oauth_async_http_client()
self._async_sdk_client = AsyncFireworks(
api_key=api_key,
base_url=base_url,
timeout=timeout,
max_retries=0,
http_client=http_async_client,
)
self.async_client = self._async_sdk_client.chat.completions
return self
def _is_langsmith_gateway(self) -> bool:
"""Return whether this instance is configured to use LangSmith Gateway."""
return self.fireworks_api_base == _resolve_gateway_base_url()
def _gateway_oauth_http_client(self) -> httpx.Client | None:
"""Build a synchronous OAuth client when Gateway OAuth is enabled."""
if (
self.langsmith_gateway_oauth_token is None
or not self._is_langsmith_gateway()
):
return None
return httpx.Client(
auth=LangSmithGatewayOAuth(
self.langsmith_gateway_oauth_token.get_secret_value()
)
)
def _gateway_oauth_async_http_client(self) -> httpx.AsyncClient | None:
"""Build an asynchronous OAuth client when Gateway OAuth is enabled."""
if (
self.langsmith_gateway_oauth_token is None
or not self._is_langsmith_gateway()
):
return None
return httpx.AsyncClient(
auth=LangSmithGatewayOAuth(
self.langsmith_gateway_oauth_token.get_secret_value()
)
)
def close(self) -> None:
"""Close the underlying sync HTTP client.
After calling, sync invocations on this model will raise. Async
invocations remain available until `aclose()` is also called. Safe to
call multiple times.
"""
if self._sdk_client is not None:
self._sdk_client.close()
async def aclose(self) -> None:
"""Close the underlying async HTTP client.
Releases the aiohttp-backed connector that the 1.x SDK uses by
default. Without this, transient `ChatFireworks` instances can leak
an `Unclosed connector` warning at GC if the event loop has already
stopped. Safe to call multiple times.
"""
if self._async_sdk_client is not None:
await self._async_sdk_client.close()
def _resolve_model_profile(self) -> ModelProfile | None:
return _get_default_model_profile(self.model_name) or None
@property
def _default_params(self) -> dict[str, Any]: