Python
print("Hello! 👋")- 1
- This is a simple Python command that prints the text “Hello” to the console. The output appears below the code block.
Hello! 👋
To run or modify the example code yourself, you can open and download the Jupyter notebook underlying this page via the sidebar.
No problem! Explanations for the individual steps of the code are hidden behind the numbers on the right. Simply hover your mouse over the number to see the explanation. Where the respective code is executed (in Python, R, or the terminal) is shown in the header of the code block.
Regardless of the model used, we first load the already-installed packages as well as our text data, and store it in a list object:
Unlike category-specific models, universal decoder models let us classify any category we like. As an example, we use the Qwen2.5 model (Bai et al., 2025) — a small, instruction-tuned model that runs comfortably on a laptop CPU.
Instead of the model used here, you can also use other universal decoder models (usually labeled for “Text Generation”) for different languages and use cases. An overview of available models can be found on Hugging Face. Make sure that the chosen model is suitable for your specific task (e.g. sentiment analysis, topic classification, etc.) and supports the language of your texts.
Unlike the previous approaches, with a universal decoder model we need to write a prompt, based on which the model generates text (i.e. the answer to our classification request), ideally in a machine-readable format. The prompt could, for example, read: “You are a trained assistant for content analysis who determines whether a text expresses fear. Always answer precisely in JSON format with fear (true or false) and reasoning (a short justification in English). Return only the JSON response, starting with ‘{’ and ending with ‘}’, with these two parameters.” We now apply this prompt iteratively to each text in our dataset. The easiest way to do this is with a for loop.
Using the max_new_tokens parameter, we can limit the length of the generated output; do_sample should generally be set to False to get deterministic, and therefore reproducible, answers.
Python
results = []
for text in textlist:
instructions = [
{"role": "system",
"content": "You are a trained assistant for content analysis who determines whether a text expresses fear. Always answer precisely in JSON format with fear (true or false) and reasoning (a short justification in English). Return only the JSON response, starting with '{' and ending with '}', with these two parameters"},
{"role": "user", "content": text}]
outputs = generate(instructions, max_new_tokens=256, do_sample=False)
results.append({"text": text, "response": outputs[0]["generated_text"][-1]['content']})Once all responses have been generated, we can extract the results from the JSON format. If we want, we can also save the additional reasoning that is output, to look at it.
It can occasionally happen that the model returns malformed JSON — for instance by “forgetting” quotation marks, wrapping the JSON in a ```json markdown code fence despite being told to return only the JSON object, or because responses are cut off once max_new_tokens is reached, so they don’t close with a curly brace. Our parsing function below strips a code fence if present, and otherwise fails gracefully rather than crashing.
def parse_response(response):
response = response.strip().strip("`").removeprefix("json").strip()
try:
parsed = json.loads(response)
return parsed['fear'], parsed['reasoning']
except (json.JSONDecodeError, KeyError):
return None, None
parsed_data = [(entry['text'], *parse_response(entry['response'])) for entry in results]
parsed_data = pd.DataFrame(parsed_data, columns=['text', 'fear', 'reasoning'])
print(parsed_data)```json / ``` markdown code fence if the model added one, since it otherwise returns clean JSON here
None for both fields instead of crashing
text fear \
0 I feel helpless and afraid like never before True
1 No commute; sunny day; my kids laughing; being... False
2 Feeling scared and lonely, can't wait for this... True
3 It's gonna get tougher but we will get through... False
4 I am terrified by what is happening. I’m scare... True
5 Stay inside, stay safe, and this madness will ... False
6 I am scared that I will get sick and die, and ... True
7 Feeling relaxed and happy but I understand tha... False
8 I am very scared and worried about contracting... True
9 I'm confident we will get through this crisis. False
reasoning
0 The statement expresses feelings of helplessne...
1 The text describes positive experiences such a...
2 The text expresses feelings of being scared an...
3 The statement suggests perseverance and determ...
4 The text expresses clear concern about potenti...
5 The text advises people to stay indoors and be...
6 The text expresses clear concern about contrac...
7 The text does not express any fear; instead, i...
8 The statement expresses clear concern and worr...
9 The statement expresses confidence and optimis...