Razmišljanje za kod i ispravljanje grešaka
Na ovoj stranici
Lekcija ažurirana 2. studenoga 2026. Izvorni primjeri koristili su Magistral, koji je povučen 31. srpnja 2026. Sada pozivaju Mistral Small 4 (
mistral-small-2603) ili Mistral Large 4 (mistral-large-4-0) sreasoning_effort="high"te parsiraju odgovor koristeći funkcijusepareriz Lekcije 3. Izvor: Reasoning (Mistral dokumentacija).
Ispravljanje grešaka: Problem razmišljanja
Zašto ispravljanje grešaka (debugging) više koristi od razmišljanja nego generiranje koda? Zato što je generiranje koda vježba prisjećanja – model je vidio milijune funkcija za sortiranje – dok je ispravljanje grešaka vježba suočavanja. Moraš istovremeno držati na umu dvije stvari: što kod treba raditi i što zapravo radi, a zatim locirati jaz. To je točno ona vrsta zadatka gdje razmišljanje prije odgovora mijenja ishod.
Pronalaženje greške u osnovi je vježba razmišljanja. Moraš razumjeti namjeru, pratiti izvršavanje, identificirati odstupanje između očekivanog i stvarnog ponašanja te formulirati popravak. Upravo tu razmišljanje čini razliku.
Klasično ispravljanje grešaka
Obrati pažnju na oblik zahtjeva u ovom primjeru. Ne kažemo „popravi ovaj kod“. Umjesto toga, opisujemo simptom – što se trebalo dogoditi nasuprot onome što se događa. To je ista disciplina koju koristiš s ljudskim kolegom: dijagnoza koja kreće od simptoma pronalazi uzrok, dok goli „popravi ovo“ bez konteksta često rezultira prepisivanjem koje maskira grešku umjesto da je riješi.
from mistralai.client import Mistral
client = Mistral(api_key="YOUR_API_KEY")
buggy_code = """
def merge_sorted_lists(list1, list2):
result = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
return result
# Test: merge_sorted_lists([1, 3, 5], [2, 4, 6])
# Expected result: [1, 2, 3, 4, 5, 6]
# Actual result: [1, 2, 3, 4, 5]
"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[
{"role": "system", "content": """Python debugging expert.
Method:
1. Trace execution mentally
2. Identify where behavior diverges
3. Explain the root cause
4. Propose a fix with a test"""},
{"role": "user", "content": f"This code has a bug. Diagnose and fix it:\n\n{buggy_code}"}
],
)
Model će identificirati da funkcija ne obrađuje preostale elemente nakon petlje while (nedostaje dodavanje repova list1[i:] i list2[j:]).
Analiza složenog koda
Razumijevanje naslijeđenog koda (legacy code) drugi je glavni slučaj upotrebe i ima zanimljivo svojstvo: trag razmišljanja jednako je vrijedan kao i odgovor. Čitajući kako je model rekonstruirao logiku – koje je hipoteze formirao, koje provjere izvršio – dobivaš kartu čitanja koda koju jednostavno konačno objašnjenje ne može pružiti.
complex_code = """
def process(data):
cache = {}
def helper(n, memo=cache):
if n in memo:
return memo[n]
if n < 2:
memo[n] = n
return n
result = helper(n-1) + helper(n-2)
memo[n] = result
return result
return [helper(x) for x in data if isinstance(x, int) and x >= 0]
"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[
{"role": "user", "content": f"""Analyze this code in depth:
1. What exactly does it do?
2. Are there any potential issues?
3. How can it be improved?
{complex_code}"""}
]
)
Ispravljanje specifičnih grešaka
Greške tipa
type_error = """
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Code:
def calculate_total(items):
total = None
for item in items:
price = item.get('price')
total = total + price
return total
"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[
{"role": "user", "content": f"Explain this error and fix the code:\n\n{type_error}"}
]
)
Problemi s performansama
slow_code = """
def find_duplicates(lst):
duplicates = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j] and lst[i] not in duplicates:
duplicates.append(lst[i])
return duplicates
# This code is very slow on large lists (100,000+ elements)
"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[
{"role": "system", "content": "Analyze the algorithmic complexity and propose an optimized version."},
{"role": "user", "content": f"Optimize this code:\n\n{slow_code}"}
]
)
Arhitektura i refaktoriranje
Razmišljanje se također primjenjuje na arhitektonske izbore:
architecture = """My Flask application has this structure:
app.py (2000 lines):
- API routes (20 endpoints)
- Business logic
- Database access
- Data validation
- Error handling
How should I restructure this application?"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[
{"role": "system", "content": """Senior software architect.
Reason through SOLID principles, separation of concerns,
and long-term maintainability."""},
{"role": "user", "content": architecture}
],
)
Uzorak: Asistent za pregled koda
Kombiniraj razmišljanje sa sustavnom analizom:
def code_review(client, code, language="python"):
"""Performs an in-depth code review with reasoning."""
review_prompt = f"""Perform a detailed code review of this {language} code.
Systematically analyze:
1. **Correctness**: Does the code do what it is supposed to do?
2. **Edge cases**: Are edge cases handled (None, empty, negative)?
3. **Performance**: What is the complexity? Is it optimal?
4. **Readability**: Is the code clear and well-named?
5. **Security**: Are there vulnerabilities (injection, XSS, etc.)?
For each issue found, indicate:
- The line number
- The severity (critical / major / minor)
- The recommended fix
Code to review:
```{language}
{code}
```"""
response = client.chat.complete(
model="mistral-small-2603",
reasoning_effort="high",
messages=[{"role": "user", "content": review_prompt}]
)
return separer(response.choices[0].message.content)[1] # the answer, without the reasoning
Small 4 ili Large 4 za kod?
Za ispravljanje grešaka i analizu koda, izbor između dva pristupa ovisi o dubini problema. Jednostavna greška – sintaksna pogreška, eksplicitna iznimka, očita optimizacija – vrlo se dobro rješava s Mistral Small 4 (mistral-small-2603) uz reasoning_effort="high" uz umjereni trošak tokena. Rezerviraj Mistral Large 4 (mistral-large-4-0, u javnoj pretpreglednoj verziji) za slučajeve gdje uzrok nije vidljiv u samom kodu: arhitektonske analize, suptilne greške poput stanja utrke (race conditions) ili curenja memorije koje se pojavljuju samo u produkciji te složeni pregledi koda gdje moraš uravnotežiti ispravnost, performanse i sigurnost.
# Simple bug: Small is sufficient
simple_bug = "why does 'hello'.split('')[0] raise an error?"
response = client.chat.complete(
model="mistral-small-2603",
messages=[{"role": "user", "content": simple_bug}],
reasoning_effort="high"
)
# Complex bug: Large 4, evaluate on your own cases
complex_bug = "My Django application has a memory leak in production that does not appear in dev..."
response = client.chat.complete(
model="mistral-large-4-0",
reasoning_effort="high",
messages=[{"role": "user", "content": complex_bug}]
)
Ključne točke
- Ispravljanje grešaka idealna je vježba razmišljanja za
reasoning_effort="high" - Usmeri model sistemskim promptom koji strukturira dijagnostičku metodu
- Razmišljanje sjaji kod suptilnih grešaka, analiza performansi i arhitekture
- Small 4 u načinu
highdovoljan je za uobičajene greške; procijeni Large 4 na suptilnim greškama i arhitekturi - Kombiniraj razmišljanje sa sustavnim pregledom koda kako bi maksimizirao kvalitetu
- Uvijek zatraži test verifikacije uz predloženi popravak