Riešenie problémov s kódom a ladenie
Na tejto strane
Lekcia aktualizovaná 2. novembra 2026. Pôvodné príklady využívali model Magistral, ktorý bol 31. júla 2026 vyradený. Teraz využívajú Mistral Small 4 (
mistral-small-2603) alebo Mistral Large 4 (mistral-large-4-0) s nastavenímreasoning_effort="high"a odpoveď spracúvajú pomocou funkcieseparerz Lekcie 3. Zdroj: Reasoning (dokumentácia Mistral).
Ladenie: Problém vyžadujúci riešenie
Prečo má ladenie väčší úžitok z riešenia problémov (reasoning) než generovanie kódu? Pretože generovanie kódu je cvičením vo vyhľadávaní – model videl milióny funkcií na triedenie –, zatiaľ čo ladenie je cvičením v konfrontácii. Musíš mať v mysli súčasne dve veci: čo by kód mal robiť a čo skutočne robí, a následne nájsť rozdiel. Presne toto je typ úlohy, kde premýšľanie pred odpoveďou mení výsledok.
Nájdenie chyby je v podstate cvičením v logickom uvažovaní. Musíš pochopiť zámer, vysledovať vykonávanie, identifikovať divergenciu medzi očakávaným a skutočným správaním a navrhnúť opravu. Presne tu robí riešenie problémov rozdiel.
Klasické ladenie
Všimni si formu požiadavky v tomto príklade. Nehovoríme „oprav tento kód“. Namiesto toho opisujeme príznak – čo sa malo stať oproti tomu, čo sa deje. Je to tá istá disciplína, ktorú používaš pri práci s ľudským kolegom: diagnóza vychádzajúca z príznaku nájde príčinu, zatiaľ čo holé „oprav to“ bez kontextu často vedie k prepisu, ktorý chybu zamaskuje, namiesto toho, aby ju vyriešil.
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 identifikuje, že funkcia nezvláda zostávajúce prvky po cykle while (chýba pridanie chvostov list1[i:] a list2[j:]).
Analýza komplexného kódu
Pochopenie staršieho kódu (legacy code) je druhým hlavným prípadom použitia a má zaujímavú vlastnosť: stopa riešenia (reasoning trace) je rovnako cenná ako samotná odpoveď. Čítaním toho, ako model rekonštruoval logiku – aké hypotézy si vytvoril, aké kontroly vykonal – získaš mapu čítania kódu, ktorú ti jednoduché záverečné vysvetlenie nemôže poskytnúť.
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}"""}
]
)
Ladenie špecifických chýb
Chyby typov
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}"}
]
)
Problémy s výkonom
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}"}
]
)
Architektúra a refaktorovanie
Riešenie problémov sa uplatňuje aj pri architektonických rozhodnutiach:
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}
],
)
Vzorec: Asistent pre kontrolu kódu
Skombinuj riešenie problémov so systematickou analýzou:
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 alebo Large 4 pre kód?
Pri ladení a analýze kódu závisí výber medzi týmito dvoma prístupmi od hĺbky problému. Jednoduchá chyba – syntaktická chyba, explicitná výnimka, zrejmá optimalizácia – je veľmi dobre zvládnutá modelom Mistral Small 4 (mistral-small-2603) s nastavením reasoning_effort="high" pri miernych nákladoch na tokeny. Model Mistral Large 4 (mistral-large-4-0, vo verejnej náhľade) si vyhradź pre prípady, keď príčina nie je v kóde samotnom viditeľná: architektonické analýzy, jemné chyby ako stavové závody (race conditions) alebo úniky pamäte, ktoré sa objavia až v produkcii, a komplexné kontroly kódu, kde musíš vyvážiť správnosť, výkon a bezpečnosť.
# 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}]
)
Kľúčové poznatky
- Ladenie je ideálnym cvičením v riešení problémov pre
reasoning_effort="high" - Usmerňuj model systémovým promptom, ktorý štruktúruje diagnostickú metódu
- Riešenie problémov vyniká pri jemných chybách, analýzach výkonu a architektúre
- Small 4 v režime
highstačí na bežné chyby; Large 4 vyhodnoť na jemné chyby a architektúru - Skombinuj riešenie problémov so systematickou kontrolou kódu pre maximalizáciu kvality
- Vždy požaduj overovací test spolu s navrhovanou opravou