Implementatie van Voorspelde Uitvoer in Python
Op deze pagina
Van Concept naar Productiecode
U begrijpt het principe achter Voorspelde Uitvoer (Predicted Outputs) en de gebruiksscenario’s. Deze les biedt complete Python-code die klaar is voor integratie in uw applicaties, inclusief foutafhandeling en prestatiemetingen.
Basisimplementatie
Het minimale patroon vereist slechts één parameter: prediction, waarin u de verwachte inhoud doorgeeft. Alles else in de aanroep blijft ongewijzigd—hetzelfde model, dezelfde berichten, dezelfde responsafhandeling. Dit maakt de functie eenvoudig om te adopteren en net zo eenvoudig om te verwijderen als metrics de winst niet bevestigen:
from mistralai.client import Mistral
client = Mistral(api_key="your-api-key")
source_code = """
import pandas as pd
def load_data(filepath):
df = pd.read_csv(filepath)
df['date'] = pd.to_datetime(df['date'])
df = df.dropna(subset=['value'])
return df
def compute_stats(df):
return {
'mean': df['value'].mean(),
'median': df['value'].median(),
'std': df['value'].std()
}
"""
prompt = (
"Add a 'separator' parameter to the load_data function "
"(default ',') and use it in read_csv. "
"Respond only with the complete modified code."
)
response = client.chat.complete(
model="codestral-latest",
messages=[
{"role": "user", "content": prompt},
{"role": "user", "content": source_code}
],
prediction={"type": "content", "content": source_code}
)
modified_code = response.choices[0].message.content
print(modified_code)
Utility-klasse voor Productie
Encapsulatie biedt hier voordelen die verder gaan dan schone code: het centraliseert de beslissing om voorspelling in of uit te schakelen. Dit is precies het soort instelling dat u direct wilt kunnen togglen. Als een deployment consequent onjuiste voorspellingen oplevert, kunt u deze op één punt uitschakelen in plaats van de parameter door uw hele codebase te zoeken:
from mistralai.client import Mistral
import time
from dataclasses import dataclass
@dataclass
class PredictionResult:
content: str
latency_ms: float
tokens_input: int
tokens_output: int
model: str
class PredictedEditor:
"""Content editor using Predicted Outputs."""
def __init__(self, api_key: str, model: str = "mistral-large-latest"):
self.client = Mistral(api_key=api_key)
self.model = model
def edit(
self,
original: str,
instruction: str,
system_prompt: str | None = None
) -> PredictionResult:
"""Edits content with output prediction."""
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.extend([
{"role": "user", "content": instruction},
{"role": "user", "content": original}
])
start = time.perf_counter()
response = self.client.chat.complete(
model=self.model,
messages=messages,
prediction={"type": "content", "content": original}
)
latency = (time.perf_counter() - start) * 1000
choice = response.choices[0]
return PredictionResult(
content=choice.message.content,
latency_ms=round(latency, 1),
tokens_input=response.usage.prompt_tokens,
tokens_output=response.usage.completion_tokens,
model=self.model
)
def edit_code(self, code: str, instruction: str) -> PredictionResult:
"""Shortcut for code editing."""
return self.edit(
original=code,
instruction=instruction,
system_prompt=(
"You are a programming assistant. "
"Respond only with the modified code, "
"without explanation or markdown."
)
)
def edit_text(self, text: str, instruction: str) -> PredictionResult:
"""Shortcut for text editing."""
return self.edit(
original=text,
instruction=instruction,
system_prompt=(
"You are a professional text editor. "
"Apply the requested modification while preserving "
"the style and structure of the original text. "
"Respond only with the modified text."
)
)
De Klasse Gebruiken
editor = PredictedEditor(api_key="your-api-key", model="codestral-latest")
# Edit code
result = editor.edit_code(
code=my_python_file,
instruction="Replace all print() calls with logging.info() calls"
)
print(f"Latency: {result.latency_ms} ms")
print(f"Tokens: {result.tokens_input} in / {result.tokens_output} out")
print(result.content)
Benchmark: Met versus Zonder Voorspelling
Sla deze stap niet over. De winst van Voorspelde Uitvoer hangt volledig af van de nauwkeurigheid van uw voorspellingen, wat weer afhangt van uw data. Geen enkel cijfer uit de documentatie vervangt meting op uw eigen voorbeelden. Dit script vergelijkt beide modi op dezelfde inputs en geeft u binnen seconden het antwoord:
import statistics
def benchmark_prediction(
client, model, messages, prediction_content, runs=5
):
"""Compares latency with and without Predicted Output."""
times_normal = []
times_predicted = []
for _ in range(runs):
# Without prediction
start = time.perf_counter()
client.chat.complete(model=model, messages=messages)
times_normal.append((time.perf_counter() - start) * 1000)
# With prediction
start = time.perf_counter()
client.chat.complete(
model=model,
messages=messages,
prediction={"type": "content", "content": prediction_content}
)
times_predicted.append((time.perf_counter() - start) * 1000)
avg_normal = statistics.mean(times_normal)
avg_predicted = statistics.mean(times_predicted)
gain_pct = (1 - avg_predicted / avg_normal) * 100
return {
"without_prediction_ms": round(avg_normal, 1),
"with_prediction_ms": round(avg_predicted, 1),
"gain_percentage": round(gain_pct, 1),
"runs": runs
}
Foutafhandeling
Foutafhandeling is hier om een structurele reden eenvoudig: een onjuiste voorspelling is geen fout. Het model negeert deze en genereert normaal—u verliest de latentiewinst, nooit de kwaliteit. De echte edge cases liggen elders:
def safe_edit(editor, original, instruction):
"""Editing with robust error handling."""
try:
result = editor.edit(original, instruction)
# Check that the response is not empty
if not result.content or len(result.content.strip()) < 10:
raise ValueError("Response too short or empty")
return result
except Exception as e:
# Fallback: retry without prediction
print(f"Predicted Output failed ({e}), falling back to standard...")
response = editor.client.chat.complete(
model=editor.model,
messages=[
{"role": "user", "content": instruction},
{"role": "user", "content": original}
]
)
return PredictionResult(
content=response.choices[0].message.content,
latency_ms=0,
tokens_input=response.usage.prompt_tokens,
tokens_output=response.usage.completion_tokens,
model=editor.model
)
Beperkingen om te Weten
Neem voordat u deployt drie punten op in uw code review. Ten eerste is de parameter n (meervoudige generaties) incompatibel met prediction. Als uw pipeline meerdere completions aanvraagt, moet u een keuze maken. Ten tweede wordt de overeenkomst tussen voorspelling en uitvoer door het model afgehandeld, ongeacht de positie van de inhoud in de respons—u hoeft geen enkele uitlijning voor te bereiden. Tot slot, en dit maakt de functie veilig om te deployen: een slechte voorspelling verslechtert nooit de kwaliteit van de respons; het kost u alleen de latentiewinst. Het worstcasescenario is simpelweg een terugkeer naar normale snelheid op de twee compatibele modellen (mistral-large-latest en codestral-latest).
Belangrijkste punten
- De parameter
predictionvoegt u eenvoudig toe aan dechat.complete()-aanroep - Encapsuleer de logica in een herbruikbare klasse voor productie
- Meet de winst systematisch met een benchmark voordat u deployt
- Voorzie een fallback zonder voorspelling voor het geval er fouten optreden
- Een slechte voorspelling verslechtert de kwaliteit niet, alleen de latentie