Building a coding chatbot with DeepSeek R1

Working with DeepSeek in Python

James Chapman

Curriculum Manager, DataCamp

Current approach

All of the input and output is stored to be sent with the next message.

Working with DeepSeek in Python

Problems with reasoning

Reasoning outputs consist of thoughts and a final response.

Working with DeepSeek in Python

Problems with reasoning

Best practices dictates that reasoning inputs should be short.

Working with DeepSeek in Python

Problems with reasoning

Storing thoughts in the conversation history increases cost, runtimes, and will likely degrade performance.

Working with DeepSeek in Python

The reasoning approach

Trimming the thoughts from the first model output.

Working with DeepSeek in Python

The reasoning approach

Trimming the thoughts from the second model output.

Working with DeepSeek in Python

Trimming thoughts

Extract thinking tokens

import re

match = re.search(r'<think>(.*?)<\/think>', response_content, re.DOTALL)
think_content = match.group(1).strip()
print(think_content)

Remove thinking tokens

final_response = re.sub(r'<think>[\s\S]*?<\/think>\s*', '', response_content, re.DOTALL)
print(final_response.strip())
Working with DeepSeek in Python

Coding a reasoning chatbot

  • "system" messages shouldn't be used with reasoning models
messages = []
user_msgs = [code_to_debug, follow_up]
for q in user_qs:
    user_dict = {"role": "user", "content": q}
    messages.append(user_dict)

    response = client.chat.completions.create(model="deepseek-ai/DeepSeek-R1", messages=messages)


final_response = re.sub(r'<think>[\s\S]*?<\/think>\s*', '', response.choices[0].message.content, re.DOTALL) assistant_dict = {"role": "assistant", "content": final_response.strip()}
messages.append(assistant_dict)
Working with DeepSeek in Python

Let's practice!

Working with DeepSeek in Python

Preparing Video For Download...