xinference 1.9.0__py3-none-any.whl → 1.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xinference might be problematic. Click here for more details.

Files changed (92) hide show
  1. xinference/_version.py +3 -3
  2. xinference/api/restful_api.py +415 -1
  3. xinference/constants.py +2 -0
  4. xinference/core/model.py +3 -4
  5. xinference/core/supervisor.py +29 -1
  6. xinference/core/worker.py +4 -1
  7. xinference/deploy/cmdline.py +2 -0
  8. xinference/deploy/test/test_cmdline.py +1 -1
  9. xinference/model/audio/core.py +5 -0
  10. xinference/model/audio/cosyvoice.py +0 -1
  11. xinference/model/audio/kokoro.py +1 -1
  12. xinference/model/audio/kokoro_zh.py +124 -0
  13. xinference/model/audio/model_spec.json +64 -20
  14. xinference/model/embedding/flag/core.py +5 -0
  15. xinference/model/embedding/llama_cpp/core.py +22 -19
  16. xinference/model/embedding/sentence_transformers/core.py +19 -4
  17. xinference/model/embedding/vllm/core.py +40 -8
  18. xinference/model/image/cache_manager.py +56 -0
  19. xinference/model/image/core.py +9 -0
  20. xinference/model/image/model_spec.json +116 -9
  21. xinference/model/image/stable_diffusion/core.py +141 -31
  22. xinference/model/llm/core.py +10 -0
  23. xinference/model/llm/llama_cpp/core.py +42 -40
  24. xinference/model/llm/llm_family.json +435 -23
  25. xinference/model/llm/llm_family.py +1 -0
  26. xinference/model/llm/mlx/core.py +52 -33
  27. xinference/model/llm/sglang/core.py +2 -44
  28. xinference/model/llm/tool_parsers/__init__.py +58 -0
  29. xinference/model/llm/tool_parsers/abstract_tool_parser.py +33 -0
  30. xinference/model/llm/tool_parsers/deepseek_r1_tool_parser.py +128 -0
  31. xinference/model/llm/tool_parsers/deepseek_v3_tool_parser.py +145 -0
  32. xinference/model/llm/tool_parsers/glm4_tool_parser.py +123 -0
  33. xinference/model/llm/tool_parsers/llama3_tool_parser.py +77 -0
  34. xinference/model/llm/tool_parsers/qwen_tool_parser.py +320 -0
  35. xinference/model/llm/transformers/core.py +6 -12
  36. xinference/model/llm/utils.py +128 -46
  37. xinference/model/llm/vllm/core.py +8 -61
  38. xinference/model/rerank/core.py +3 -0
  39. xinference/model/rerank/sentence_transformers/core.py +1 -1
  40. xinference/model/rerank/vllm/core.py +56 -6
  41. xinference/model/utils.py +1 -2
  42. xinference/model/video/model_spec.json +95 -1
  43. xinference/thirdparty/cosyvoice/bin/export_jit.py +3 -4
  44. xinference/thirdparty/cosyvoice/bin/export_onnx.py +49 -126
  45. xinference/thirdparty/cosyvoice/bin/{inference.py → inference_deprecated.py} +1 -0
  46. xinference/thirdparty/cosyvoice/bin/train.py +23 -3
  47. xinference/thirdparty/cosyvoice/cli/cosyvoice.py +8 -4
  48. xinference/thirdparty/cosyvoice/cli/frontend.py +4 -4
  49. xinference/thirdparty/cosyvoice/cli/model.py +53 -75
  50. xinference/thirdparty/cosyvoice/dataset/dataset.py +5 -18
  51. xinference/thirdparty/cosyvoice/dataset/processor.py +24 -25
  52. xinference/thirdparty/cosyvoice/flow/decoder.py +24 -433
  53. xinference/thirdparty/cosyvoice/flow/flow.py +6 -14
  54. xinference/thirdparty/cosyvoice/flow/flow_matching.py +33 -145
  55. xinference/thirdparty/cosyvoice/hifigan/generator.py +169 -1
  56. xinference/thirdparty/cosyvoice/llm/llm.py +108 -17
  57. xinference/thirdparty/cosyvoice/transformer/upsample_encoder.py +14 -115
  58. xinference/thirdparty/cosyvoice/utils/common.py +20 -0
  59. xinference/thirdparty/cosyvoice/utils/executor.py +8 -4
  60. xinference/thirdparty/cosyvoice/utils/file_utils.py +45 -1
  61. xinference/thirdparty/cosyvoice/utils/losses.py +37 -0
  62. xinference/thirdparty/cosyvoice/utils/mask.py +35 -1
  63. xinference/thirdparty/cosyvoice/utils/train_utils.py +24 -6
  64. xinference/thirdparty/cosyvoice/vllm/cosyvoice2.py +103 -0
  65. xinference/types.py +105 -2
  66. xinference/ui/gradio/chat_interface.py +2 -0
  67. xinference/ui/gradio/media_interface.py +353 -7
  68. xinference/ui/web/ui/build/asset-manifest.json +3 -3
  69. xinference/ui/web/ui/build/index.html +1 -1
  70. xinference/ui/web/ui/build/static/js/main.1086c759.js +3 -0
  71. xinference/ui/web/ui/build/static/js/main.1086c759.js.map +1 -0
  72. xinference/ui/web/ui/node_modules/.cache/babel-loader/3c5758bd12fa334294b1de0ff6b1a4bac8d963c45472eab9dc3e530d82aa6b3f.json +1 -0
  73. xinference/ui/web/ui/node_modules/.cache/babel-loader/a3eb18af328280b139693c9092dff2a0ef8c9a967e6c8956ceee0996611f1984.json +1 -0
  74. xinference/ui/web/ui/node_modules/.cache/babel-loader/d5c224be7081f18cba1678b7874a9782eba895df004874ff8f243f94ba79942a.json +1 -0
  75. xinference/ui/web/ui/node_modules/.cache/babel-loader/f7f18bfb539b036a6a342176dd98a85df5057a884a8da978d679f2a0264883d0.json +1 -0
  76. xinference/ui/web/ui/src/locales/en.json +2 -0
  77. xinference/ui/web/ui/src/locales/ja.json +2 -0
  78. xinference/ui/web/ui/src/locales/ko.json +2 -0
  79. xinference/ui/web/ui/src/locales/zh.json +2 -0
  80. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/METADATA +16 -12
  81. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/RECORD +86 -77
  82. xinference/ui/web/ui/build/static/js/main.4918643a.js +0 -3
  83. xinference/ui/web/ui/build/static/js/main.4918643a.js.map +0 -1
  84. xinference/ui/web/ui/node_modules/.cache/babel-loader/3d2a89f0eccc1f90fc5036c9a1d587c2120e6a6b128aae31d1db7d6bad52722b.json +0 -1
  85. xinference/ui/web/ui/node_modules/.cache/babel-loader/89179f8f51887b9167721860a12412549ff04f78162e921a7b6aa6532646deb2.json +0 -1
  86. xinference/ui/web/ui/node_modules/.cache/babel-loader/8e5cb82c2ff3299c6a44563fe6b1c5515c9750613c51bb63abee0b1d70fc5019.json +0 -1
  87. xinference/ui/web/ui/node_modules/.cache/babel-loader/9dc5cfc67dd0617b0272aeef8651f1589b2155a4ff1fd72ad3166b217089b619.json +0 -1
  88. /xinference/ui/web/ui/build/static/js/{main.4918643a.js.LICENSE.txt → main.1086c759.js.LICENSE.txt} +0 -0
  89. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/WHEEL +0 -0
  90. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/entry_points.txt +0 -0
  91. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/licenses/LICENSE +0 -0
  92. {xinference-1.9.0.dist-info → xinference-1.10.0.dist-info}/top_level.txt +0 -0
