Prompting, Tuning & Observability
System messages & prompt techniques · temperature, tokens & reasoning effort · chain of thought & maker-checker loops · tracing, token and latency metrics · model router & deterministic routing
By the tools4free.dev team · Last reviewed November 13, 2026
Practice questions for this topic →
Prompt engineering and system messages
The prompt engineering page says its techniques aren't recommended for reasoning models such as gpt-5 and o-series models. A system message is a set of instructions and context that guides the model's responses. It typically appears first and acts as the highest-level set of instructions. It influences the model but doesn't guarantee compliance: test, iterate and layer it with other mitigations such as filtering and evaluation.
| Technique | What it does |
|---|---|
| Role and scope | Define what the assistant is and what it can and can't do |
| Output contract | Specify the format (for example JSON with fixed keys); keep it small and stable |
| "When unsure" policy / an "out" | Say what to do when the request is ambiguous, out of scope or the answer isn't present; this helps the model avoid false responses |
| Few-shot examples | Example user and assistant pairs in the message list; instructions go in the system message |
| Cue | A prefix that jump-starts the output in the form you want |
| Break the task down | Smaller steps, for example extract claims first, then query |
| Repeat instructions at the end | A response to recency bias: the end of the prompt can influence output more than the start |
| Grounding context and citations | Give the model data to draw from; inline citations reduce false content better than citations at the end |
- Common pitfalls: conflicting instructions without prioritization, overly long system messages that use context window, and hidden requirements (if the output format matters, state it explicitly).
- Instructions such as "only write true facts" or "don't fabricate information" might not be adequate; asking for citations helps reduce incorrect responses.
- For function calling: describe each function and unclear parameter, tell the model to ask for clarification when a request is ambiguous, and say "Only use the functions you have been provided with." if it calls functions you didn't define.
- Developer messages (
role: developer) are functionally the same as system messages for reasoning models. - Fine-tuning, not RAG, is for changing model behavior, style or task performance rather than adding fresh knowledge.
Generation parameters, token budgets and latency
| Setting | Effect |
|---|---|
temperature (0 to 2) | Higher (for example 0.7) is more random and divergent; lower (for example 0.2) is more focused; use a low value for a legal document, higher for fiction |
top_p | Also controls randomness, in a different way; change either temperature or top_p, not both |
max_tokens | Cap output length; set it as low as possible to cut latency; it can truncate but doesn't change quality |
| Stop sequences | Prevent generating extra content |
n | More outputs per request can raise latency; for the fastest response leave it unset or 1 |
stream: true | Tokens return as available; time to first response drops but total time doesn't change |
Reasoning models
reasoning_effort | Best for |
|---|---|
none | Latency-critical work such as voice, fast retrieval and classification |
low | Efficient reasoning: tool use, planning, search where speed and cost matter |
medium | A balanced starting point for most workloads |
high | Hard reasoning, complex debugging, tasks where quality matters more than latency |
xhigh / max | Deep research, long agentic runs and the most complex tasks; use when evaluations show a gain that justifies latency and cost |
- Reasoning tokens never appear in the message content, occupy the context window and are billed as output tokens. Read them from
completion_tokens_details.reasoning_tokens(Chat Completions) oroutput_tokens_details.reasoning_tokens(Responses). - Cap total generation with
max_output_tokens(Responses) ormax_completion_tokens(Chat Completions); both cover reasoning, visible output and formatting tokens. - If the cap or context window is reached the response is
incomplete, possibly before any visible output, and you still pay for input and reasoning tokens. Checkstatuson every response and reserve at least 25,000 tokens for reasoning and output while learning a workload. - Prompt caching reduces latency and cost for prompts with identical content at the start, with a minimum of 1,024 tokens; it has no impact on the output beyond lower latency and cost. Keep reused content identical across requests.
- Mixing different workloads on one endpoint can hurt latency: short calls can wait for longer completions and the cache hit rate can drop.
- Content filtering adds safety and also latency; for certain lower risk use cases, disabling the content filters to improve performance might be worth exploring.
Chain of thought, reflection and self-critique
| Approach | Notes |
|---|---|
| Chain-of-thought prompting | Instruct the model to proceed step by step and show the steps; reduces inaccuracy and makes the response easier to assess. Only for non-reasoning models |
| Reasoning summary | For reasoning models in the Responses API, use the reasoning summary parameter; extracting raw reasoning any other way isn't supported and can lead to throttling or suspension |
| Maker-checker loop (evaluator-optimizer, critic or reflection loop) | A maker proposes, a checker evaluates against defined criteria and sends feedback; repeat until approval or a maximum iteration limit |
| Evaluators | Coherence and fluency use LLM-as-judge scoring; agent evaluators include Task Adherence, Task Completion, Intent Resolution and Tool Call Accuracy; custom evaluators define your own scoring logic |
- A maker-checker loop needs clear acceptance criteria so the checker gives consistent pass or fail decisions, an iteration cap to prevent infinite refinement, and fallback behavior at the cap, such as escalation to a human reviewer or a quality warning with the best result.
- Avoid group chat style loops when the chat manager has no objective way to decide that the task is complete; consider limiting group chat to three or fewer agents.
- Use conversation-level evaluation (
evaluation_level="conversation",messagesformat) to score the full interaction rather than individual turns, for example conversation-wide coherence.
Observability: tracing, token analytics, safety signals, latency
Foundry observability has three core capabilities: evaluation, monitoring and tracing. Tracing and monitoring data goes to the Azure Monitor Application Insights resource connected to the project.
| Need | Use |
|---|---|
| Trace prompt and hosted agents with no code changes | Server-side tracing: connect an Application Insights resource to the project (Build > Agents > Traces > Connect); traces for the past 90 days |
| Trace your own surrounding application code | Client-side instrumentation: azure-ai-projects, opentelemetry-sdk, azure-core-tracing-opentelemetry |
| Trace locally while developing | Microsoft Foundry Toolkit for Visual Studio Code with a local OTLP-compatible collector |
| Operational view | Agent Monitoring Dashboard (Monitor tab): token usage, latency, run success rate, evaluation metrics, red-team results |
| Safety and quality signals in production | Continuous evaluation of sampled traffic, scheduled evaluation to detect drift, scheduled red teaming, Azure Monitor alerts |
- Traces are built from spans (single operations, nested) with attributes, using OpenTelemetry semantic conventions. Common GenAI spans:
invoke_agent,plan,invoke_workflowandexecute_tool(tool arguments and results are attributes). - Viewing traces needs the Log Analytics Reader role on the connected Application Insights resource. No traces: check the Application Insights connection, permissions and instrumentation, generate traffic and wait a few minutes.
- Tracing is generally available for prompt and hosted agents; workflow and external agents are in preview.
- Tracing can capture sensitive input, output and tool arguments: don't put secrets in prompts, tool arguments or span attributes, and redact personal data before it reaches telemetry.
- Dashboard guidance: latency above 10 seconds can indicate throttling, complex tool calls or network issues; a run success rate below 95% warrants investigation.
Latency breakdown for Azure OpenAI deployments
Total time to last token: TTLT = TTFT + (TBT × Tokens Generated). TTFT is time to first token, TBT is time between tokens.
| Azure Monitor metric | Maps to | Use it for |
|---|---|---|
Time to Last Byte (AzureOpenAITTLTInMS) | TTLT | Non-streaming requests and overall response time |
Time to Response (AzureOpenAITimeToResponse) | TTFT | Streaming requests and first-token latency |
Time Between Tokens (AzureOpenAINormalizedTBTInMS) | TBT | Generation throughput; a rise suggests the deployment is under load |
| Generated Completion Tokens, Processed Prompt Tokens | Token counts | Always pair with a latency metric; they also give input and output TPM |
- If TTLT and generated tokens rise together, token volume explains it and it isn't a regression. If TTLT rises without more tokens, check capacity: PTU utilization on provisioned deployments, or Azure OpenAI Requests for 429 throttling on pay-as-you-go.
- Azure OpenAI dashboards in the portal are grouped into HTTP Requests, Tokens-Based Usage, PTU Utilization and Fine-tuning. Platform metrics are collected automatically; resource logs need a diagnostic setting.
Orchestrate models, flows and rules
| Pattern | Routing | Watch out for |
|---|---|---|
| Sequential | Deterministic, predefined order | Failures in early stages propagate; no parallelism |
| Concurrent | Deterministic or dynamic selection; agents work independently on the same input | Needs conflict resolution when results contradict |
| Group chat | Chat manager controls turn order | Conversation loops; hard to control with many agents |
| Handoff | Agents decide when to transfer control; one active agent at a time | Infinite handoff loops; unpredictable routing |
| Magentic | Manager agent builds and adapts a task ledger | Slow to converge; stalls on ambiguous goals |
Start with the lowest complexity that reliably works: a direct model call, then a single agent with tools, then multiagent orchestration. When the right agent is identifiable from the initial input, use deterministic routing or a simpler dispatcher that classifies the input and sends it on, instead of handoff. If you define agents in code (Microsoft Agent Framework, Semantic Kernel) you control routing; no-code environments may not allow it. A Foundry workflow can add if/else branching and human-in-the-loop steps without code.
Model router
| Routing mode | Behavior |
|---|---|
| Balanced (default) | Considers models within a small quality range (for example 1% to 2% of the best) and picks the most cost-effective |
| Cost | Considers a larger quality band (for example 5% to 6%) and picks the most cost-effective |
| Quality | Picks the highest quality rated model for the prompt, ignoring cost |
- Model router is a trained language model deployed like any other Foundry model; it picks the model per request from complexity, reasoning and task type, and supports Global Standard and Data Zone Standard deployments.
- You don't separately deploy the underlying LLMs, except Claude models, which you deploy from the catalog first. A model subset restricts the pool (at least one model); the effective context window is limited by the smallest underlying model.
- Routing mode and subset changes can take up to five minutes. Compare model router with your current baseline by evaluation; auto-update can change the underlying models, performance and cost.
CLI and PowerShell
| Task | Azure CLI | PowerShell |
|---|---|---|
| Install client-side tracing packages (Python) | pip install azure-ai-projects opentelemetry-sdk azure-core-tracing-opentelemetry | - |
| Cap tokens and set reasoning effort (Python, chat completions) | max_completion_tokens=5000, reasoning_effort="medium" | - |
Exam Tips
Tick each tip once you can answer it without looking.
“Someone assumes a system message guarantees the model follows every rule” → It doesn't; test and iterate, and layer filtering and evaluation. Trap: A longer system message doesn't add a guarantee and can reduce room for user content.
“Reduce fabricated statements beyond telling the model not to fabricate” → Ask for citations; inline citations close to the claim work better than citations at the end. Trap: Instructions like "only write true facts" might not be adequate on their own.
“More focused, repeatable output (for example a legal document) versus creative output” → Lower temperature for focused; higher (for example 0.7) for divergent; temperature range 0 to 2. Trap: Changing temperature and top_p together isn't the recommendation; alter one.
“Step-by-step chain-of-thought prompting” → Only for non-reasoning models; reasoning models expose a reasoning summary. Trap: Extracting raw reasoning by other methods isn't supported and can lead to throttling or suspension.
“Reasoning model returns status: incomplete with no visible answer” → The cap (max_output_tokens / max_completion_tokens) or context window was used up by reasoning tokens; raise the budget (reserve at least 25,000 tokens) and check status. Trap: Reasoning tokens are billed as output tokens even though they never appear in the message.
“Voice or classification where latency matters most on a reasoning model” → reasoning_effort none. Trap: high is for hard reasoning where quality matters more than latency.
“Lower per-call latency of a completion” → Lower max_tokens, add stop sequences, don't set n; stream for faster first response. Trap: Streaming doesn't change the time to get all tokens.
“Long prompt with a large identical prefix on every call” → Prompt caching: identical content at the start, minimum 1,024 tokens. Trap: It doesn't change the output content; it lowers latency and cost.
“Trace Foundry prompt or hosted agents with no code changes” → Connect Application Insights to the project (server-side tracing); needs Log Analytics Reader to query. Trap: Client-side instrumentation is a second step for your own application code.
“Locate which tool call or nested step introduced a bad output” → Open the trace and step through its spans (invoke_agent, execute_tool). Trap: Aggregate dashboard metrics show averages, not the step order.
“TTLT went up and generated tokens went up with it” → Expected token-driven latency, not a regression: TTLT = TTFT + (TBT × tokens); if TTLT rises without more tokens, check capacity and 429s. Trap: Chart a latency metric alone and it isn't actionable; pair it with a token count.
“First-token latency for a streaming workload” → Time to Response (AzureOpenAITimeToResponse), maps to TTFT. Trap: Time to Last Byte maps to TTLT, the whole response.
“Draft-review-revise loop between two agents” → Maker-checker loop with acceptance criteria, an iteration cap and fallback behavior. Trap: Without a cap the refinement can loop forever.
“One deployment that balances cost, quality and latency across many models” → Model router: Balanced (default), Cost or Quality mode; optional model subset. Trap: The effective context window is limited by the smallest underlying model.
“The right specialist is already clear from the first user input” → Deterministic routing or a simple dispatcher that classifies and forwards. Trap: Handoff lets agents choose routes and can loop.
“Traces contain personal data or secrets” → Redact before telemetry and never put secrets in prompts, tool arguments or span attributes. Trap: Trace data is production telemetry; apply the same access controls and retention as logs.
Sources
- System message design
- Prompt engineering techniques
- Function calling
- Azure OpenAI reasoning models
- Performance and latency
- Prompt caching
- RAG and indexes in Microsoft Foundry
- AI agent orchestration patterns
- Built-in evaluators reference
- General purpose evaluators
- Observability in generative AI
- Agent tracing overview
- Set up tracing
- Agent Monitoring Dashboard
- Monitor Azure OpenAI
- Model router concepts
- How to use model router
- Build a workflow in Foundry
Checked against Microsoft Learn on November 13, 2026.