Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Cur i bhFeidhm Aschuir Rháthaithe i bPython

Ceacht 7 as 16 Nuashonraithe 2 Samhain 2026 Ardleibhéal
Ar an leathanach seo
  1. Ó Choincheap go Cóid Táirgeachta
  2. Bunús Cur i bhFeidhm
  3. Aicis Úsáide don Táirgeacht
  4. Tagarmharc: Le vs. Gan Ráthú
  5. Láimhseáil Earráidí
  6. Srialta le Bheith ar an Eolas
  7. Príomhphointí

Ó Choincheap go Cóid Táirgeachta

Tuigeann tú an prionsabal atá taobh thiar d’Aschuir Rháthaithe agus a gcásanna úsáide. Soláthraíonn an ceacht seo cód Python iomlán atá réidh le comhtháthú i d’fheidhmchláir, lena n-áirítear láimhseáil earráidí agus tomhas feidhmíochta.

Bunús Cur i bhFeidhm

Ní theastaíonn ach paraiméadar amháin don phatrún íosta: prediction, áit a dtugann tú an t-ábhar a bhfuiltear ag súil leis. Fanann gach rud eile sa ghlao gan athrú—an tsamhail chéanna, na teachtaireachtaí céanna, an láimhseáil freagartha chéanna. Déanann sé seo an ghné seo éasca le glacadh léi, agus chomh héasca céanna le baint má dheimhníonn na méadrachtaí nach bhfuil aon tairbhe ann:

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)

Aicis Úsáide don Táirgeacht

Tairbhíonn tú níos mó ná cód glan trí é a chapsúlú: lárnóidh sé an cinneadh chun an ráthú a chumasú nó a dhíchumasú. Is é seo go díreach an cineál socraithe ar mhaith leat a lascainiú láithreach. Má nochtann imlonnú go bhfuil ráthuithe míchearta ann go seasmhach, is féidir leat iad a dhíchumasú ag pointe amháin in ionat iad a lorg ar fud do bhunáit cóid:

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:
    """Eagarthóir ábhair ag baint úsáide as Aschuir Rháthaithe."""

    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:
        """Cuir ábhar in eagar le ráthú aschuir."""
        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:
        """Aicearra chun cód a chur in eagar."""
        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:
        """Aicearra chun téacs a chur in eagar."""
        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."
            )
        )

An Aicis a Úsáid

editor = PredictedEditor(api_key="your-api-key", model="codestral-latest")

# Cód a chur in eagar
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)

Tagarmharc: Le vs. Gan Ráthú

Ná scipeáil an céim seo. Braitheann an tairbhe ó Aschuir Rháthaithe go hiomlán ar chruinneas do ráthuithe, agus braitheann sin ar do chuid sonraí. Ní chuirfigear aon uimhir ón doiciméadú in ionad tomhais ar do shamplaí féin. Tugann an script seo comparáid idir an dá mhód ar na hionchuir chéanna, agus tugann sé an freagra duit i gceann soicind:

import statistics

def benchmark_prediction(
    client, model, messages, prediction_content, runs=5
):
    """Déanann sé comparáid idir moill le agus gan Aschur Ráthaithe."""
    times_normal = []
    times_predicted = []

    for _ in range(runs):
        # Gan ráthú
        start = time.perf_counter()
        client.chat.complete(model=model, messages=messages)
        times_normal.append((time.perf_counter() - start) * 1000)

        # Le ráthú
        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
    }

Láimhseáil Earráidí

Tá láimhseáil earráidí díreach anseo ar chúis struchtúrach: ní earráid é ráthú mícheart. Déanann an tsamhail neamhaird air agus gineann sí go gnáth—caillfidh tú an tairbhe moille, ach ní chaillfidh tú cáilíocht riamh. Tá na cásanna imeallacha fíor in áit eile:

def safe_edit(editor, original, instruction):
    """Cuir in eagar le láimhseáil láidir earráidí."""
    try:
        result = editor.edit(original, instruction)

        # Seiceáil nach bhfuil an freagra folamh
        if not result.content or len(result.content.strip()) < 10:
            raise ValueError("Response too short or empty")

        return result

    except Exception as e:
        # Cúlú: déan iarracht arís gan ráthú
        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
        )

Srialta le Bheith ar an Eolas

Sula ndéanann tú imlonnú, comhtháthaigh trí phointe i do athbhreithniú cóid. Ar an gcéad dul síos, níl an paraiméadar n (giniúintí iolracha) comhoiriúnach le prediction. Má iarrann do phíblíne críochnuithe iolracha, caithfidh tú roghnú. Ar an dara dul síos, déanann an tsamhail an meaitseáil idir an ráthú agus an t-aschur beag beann ar shuíomh an ábhair sa fhreagra—ní gá duit aon ailíniú a ullmhú. Ar deireadh, agus is é seo an rud a dhéanann an ghné sábháilte le himlonnú: ní dhéanann droch-ráthú dochar do cháilíocht na freagra riamh; ní chostóidh sé ach an tairbhe moille duit. Is é an measa atá le tarlú ná filleadh ar an ngnáthluas ar an dá shamhail atá comhoiriúnach (mistral-large-latest agus codestral-latest).

Príomhphointí

  • Ní chuireann an paraiméadar prediction ach leis an nglao chat.complete()
  • Capsúil an loighic in aicis in-athúsáidte don táirgeacht
  • Tomhais an tairbhe go córasach le tagarmharc sula ndéanann tú imlonnú
  • Pleanáil cúlú gan ráthú i gcás earráidí
  • Ní dhéanann droch-ráthú dochar do cháilíocht, ach do mhoill amháin