Views
No views yet
[!TIP] If you encounter significant endless repetitions, please refer to the Best Practices section for optimal sampling parameters, and set thepresence_penaltyto 1.5.
transformers and we advise you to use the latest version of transformers.transformers<4.51.0, you will encounter the following error:KeyError: 'qwen3'1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_name = "Qwen/Qwen3-0.6B"
4
5# load the tokenizer and the model
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForCausalLM.from_pretrained(
8 model_name,
9 torch_dtype="auto",
10 device_map="auto"
11)
12
13# prepare the model input
14prompt = "Give me a short introduction to large language model."
15messages = [
16 {"role": "user", "content": prompt}
17]
18text = tokenizer.apply_chat_template(
19 messages,
20 tokenize=False,
21 add_generation_prompt=True,
22 enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
23)
24model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
25
26# conduct text completion
27generated_ids = model.generate(
28 **model_inputs,
29 max_new_tokens=32768
30)
31output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
32
33# parsing thinking content
34try:
35 # rindex finding 151668 (</think>)
36 index = len(output_ids) - output_ids[::-1].index(151668)
37except ValueError:
38 index = 0
39
40thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
41content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
42
43print("thinking content:", thinking_content)
44print("content:", content)sglang>=0.4.6.post1 or vllm>=0.8.5 or to create an OpenAI-compatible API endpoint:python -m sglang.launch_server --model-path Qwen/Qwen3-0.6B --reasoning-parser qwen3vllm serve Qwen/Qwen3-0.6B --enable-reasoning --reasoning-parser deepseek_r1enable_thinking=Trueenable_thinking=True or leaving it as the default value in tokenizer.apply_chat_template, the model will engage its thinking mode.1text = tokenizer.apply_chat_template(
2 messages,
3 tokenize=False,
4 add_generation_prompt=True,
5 enable_thinking=True # True is the default value for enable_thinking
6)<think>...</think> block, followed by the final response.[!NOTE] For thinking mode, useTemperature=0.6,TopP=0.95,TopK=20, andMinP=0(the default setting ingeneration_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 section.
enable_thinking=False1text = tokenizer.apply_chat_template(
2 messages,
3 tokenize=False,
4 add_generation_prompt=True,
5 enable_thinking=False # Setting enable_thinking=False disables thinking mode
6)<think>...</think> block.[!NOTE] For non-thinking mode, we suggest usingTemperature=0.7,TopP=0.8,TopK=20, andMinP=0. For more detailed guidance, please refer to the Best Practices section.
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.1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3class QwenChatbot:
4 def __init__(self, model_name="Qwen/Qwen3-0.6B"):
5 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
6 self.model = AutoModelForCausalLM.from_pretrained(model_name)
7 self.history = []
8
9 def generate_response(self, user_input):
10 messages = self.history + [{"role": "user", "content": user_input}]
11
12 text = self.tokenizer.apply_chat_template(
13 messages,
14 tokenize=False,
15 add_generation_prompt=True
16 )
17
18 inputs = self.tokenizer(text, return_tensors="pt")
19 response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
20 response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
21
22 # Update history
23 self.history.append({"role": "user", "content": user_input})
24 self.history.append({"role": "assistant", "content": response})
25
26 return response
27
28# Example Usage
29if __name__ == "__main__":
30 chatbot = QwenChatbot()
31
32 # First input (without /think or /no_think tags, thinking mode is enabled by default)
33 user_input_1 = "How many r's in strawberries?"
34 print(f"User: {user_input_1}")
35 response_1 = chatbot.generate_response(user_input_1)
36 print(f"Bot: {response_1}")
37 print("----------------------")
38
39 # Second input with /no_think
40 user_input_2 = "Then, how many r's in blueberries? /no_think"
41 print(f"User: {user_input_2}")
42 response_2 = chatbot.generate_response(user_input_2)
43 print(f"Bot: {response_2}")
44 print("----------------------")
45
46 # Third input with /think
47 user_input_3 = "Really? /think"
48 print(f"User: {user_input_3}")
49 response_3 = chatbot.generate_response(user_input_3)
50 print(f"Bot: {response_3}")[!NOTE] For API compatibility, whenenable_thinking=True, regardless of whether the user uses/thinkor/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. Whenenable_thinking=False, the soft switches are not valid. Regardless of any/thinkor/no_thinktags input by the user, the model will not generate think content and will not include a<think>...</think>block.
1from qwen_agent.agents import Assistant
2
3# Define LLM
4llm_cfg = {
5 'model': 'Qwen3-0.6B',
6
7 # Use the endpoint provided by Alibaba Model Studio:
8 # 'model_type': 'qwen_dashscope',
9 # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
10
11 # Use a custom endpoint compatible with OpenAI API:
12 'model_server': 'http://localhost:8000/v1', # api_base
13 'api_key': 'EMPTY',
14
15 # Other parameters:
16 # 'generate_cfg': {
17 # # Add: When the response content is `<think>this is the thought</think>this is the answer;
18 # # Do not add: When the response has been separated by reasoning_content and content.
19 # 'thought_in_content': True,
20 # },
21}
22
23# Define Tools
24tools = [
25 {'mcpServers': { # You can specify the MCP configuration file
26 'time': {
27 'command': 'uvx',
28 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
29 },
30 "fetch": {
31 "command": "uvx",
32 "args": ["mcp-server-fetch"]
33 }
34 }
35 },
36 'code_interpreter', # Built-in tools
37]
38
39# Define Agent
40bot = Assistant(llm=llm_cfg, function_list=tools)
41
42# Streaming generation
43messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
44for responses in bot.run(messages=messages):
45 pass
46print(responses)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.enable_thinking=False), we suggest using Temperature=0.7, TopP=0.8, TopK=20, and MinP=0.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.answer field with only the choice letter, e.g., "answer": "C"."