@@ -154,6 +154,7 @@ class LLMFamilyV2(BaseModel, ModelInstanceInfoMixin):
154
154
  reasoning_end_tag: Optional[str]
155
155
  cache_config: Optional[dict]
156
156
  virtualenv: Optional[VirtualEnvSettings]
157
+ tool_parser: Optional[str]
157
158
 
158
159
  class Config:
159
160
  extra = "allow"
@@ -148,6 +148,16 @@ class MLXModel(LLM):
148
148
  # to call aynsc method with asyncio.run_coroutine_threadsafe
149
149
  self._loop = loop # type: ignore
150
150
 
151
+ def _cleanup_memory(self):
152
+ import gc
153
+
154
+ import mlx.core as mx
155
+
156
+ # mandatory recycling
157
+ gc.collect()
158
+ # clear the MLX cache
159
+ mx.clear_cache()
160
+
151
161
  @property
152
162
  def driver_info(self) -> Optional[dict]:
153
163
  return self._driver_info
@@ -333,6 +343,7 @@ class MLXModel(LLM):
333
343
  self.prepare_parse_reasoning_content(
334
344
  reasoning_content, enable_thinking=enable_thinking
335
345
  )
346
+ self.prepare_parse_tool_calls()
336
347
 
337
348
  kwargs = {}
