de-francophones commited on
Commit
6d81bd9
·
verified ·
1 Parent(s): 5a9976d

Add languages tag

Browse files
Files changed (1) hide show
  1. README.md +406 -287
README.md CHANGED
@@ -1,288 +1,407 @@
1
- ---
2
- tags:
3
- - unsloth
4
- base_model:
5
- - Qwen/Qwen3-1.7B
6
- ---
7
- # Qwen3-1.7B
8
-
9
- ## Qwen3 Highlights
10
-
11
- Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
12
-
13
- - **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
14
- - **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
15
- - **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
16
- - **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
17
- - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
18
-
19
- ## Model Overview
20
-
21
- **Qwen3-1.7B** has the following features:
22
- - Type: Causal Language Models
23
- - Training Stage: Pretraining & Post-training
24
- - Number of Parameters: 1.7B
25
- - Number of Paramaters (Non-Embedding): 1.4B
26
- - Number of Layers: 28
27
- - Number of Attention Heads (GQA): 16 for Q and 8 for KV
28
- - Context Length: 32,768
29
-
30
- For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
31
-
32
- ## Quickstart
33
-
34
- The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
35
-
36
- With `transformers<4.51.0`, you will encounter the following error:
37
- ```
38
- KeyError: 'qwen3'
39
- ```
40
-
41
- The following contains a code snippet illustrating how to use the model generate content based on given inputs.
42
- ```python
43
- from transformers import AutoModelForCausalLM, AutoTokenizer
44
-
45
- model_name = "Qwen/Qwen3-1.7B"
46
-
47
- # load the tokenizer and the model
48
- tokenizer = AutoTokenizer.from_pretrained(model_name)
49
- model = AutoModelForCausalLM.from_pretrained(
50
- model_name,
51
- torch_dtype="auto",
52
- device_map="auto"
53
- )
54
-
55
- # prepare the model input
56
- prompt = "Give me a short introduction to large language model."
57
- messages = [
58
- {"role": "user", "content": prompt}
59
- ]
60
- text = tokenizer.apply_chat_template(
61
- messages,
62
- tokenize=False,
63
- add_generation_prompt=True,
64
- enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
65
- )
66
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
67
-
68
- # conduct text completion
69
- generated_ids = model.generate(
70
- **model_inputs,
71
- max_new_tokens=32768
72
- )
73
- output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
74
-
75
- # parsing thinking content
76
- try:
77
- # rindex finding 151668 (</think>)
78
- index = len(output_ids) - output_ids[::-1].index(151668)
79
- except ValueError:
80
- index = 0
81
-
82
- thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
83
- content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
84
-
85
- print("thinking content:", thinking_content)
86
- print("content:", content)
87
- ```
88
-
89
- For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
90
- - vLLM:
91
- ```shell
92
- vllm serve Qwen/Qwen3-1.7B --enable-reasoning --reasoning-parser deepseek_r1
93
- ```
94
- - SGLang:
95
- ```shell
96
- python -m sglang.launch_server --model-path Qwen/Qwen3-1.7B --reasoning-parser deepseek-r1
97
- ```
98
-
99
- ## Switching Between Thinking and Non-Thinking Mode
100
-
101
- > [!TIP]
102
- > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
103
- > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
104
-
105
- ### `enable_thinking=True`
106
-
107
- By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
108
-
109
- ```python
110
- text = tokenizer.apply_chat_template(
111
- messages,
112
- tokenize=False,
113
- add_generation_prompt=True,
114
- enable_thinking=True # True is the default value for enable_thinking
115
- )
116
- ```
117
-
118
- In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
119
-
120
- > [!NOTE]
121
- > For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
122
-
123
-
124
- ### `enable_thinking=False`
125
-
126
- We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
127
-
128
- ```python
129
- text = tokenizer.apply_chat_template(
130
- messages,
131
- tokenize=False,
132
- add_generation_prompt=True,
133
- enable_thinking=False # Setting enable_thinking=False disables thinking mode
134
- )
135
- ```
136
-
137
- In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
138
-
139
- > [!NOTE]
140
- > For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
141
-
142
- ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
143
-
144
- We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
145
-
146
- Here is an example of a multi-turn conversation:
147
-
148
- ```python
149
- from transformers import AutoModelForCausalLM, AutoTokenizer
150
-
151
- class QwenChatbot:
152
- def __init__(self, model_name="Qwen/Qwen3-1.7B"):
153
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
154
- self.model = AutoModelForCausalLM.from_pretrained(model_name)
155
- self.history = []
156
-
157
- def generate_response(self, user_input):
158
- messages = self.history + [{"role": "user", "content": user_input}]
159
-
160
- text = self.tokenizer.apply_chat_template(
161
- messages,
162
- tokenize=False,
163
- add_generation_prompt=True
164
- )
165
-
166
- inputs = self.tokenizer(text, return_tensors="pt")
167
- response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
168
- response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
169
-
170
- # Update history
171
- self.history.append({"role": "user", "content": user_input})
172
- self.history.append({"role": "assistant", "content": response})
173
-
174
- return response
175
-
176
- # Example Usage
177
- if __name__ == "__main__":
178
- chatbot = QwenChatbot()
179
-
180
- # First input (without /think or /no_think tags, thinking mode is enabled by default)
181
- user_input_1 = "How many r's in strawberries?"
182
- print(f"User: {user_input_1}")
183
- response_1 = chatbot.generate_response(user_input_1)
184
- print(f"Bot: {response_1}")
185
- print("----------------------")
186
-
187
- # Second input with /no_think
188
- user_input_2 = "Then, how many r's in blueberries? /no_think"
189
- print(f"User: {user_input_2}")
190
- response_2 = chatbot.generate_response(user_input_2)
191
- print(f"Bot: {response_2}")
192
- print("----------------------")
193
-
194
- # Third input with /think
195
- user_input_3 = "Really? /think"
196
- print(f"User: {user_input_3}")
197
- response_3 = chatbot.generate_response(user_input_3)
198
- print(f"Bot: {response_3}")
199
- ```
200
-
201
- > **Note**
202
- > For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
203
- > When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
204
-
205
- ## Agentic Use
206
-
207
- Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
208
-
209
- To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
210
- ```python
211
- from qwen_agent.agents import Assistant
212
-
213
- # Define LLM
214
- llm_cfg = {
215
- 'model': 'Qwen3-1.7B',
216
-
217
- # Use the endpoint provided by Alibaba Model Studio:
218
- # 'model_type': 'qwen_dashscope',
219
- # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
220
-
221
- # Use a custom endpoint compatible with OpenAI API:
222
- 'model_server': 'http://localhost:8000/v1', # api_base
223
- 'api_key': 'EMPTY',
224
-
225
- # Other parameters:
226
- # 'generate_cfg': {
227
- # # Add: When the response content is `<think>this is the thought</think>this is the answer;
228
- # # Do not add: When the response has been separated by reasoning_content and content.
229
- # 'thought_in_content': True,
230
- # },
231
- }
232
-
233
- # Define Tools
234
- tools = [
235
- {'mcpServers': { # You can specify the MCP configuration file
236
- 'time': {
237
- 'command': 'uvx',
238
- 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
239
- },
240
- "fetch": {
241
- "command": "uvx",
242
- "args": ["mcp-server-fetch"]
243
- }
244
- }
245
- },
246
- 'code_interpreter', # Built-in tools
247
- ]
248
-
249
- # Define Agent
250
- bot = Assistant(llm=llm_cfg, function_list=tools)
251
-
252
- # Streaming generation
253
- messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
254
- for responses in bot.run(messages=messages):
255
- pass
256
- print(responses)
257
- ```
258
-
259
- ## Best Practices
260
-
261
- To achieve optimal performance, we recommend the following settings:
262
-
263
- 1. **Sampling Parameters**:
264
- - For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
265
- - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
266
- - For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
267
-
268
- 2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
269
-
270
- 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
271
- - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
272
- - **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
273
-
274
- 4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
275
-
276
- ### Citation
277
-
278
- If you find our work helpful, feel free to give us a cite.
279
-
280
- ```
281
- @misc{qwen3,
282
- title = {Qwen3},
283
- url = {https://qwenlm.github.io/blog/qwen3/},
284
- author = {Qwen Team},
285
- month = {April},
286
- year = {2025}
287
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  ```
 
1
+ ---
2
+ tags:
3
+ - unsloth
4
+ base_model:
5
+ - Qwen/Qwen3-1.7B
6
+ language:
7
+ - eng
8
+ - fra
9
+ - por
10
+ - deu
11
+ - ron
12
+ - swe
13
+ - dan
14
+ - bul
15
+ - rus
16
+ - ces
17
+ - ell
18
+ - ukr
19
+ - spa
20
+ - nld
21
+ - slk
22
+ - hrv
23
+ - pol
24
+ - lit
25
+ - nob
26
+ - nno
27
+ - fas
28
+ - slv
29
+ - guj
30
+ - lav
31
+ - ita
32
+ - oci
33
+ - nep
34
+ - mar
35
+ - bel
36
+ - srp
37
+ - ltz
38
+ - vec
39
+ - asm
40
+ - cym
41
+ - szl
42
+ - ast
43
+ - hne
44
+ - awa
45
+ - mai
46
+ - bho
47
+ - snd
48
+ - gle
49
+ - fao
50
+ - hin
51
+ - pan
52
+ - ben
53
+ - ori
54
+ - tgk
55
+ - ydd
56
+ - lmo
57
+ - lij
58
+ - scn
59
+ - fur
60
+ - srd
61
+ - glg
62
+ - cat
63
+ - isl
64
+ - als
65
+ - lim
66
+ - prs
67
+ - afr
68
+ - mkd
69
+ - sin
70
+ - urd
71
+ - mag
72
+ - bos
73
+ - hye
74
+ - zho
75
+ - yue
76
+ - mya
77
+ - ara
78
+ - ars
79
+ - apc
80
+ - arz
81
+ - ary
82
+ - acm
83
+ - acq
84
+ - aeb
85
+ - heb
86
+ - mlt
87
+ - ind
88
+ - zsm
89
+ - tgl
90
+ - ceb
91
+ - jav
92
+ - sun
93
+ - min
94
+ - ban
95
+ - bjn
96
+ - pag
97
+ - ilo
98
+ - war
99
+ - tam
100
+ - tel
101
+ - kan
102
+ - mal
103
+ - tur
104
+ - azj
105
+ - uzn
106
+ - kaz
107
+ - bak
108
+ - tat
109
+ - tha
110
+ - lao
111
+ - fin
112
+ - est
113
+ - hun
114
+ - vie
115
+ - khm
116
+ - jpn
117
+ - kor
118
+ - kat
119
+ - eus
120
+ - hat
121
+ - pap
122
+ - kea
123
+ - tpi
124
+ - swa
125
+ ---
126
+ # Qwen3-1.7B
127
+
128
+ ## Qwen3 Highlights
129
+
130
+ Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
131
+
132
+ - **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
133
+ - **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
134
+ - **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
135
+ - **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
136
+ - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
137
+
138
+ ## Model Overview
139
+
140
+ **Qwen3-1.7B** has the following features:
141
+ - Type: Causal Language Models
142
+ - Training Stage: Pretraining & Post-training
143
+ - Number of Parameters: 1.7B
144
+ - Number of Paramaters (Non-Embedding): 1.4B
145
+ - Number of Layers: 28
146
+ - Number of Attention Heads (GQA): 16 for Q and 8 for KV
147
+ - Context Length: 32,768
148
+
149
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
150
+
151
+ ## Quickstart
152
+
153
+ The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
154
+
155
+ With `transformers<4.51.0`, you will encounter the following error:
156
+ ```
157
+ KeyError: 'qwen3'
158
+ ```
159
+
160
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
161
+ ```python
162
+ from transformers import AutoModelForCausalLM, AutoTokenizer
163
+
164
+ model_name = "Qwen/Qwen3-1.7B"
165
+
166
+ # load the tokenizer and the model
167
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
168
+ model = AutoModelForCausalLM.from_pretrained(
169
+ model_name,
170
+ torch_dtype="auto",
171
+ device_map="auto"
172
+ )
173
+
174
+ # prepare the model input
175
+ prompt = "Give me a short introduction to large language model."
176
+ messages = [
177
+ {"role": "user", "content": prompt}
178
+ ]
179
+ text = tokenizer.apply_chat_template(
180
+ messages,
181
+ tokenize=False,
182
+ add_generation_prompt=True,
183
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
184
+ )
185
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
186
+
187
+ # conduct text completion
188
+ generated_ids = model.generate(
189
+ **model_inputs,
190
+ max_new_tokens=32768
191
+ )
192
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
193
+
194
+ # parsing thinking content
195
+ try:
196
+ # rindex finding 151668 (</think>)
197
+ index = len(output_ids) - output_ids[::-1].index(151668)
198
+ except ValueError:
199
+ index = 0
200
+
201
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
202
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
203
+
204
+ print("thinking content:", thinking_content)
205
+ print("content:", content)
206
+ ```
207
+
208
+ For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
209
+ - vLLM:
210
+ ```shell
211
+ vllm serve Qwen/Qwen3-1.7B --enable-reasoning --reasoning-parser deepseek_r1
212
+ ```
213
+ - SGLang:
214
+ ```shell
215
+ python -m sglang.launch_server --model-path Qwen/Qwen3-1.7B --reasoning-parser deepseek-r1
216
+ ```
217
+
218
+ ## Switching Between Thinking and Non-Thinking Mode
219
+
220
+ > [!TIP]
221
+ > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
222
+ > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
223
+
224
+ ### `enable_thinking=True`
225
+
226
+ By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
227
+
228
+ ```python
229
+ text = tokenizer.apply_chat_template(
230
+ messages,
231
+ tokenize=False,
232
+ add_generation_prompt=True,
233
+ enable_thinking=True # True is the default value for enable_thinking
234
+ )
235
+ ```
236
+
237
+ In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
238
+
239
+ > [!NOTE]
240
+ > For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
241
+
242
+
243
+ ### `enable_thinking=False`
244
+
245
+ We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
246
+
247
+ ```python
248
+ text = tokenizer.apply_chat_template(
249
+ messages,
250
+ tokenize=False,
251
+ add_generation_prompt=True,
252
+ enable_thinking=False # Setting enable_thinking=False disables thinking mode
253
+ )
254
+ ```
255
+
256
+ In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
257
+
258
+ > [!NOTE]
259
+ > For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
260
+
261
+ ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
262
+
263
+ We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
264
+
265
+ Here is an example of a multi-turn conversation:
266
+
267
+ ```python
268
+ from transformers import AutoModelForCausalLM, AutoTokenizer
269
+
270
+ class QwenChatbot:
271
+ def __init__(self, model_name="Qwen/Qwen3-1.7B"):
272
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
273
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
274
+ self.history = []
275
+
276
+ def generate_response(self, user_input):
277
+ messages = self.history + [{"role": "user", "content": user_input}]
278
+
279
+ text = self.tokenizer.apply_chat_template(
280
+ messages,
281
+ tokenize=False,
282
+ add_generation_prompt=True
283
+ )
284
+
285
+ inputs = self.tokenizer(text, return_tensors="pt")
286
+ response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
287
+ response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
288
+
289
+ # Update history
290
+ self.history.append({"role": "user", "content": user_input})
291
+ self.history.append({"role": "assistant", "content": response})
292
+
293
+ return response
294
+
295
+ # Example Usage
296
+ if __name__ == "__main__":
297
+ chatbot = QwenChatbot()
298
+
299
+ # First input (without /think or /no_think tags, thinking mode is enabled by default)
300
+ user_input_1 = "How many r's in strawberries?"
301
+ print(f"User: {user_input_1}")
302
+ response_1 = chatbot.generate_response(user_input_1)
303
+ print(f"Bot: {response_1}")
304
+ print("----------------------")
305
+
306
+ # Second input with /no_think
307
+ user_input_2 = "Then, how many r's in blueberries? /no_think"
308
+ print(f"User: {user_input_2}")
309
+ response_2 = chatbot.generate_response(user_input_2)
310
+ print(f"Bot: {response_2}")
311
+ print("----------------------")
312
+
313
+ # Third input with /think
314
+ user_input_3 = "Really? /think"
315
+ print(f"User: {user_input_3}")
316
+ response_3 = chatbot.generate_response(user_input_3)
317
+ print(f"Bot: {response_3}")
318
+ ```
319
+
320
+ > **Note**
321
+ > For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
322
+ > When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
323
+
324
+ ## Agentic Use
325
+
326
+ Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
327
+
328
+ To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
329
+ ```python
330
+ from qwen_agent.agents import Assistant
331
+
332
+ # Define LLM
333
+ llm_cfg = {
334
+ 'model': 'Qwen3-1.7B',
335
+
336
+ # Use the endpoint provided by Alibaba Model Studio:
337
+ # 'model_type': 'qwen_dashscope',
338
+ # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
339
+
340
+ # Use a custom endpoint compatible with OpenAI API:
341
+ 'model_server': 'http://localhost:8000/v1', # api_base
342
+ 'api_key': 'EMPTY',
343
+
344
+ # Other parameters:
345
+ # 'generate_cfg': {
346
+ # # Add: When the response content is `<think>this is the thought</think>this is the answer;
347
+ # # Do not add: When the response has been separated by reasoning_content and content.
348
+ # 'thought_in_content': True,
349
+ # },
350
+ }
351
+
352
+ # Define Tools
353
+ tools = [
354
+ {'mcpServers': { # You can specify the MCP configuration file
355
+ 'time': {
356
+ 'command': 'uvx',
357
+ 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
358
+ },
359
+ "fetch": {
360
+ "command": "uvx",
361
+ "args": ["mcp-server-fetch"]
362
+ }
363
+ }
364
+ },
365
+ 'code_interpreter', # Built-in tools
366
+ ]
367
+
368
+ # Define Agent
369
+ bot = Assistant(llm=llm_cfg, function_list=tools)
370
+
371
+ # Streaming generation
372
+ messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
373
+ for responses in bot.run(messages=messages):
374
+ pass
375
+ print(responses)
376
+ ```
377
+
378
+ ## Best Practices
379
+
380
+ To achieve optimal performance, we recommend the following settings:
381
+
382
+ 1. **Sampling Parameters**:
383
+ - For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
384
+ - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
385
+ - For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
386
+
387
+ 2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
388
+
389
+ 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
390
+ - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
391
+ - **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
392
+
393
+ 4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
394
+
395
+ ### Citation
396
+
397
+ If you find our work helpful, feel free to give us a cite.
398
+
399
+ ```
400
+ @misc{qwen3,
401
+ title = {Qwen3},
402
+ url = {https://qwenlm.github.io/blog/qwen3/},
403
+ author = {Qwen Team},
404
+ month = {April},
405
+ year = {2025}
406
+ }
407
  ```