338
349
  kwargs["revision"] = self._model_config.get(
@@ -458,14 +469,18 @@ class MLXModel(LLM):
458
469
  repetition_penalty=kwargs.pop("repetition_penalty"),
459
470
  repetition_context_size=kwargs.pop("repetition_context_size"),
460
471
  )
461
- yield from stream_generate(
462
- self._model,
463
- self._tokenizer,
464
- prompt_token_ids,
465
- sampler=sampler,
466
- logits_processors=logits_processors,
467
- **kwargs,
468
- )
472
+ try:
473
+ yield from stream_generate(
474
+ self._model,
475
+ self._tokenizer,
476
+ prompt_token_ids,
477
+ sampler=sampler,
478
+ logits_processors=logits_processors,
479
+ **kwargs,
480
+ )
481
+ finally:
482
+ # after completing the inference, clear the memory.
483
+ self._cleanup_memory()
469
484
 
470
485
  def _prepare_inputs(
471
486
  self, prompt: Union[str, Dict[str, Any]], kwargs
@@ -755,7 +770,7 @@ class MLXChatModel(MLXModel, ChatModelMixin):
755
770
  assert not isinstance(c, Iterator)
756
771
  if tools:
757
772
  return self._post_process_completion(
758
- self.model_family, self.model_uid, c, self.reasoning_parser
773
+ self.model_family, self.model_uid, c
759
774
  )
760
775
  return self._to_chat_completion(c, self.reasoning_parser)
761
776
 
@@ -831,18 +846,32 @@ class MLXVisionModel(MLXModel, ChatModelMixin):
831
846
 
832
847
  detokenizer.reset()
833
848
  tic = time.perf_counter()
834
- for n, (token, logprobs) in enumerate(
835
- generate_step(input_ids, self._model, pixel_values, mask, **kwargs),
836
- ):
837
- if n == 0:
838
- prompt_time = time.perf_counter() - tic
839
- prompt_tps = len(input_ids) / prompt_time
840
- tic = time.perf_counter()
841
- if token == tokenizer.eos_token_id:
842
- break
843
- detokenizer.add_token(token)
849
+ try:
850
+ for n, (token, logprobs) in enumerate(
851
+ generate_step(input_ids, self._model, pixel_values, mask, **kwargs),
852
+ ):
853
+ if n == 0:
854
+ prompt_time = time.perf_counter() - tic
855
+ prompt_tps = len(input_ids) / prompt_time
856
+ tic = time.perf_counter()
857
+ if token == tokenizer.eos_token_id:
858
+ break
859
+ detokenizer.add_token(token)
860
+
861
+ # Yield the last segment if streaming
862
+ yield GenerationResponse(
863
+ text=detokenizer.last_segment,
864
+ token=token,
865
+ logprobs=logprobs,
866
+ from_draft=False,
867
+ prompt_tokens=len(input_ids),
868
+ prompt_tps=prompt_tps,
869
+ generation_tokens=n + 1,
870
+ generation_tps=(n + 1) / (time.perf_counter() - tic),
871
+ peak_memory=mx.metal.get_peak_memory() / 1e9,
872
+ )
844
873
 
845
- # Yield the last segment if streaming
874
+ detokenizer.finalize()
846
875
  yield GenerationResponse(
847
876
  text=detokenizer.last_segment,
848
877
  token=token,
@@ -854,19 +883,9 @@ class MLXVisionModel(MLXModel, ChatModelMixin):
854
883
  generation_tps=(n + 1) / (time.perf_counter() - tic),
855
884
  peak_memory=mx.metal.get_peak_memory() / 1e9,
856
885
  )
857
-
858
- detokenizer.finalize()
859
- yield GenerationResponse(
860
- text=detokenizer.last_segment,
861
- token=token,
862
- logprobs=logprobs,
863
- from_draft=False,
864
- prompt_tokens=len(input_ids),
865
- prompt_tps=prompt_tps,
866
- generation_tokens=n + 1,
867
- generation_tps=(n + 1) / (time.perf_counter() - tic),
868
- peak_memory=mx.metal.get_peak_memory() / 1e9,
869
- )
886
+ finally:
887
+ # after completing the inference, clear the memory
888
+ self._cleanup_memory()
870
889
 
871
890
  def _prepare_inputs(
872
891
  self, prompt: Union[str, Dict[str, Any]], kwargs
@@ -175,6 +175,7 @@ class SGLANGModel(LLM):
175
175
  self.prepare_parse_reasoning_content(
176
176
  reasoning_content, enable_thinking=enable_thinking
177
177
  )
178
+ self.prepare_parse_tool_calls()
178
179
 
179
180
  # Fix: GH#2169
180
181
  if sgl.__version__ >= "0.2.14":
@@ -646,49 +647,6 @@ class SGLANGChatModel(SGLANGModel, ChatModelMixin):
646
647
  def is_tool_call_chunk_end(chunk):
647
648
  return chunk["choices"][0]["text"].endswith(QWEN_TOOL_CALL_SYMBOLS[1])
648
649
 
649
- async def _async_to_tool_completion_chunks(
650
- self,
651
- chunks: AsyncGenerator[CompletionChunk, None],
652
- ) -> AsyncGenerator[ChatCompletionChunk, None]:
653
- i = 0
654
- previous_texts = [""]
655
- tool_call = False
656
- tool_call_texts = [""]
657
- if self.reasoning_parser:
658
- chunks = self.reasoning_parser.prepare_reasoning_content_streaming(chunks)
659
- async for chunk in chunks:
660
- if i == 0:
661
- for first_chunk in self._get_first_chat_completion_chunk(
662
- chunk, self.reasoning_parser
663
- ):
664
- yield first_chunk
665
- # usage
666
- choices = chunk.get("choices")
667
- if not choices:
668
- yield self._get_final_chat_completion_chunk(chunk)
669
- else:
670
- if self.is_tool_call_chunk_start(chunk):
671
- tool_call = True
672
- if tool_call:
673
- tool_call_text = tool_call_texts[-1]
674
- tool_call_text += chunk["choices"][0]["text"]
675
- tool_call_texts.append(tool_call_text)
676
- if self.is_tool_call_chunk_end(chunk):
677
- yield self._post_process_completion_chunk(
678
- self.model_family,
679
- self.model_uid,
680
- chunk,
681
- reasoning_parser=self.reasoning_parser,
682
- tool_call_text=tool_call_text,
683
- )
684
- tool_call = False
685
- tool_call_texts = [""]
686
- else:
687
- yield self._to_chat_completion_chunk(
688
- chunk, self.reasoning_parser, previous_texts
689
- )
690
- i += 1
691
-
692
650
  async def async_chat(
693
651
  self,
694
652
  messages: List[Dict],
@@ -731,7 +689,7 @@ class SGLANGChatModel(SGLANGModel, ChatModelMixin):
731
689
  assert not isinstance(c, AsyncGenerator)
732
690
  if tools:
733
691
  return self._post_process_completion(
734
- self.model_family, self.model_uid, c, self.reasoning_parser
692
+ self.model_family, self.model_uid, c
735
693
  )
736
694
  return self._to_chat_completion(c, self.reasoning_parser)
737
695
 
@@ -0,0 +1,58 @@
1
+ from functools import wraps
2
+ from typing import Any, Callable, Dict, Type
3
+
4
+ # Global registry for tool parsers, mapping parser names to their classes
5
+ TOOL_PARSERS: Dict[str, Type[Any]] = {}
6
+
7
+
8
+ def register_tool_parser(name: str):
9
+ """
10
+ Decorator for registering ToolParser classes to the TOOL_PARSERS registry.
11
+
12
+ This decorator allows tool parser classes to be automatically registered
13
+ when they are defined, making them available for dynamic lookup.
14
+
15
+ Args:
16
+ name (str): The name to register the tool parser under. This should
17
+ typically match the model family name (e.g., "qwen", "glm4").
18
+
19
+ Returns:
20
+ Callable: The decorator function that registers the class.
21
+
22
+ Example:
23
+ @register_tool_parser("qwen")
24
+ class QwenToolParser(ToolParser):
25
+ def parse_tool_calls(self, text: str) -> List[ToolCall]:
26
+ # Implementation for parsing Qwen model tool calls
27
+ pass
28
+
29
+ Note:
30
+ The registered class should implement the ToolParser interface
31
+ and provide methods for parsing tool calls from model outputs.
32
+ """
33
+
34
+ def decorator(cls: Type[Any]) -> Type[Any]:
35
+ """
36
+ The actual decorator that performs the registration.
37
+
38
+ Args:
39
+ cls: The tool parser class to register.
40
+
41
+ Returns:
42
+ The same class (unmodified) after registration.
43
+ """
44
+ TOOL_PARSERS[name] = cls
45
+ return cls
46
+
47
+ return decorator
48
+
49
+
50
+ # Import all tool parser modules to trigger decorator registration
51
+ # This ensures all tool parsers are automatically registered when this module is imported
52
+ from . import (
53
+ deepseek_r1_tool_parser,
54
+ deepseek_v3_tool_parser,
55
+ glm4_tool_parser,
56
+ llama3_tool_parser,
57
+ qwen_tool_parser,
58
+ )
@@ -0,0 +1,33 @@
1
+ class ToolParser:
2
+ """
3
+ Abstract ToolParser class that should not be used directly. Provided
4
+ properties and methods should be used in
5
+ derived classes.
6
+ """
7
+
8
+ def extract_tool_calls(self, model_output: str):
9
+ """
10
+ Static method that should be implemented for extracting tool calls from
11
+ a complete model-generated string.
12
+ Used for non-streaming responses where we have the entire model response
13
+ available before sending to the client.
14
+ Static because it's stateless.
15
+ """
16
+ raise NotImplementedError(
17
+ "AbstractToolParser.extract_tool_calls has not been implemented!"
18
+ )
19
+
20
+ def extract_tool_calls_streaming(
21
+ self, previous_text, current_text: str, delta_text: str
22
+ ):
23
+ """
24
+ Instance method that should be implemented for extracting tool calls
25
+ from an incomplete response; for use when handling tool calls and
26
+ streaming. Has to be an instance method because it requires state -
27
+ the current tokens/diffs, but also the information about what has
28
+ previously been parsed and extracted (see constructor)
29
+ """
30
+ raise NotImplementedError(
31
+ "AbstractToolParser.extract_tool_calls_streaming has not been "
32
+ "implemented!"
33
+ )
@@ -0,0 +1,128 @@
1
+ import json
2
+ import logging
3
+ import re
4
+ from typing import Any, List, Optional, Tuple
5
+
6
+ from . import register_tool_parser
7
+ from .abstract_tool_parser import ToolParser
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ @register_tool_parser("deepseek-r1")
13
+ class DeepseekR1ToolParser(ToolParser):
14
+ """
15
+ Tool parser implementation for DeepSeek R1 model.
16
+
17
+ This parser handles the specific format used by DeepSeek R1 for tool calls,
18
+ which includes special Unicode tokens and JSON-formatted function arguments.
19
+ """
20
+
21
+ def __init__(self):
22
+ """
23
+ Initialize the DeepSeek R1 tool parser.
24
+ """
25
+ super().__init__()
26
+ # Regex pattern to match DeepSeek R1 tool call format
27
+ self.tool_calls_regex = (
28
+ r"<\|tool▁call▁begin|>function<\|tool▁sep|>([^\n]+)\n"
29
+ r"```json\n(.*?)\n```<\|tool▁call▁end|>"
30
+ )
31
+
32
+ def extract_tool_calls(
33
+ self, model_output: str
34
+ ) -> List[Tuple[Optional[str], Optional[str], Optional[dict]]]:
35
+ """
36
+ Extract tool calls from complete model output.
37
+
38
+ Parses the model output to find tool call patterns and extracts
39
+ function names and arguments. Handles JSON parsing errors gracefully
40
+ and deduplicates identical tool calls.
41
+
42
+ Args:
43
+ model_output (str): The complete output string from the model.
44
+
45
+ Returns:
46
+ List[Tuple[Optional[str], Optional[str], Optional[dict]]]:
47
+ A list of tuples where each tuple contains:
48
+ - content (str or None): Raw content if parsing failed, None if successful
49
+ - function_name (str or None): Name of the function to call
50
+ - arguments (dict or None): Parsed function arguments
51
+
52
+ Example:
53
+ >>> parser = DeepseekR1ToolParser()
54
+ >>> output = '<|tool▁call▁begin|>function<|tool▁sep|>get_current_weather\n```json\n{"location": "上海", "unit": "celsius"}\n```<|tool▁call▁end|>'
55
+ >>> result = parser.extract_tool_calls(output)
56
+ >>> print(result)
57
+ [(None, 'get_current_weather', {'location': 'Beijing'})]
58
+ """
59
+ matches = re.findall(self.tool_calls_regex, model_output, re.DOTALL)
60
+ if not matches:
61
+ # No tool calls found, return the original output as content
62
+ return [(model_output, None, None)]
63
+
64
+ # Use set for deduplication of identical tool calls
65
+ tool_calls = set()
66
+ results: List[Tuple[Optional[str], Optional[str], Optional[dict]]] = []
67
+
68
+ for func_name, raw_json in matches:
69
+ func_and_args = None
70
+ try:
71
+ # Parse JSON arguments
72
+ func_and_args = json.loads(raw_json)
73
+ # Create hashable representation for deduplication
74
+ arguments_hashable = frozenset(func_and_args.items())
75
+ tool_call_tuple = (
76
+ None, # No content error
77
+ func_name,
78
+ func_and_args,
79
+ )
80
+ except Exception as e:
81
+ # JSON parsing failed, treat as raw content
82
+ logger.warning(
83
+ f"Failed to parse tool call JSON: {raw_json}, error: {e}"
84
+ )
85
+ tool_call_tuple = (raw_json, None, None)
86
+ arguments_hashable = None
87
+
88
+ # Create deduplication key
89
+ dedup_key = (
90
+ (func_name, arguments_hashable)
91
+ if func_and_args is not None
92
+ else raw_json
93
+ )
94
+
95
+ # Add to results if not already seen
96
+ if dedup_key not in tool_calls:
97
+ tool_calls.add(dedup_key)
98
+ results.append(tool_call_tuple)
99
+
100
+ return results
101
+
102
+ def extract_tool_calls_streaming(
103
+ self, previous_text: List[str], current_text: str, delta_text: str
104
+ ) -> Optional[Any]:
105
+ """
106
+ Extract tool calls from streaming output.
107
+
108
+ Currently not supported for DeepSeek R1 model. This method raises
109
+ a ValueError indicating that streaming tool call extraction is only
110
+ available for specific model/backend combinations.
111
+
112
+ Args:
113
+ previous_text (List[str]): Previous text chunks from the stream.
114
+ current_text (str): Current accumulated text.
115
+ delta_text (str): New text delta in this chunk.
116
+
117
+ Raises:
118
+ ValueError: Always raised as streaming is not supported.
119
+
120
+ Note:
121
+ DeepSeek R1 model does not currently support streaming tool call
122
+ extraction. Use extract_tool_calls() with complete output instead.
123
+ """
124
+ raise NotImplementedError(
125
+ "Streaming support for tool calls is available only when using "
126
+ "Qwen models with vLLM backend or GLM4-chat models without vLLM backend. "
127
+ "DeepSeek R1 does not support streaming tool call extraction."
128
+ )
@@ -0,0 +1,145 @@
1
+ import json
2
+ import logging
3
+ import re
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ from . import register_tool_parser
7
+ from .abstract_tool_parser import ToolParser
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ @register_tool_parser("deepseek-v3")
13
+ class DeepseekV3ToolParser(ToolParser):
14
+ """
15
+ Tool parser implementation for DeepSeek V3 model.
16
+
17
+ This parser handles the specific format used by DeepSeek V3 for tool calls,
18
+ which uses JSON code blocks wrapped in markdown format.
19
+
20
+ """
21
+
22
+ def __init__(self):
23
+ """
24
+ Initialize the DeepSeek V3 tool parser.
25
+ """
26
+ super().__init__()
27
+ # Regex pattern to match JSON code blocks
28
+ self.tool_calls_regex = r"\s*```json\s*(.*?)\s*```"
29
+
30
+ def _parse_json_function_call(
31
+ self,
32
+ function_call_str: str,
33
+ ) -> str:
34
+ """
35
+ Parse JSON function call from string.
36
+
37
+ Args:
38
+ function_call_str (str): The function call string to parse.
39
+
40
+ Returns:
41
+ str: Parsed result or original string if no match found.
42
+
43
+ """
44
+ match = self.tool_calls_regex.search(function_call_str)
45
+ if match:
46
+ result = match.group(1)
47
+ return result
48
+ return function_call_str
49
+
50
+ def extract_tool_calls(
51
+ self, model_output: str
52
+ ) -> List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]:
53
+ """
54
+ Extract tool calls from complete model output.
55
+
56
+ Parses the model output to find JSON code blocks containing tool calls
57
+ and extracts function names and parameters. Handles JSON parsing errors
58
+ gracefully and deduplicates identical tool calls.
59
+
60
+ Args:
61
+ model_output (str): The complete output string from the model.
62
+
63
+ Returns:
64
+ List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]:
65
+ A list of tuples where each tuple contains:
66
+ - content (str or None): Raw content if parsing failed, None if successful
67
+ - function_name (str or None): Name of the function to call
68
+ - parameters (dict or None): Function parameters
69
+
70
+ Example:
71
+ >>> parser = DeepseekV3ToolParser()
72
+ >>> output = '```json\n{"name": "get_weather", "parameters": {"location": "Beijing"}}\n```'
73
+ >>> result = parser.extract_tool_calls(output)
74
+ >>> print(result)
75
+ [(None, 'get_weather', {'location': 'Beijing'})]
76
+ """
77
+ matches = re.findall(self.tool_calls_regex, model_output, re.DOTALL)
78
+
79
+ if not matches:
80
+ # No tool calls found, return the original output as content
81
+ return [(model_output, None, None)]
82
+
83
+ # Use set for deduplication of identical tool calls
84
+ tool_calls = set()
85
+ results: List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]] = (
86
+ []
87
+ )
88
+
89
+ for raw_json in matches:
90
+ func_and_args = None
91
+ try:
92
+ # Parse JSON to extract function call information
93
+ func_and_args = json.loads(raw_json)
94
+ # Convert dictionary to frozenset for deduplication
95
+ arguments_hashable = frozenset(func_and_args["parameters"])
96
+ tool_call_tuple = (
97
+ None, # No content error
98
+ func_and_args["name"],
99
+ func_and_args["parameters"],
100
+ )
101
+ except json.JSONDecodeError:
102
+ tool_call_tuple = (
103
+ raw_json,
104
+ None,
105
+ None,
106
+ ) # If parsing fails, treat as raw content
107
+ arguments_hashable = None # No need for hashing
108
+
109
+ # Avoid duplicate entries
110
+ dedup_key = (
111
+ (func_and_args["name"], arguments_hashable)
112
+ if func_and_args is not None
113
+ else (raw_json)
114
+ )
115
+
116
+ # Add to results if not already seen
117
+ if dedup_key not in tool_calls:
118
+ tool_calls.add(dedup_key)
119
+ results.append(tool_call_tuple)
120
+
121
+ return results
122
+
123
+ def extract_tool_calls_streaming(
124
+ self, previous_text: List[str], current_text: str, delta_text: str
125
+ ) -> Optional[Any]:
126
+ """
127
+ Extract tool calls from streaming output.
128
+
129
+ Currently not supported for DeepSeek V3 model. This method raises
130
+ a ValueError indicating that streaming tool call extraction is only
131
+ available for specific model/backend combinations.
132
+
133
+ Args:
134
+ previous_text (List[str]): Previous text chunks from the stream.
135
+ current_text (str): Current accumulated text.
136
+ delta_text (str): New text delta in this chunk.
137
+
138
+ Raises:
139
+ ValueError: Always raised as streaming is not supported.
140
+ """
141
+ raise NotImplementedError(
142
+ "Streaming support for tool calls is available only when using "
143
+ "Qwen models with vLLM backend or GLM4-chat models without vLLM backend. "
144
+ "DeepSeek V3 does not support streaming tool call extraction."
145
+ )
@@ -0,0 +1,123 @@
1
+ import json
2
+ import logging
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ from . import register_tool_parser
6
+ from .abstract_tool_parser import ToolParser
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ @register_tool_parser("glm4")
12
+ class Glm4ToolParser(ToolParser):
13
+ """
14
+ Tool parser implementation for GLM4 model.
15
+
16
+ This parser handles the specific format used by GLM4 for tool calls,
17
+ which uses JSON code blocks wrapped in markdown format.
18
+
19
+ """
20
+
21
+ def __init__(self):
22
+ """
23
+ Initialize the GLM4 tool parser.
24
+ """
25
+ super().__init__()
26
+ # Regex pattern to match JSON code blocks
27
+ self.tool_calls_regex = r"\s*```json\s*(.*?)\s*```"
28
+
29
+ def _parse_json_function_call(
30
+ self,
31
+ function_call_str: str,
32
+ ) -> str:
33
+ """
34
+ Parse JSON function call from string.
35
+
36
+ Args:
37
+ function_call_str (str): The function call string to parse.
38
+
39
+ Returns:
40
+ str: Parsed result or original string if no match found.
41
+
42
+ """
43
+ match = self.tool_calls_regex.search(function_call_str)
44
+ if match:
45
+ result = match.group(1)
46
+ return result
47
+ return function_call_str
48
+
49
+ def extract_tool_calls(
50
+ self, model_output: str
51
+ ) -> List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]:
52
+ """
53
+ Extract tool calls from complete model output.
54
+
55
+ Parses the model output to find JSON code blocks containing tool calls
56
+ and extracts function names and parameters. Handles JSON parsing errors
57
+ gracefully and deduplicates identical tool calls.
58
+
59
+ Args:
60
+ model_output (str): The complete output string from the model.
61
+
62
+ Returns:
63
+ List[Tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]]:
64
+ A list of tuples where each tuple contains:
65
+ - content (str or None): Raw content if parsing failed, None if successful
66
+ - function_name (str or None): Name of the function to call
67
+ - parameters (dict or None): Function parameters
68
+
69
+ Example:
70
+ >>> parser = Glm4ToolParser()
71
+ >>> output = {"name": "get_weather", "parameters": {"location": "Beijing"}}
72
+ >>> result = parser.extract_tool_calls(output)
73
+ >>> print(result)
74
+ [(None, 'get_weather', {'location': 'Beijing'})]
75
+ """
76
+ try:
77
+ if isinstance(model_output, dict):
78
+ try:
79
+ return [
80
+ (
81
+ None,
82
+ model_output["name"],
83
+ json.loads(model_output["arguments"]),
84
+ )
85
+ ]
86
+ except Exception:
87
+ return [(None, model_output["name"], model_output["arguments"])]
88
+ except KeyError:
89
+ logger.error("Can't parse glm output: %s", model_output)
90
+ return [(str(model_output), None, None)]
91
+ else:
92
+ return [(str(model_output), None, None)]
93
+
94
+ def extract_tool_calls_streaming(
95
+ self, previous_text: List[str], current_text: str, delta_text: str
96
+ ) -> Optional[Any]:
97
+ """
98
+ Extract tool calls from streaming output.
99
+
100
+ Currently has limited support for GLM4 model streaming. This method raises
101
+ a ValueError indicating that streaming tool call extraction is only
102
+ available for specific model/backend combinations.
103
+
104
+ Args:
105
+ previous_text (List[str]): Previous text chunks from the stream.
106
+ current_text (str): Current accumulated text.
107
+ delta_text (str): New text delta in this chunk.
108
+ """
109
+ try:
110
+ if isinstance(current_text, dict):
111
+ try:
112
+ return (
113
+ None,
114
+ current_text["name"],
115
+ json.loads(current_text["arguments"]),
116
+ )
117
+ except Exception:
118
+ return (None, current_text["name"], current_text["arguments"])
119
+ except KeyError:
120
+ logger.error("Can't parse glm output: %s", current_text)
121
+ return (str(current_text), None, None)
122
+ else:
123
+ return (str(current_text), None, None)