Your AI Agent Works. Now Make It SAFER.
/Recently I have been building an agent in Microsoft Copilot Studio. Getting the agent to work was actually not the difficult part. Getting it to work in a way where I could still see what it was doing, understand why it made a decision, control what it was allowed to change and measure what the AI was consuming became a lot more interesting.
The result is a demo agent I called Project Pulse. It helps employees look at their Outlook calendar, determine which meetings belong to their projects, prepare proposed timesheet entries and create a small overview of project progress.
I could have asked an LLM to perform almost every step of that process. But should I?
That question became the basis for a framework I have been working on together with Onyinye Madubuko called SAFER:
- Sustainable
- Accountable
- Fair
- Explainable
- Resilient
The idea is not that you perform one SAFER check before going to production. These are questions you should keep asking while designing, building, testing and running the system.
Sustainability is more than CO2
When we talk about sustainable AI the conversation quickly goes toward energy consumption and emissions. Those things absolutely matter, but sustainability is wider than that.
There are environmental questions around electricity, water, hardware and materials. There are social questions around accessibility, inclusion and human control. There are governance questions around ownership and evidence. And there is an economic question which is sometimes forgotten: are we actually getting enough value from all the resources we are consuming?
This last question becomes especially interesting with generative AI. Inference isn't free from a resource perspective, but it is also difficult to attach one universal energy number to a token or prompt.
For example, the paper How Hungry is AI? benchmarked 30 models and found a very large difference between systems. The most energy-intensive models exceeded 29 Wh for a long prompt and were more than 65 times as energy-intensive as the most efficient systems in the benchmark. Another 2025 paper, Towards Sustainable NLP, found strong relationships between inference energy, generated output length and response time.
Then there is the infrastructure underneath the model. Leitmotiv's NADIKI project takes this much deeper by trying to connect AI workloads with lifecycle indicators and infrastructure data such as energy, hardware and cooling. This highlights one of the problems we have when talking about the footprint of a cloud AI request: often we simply don't have enough infrastructure-level information to claim an exact number.
This is why I would be careful with statements like:
"One AI prompt uses exactly X Wh."
It might be a useful estimate for a clearly defined scenario, but it isn't a universal constant. Model, hardware, utilization, location, token count and system boundaries all matter.
So instead of trying to make Project Pulse display a very precise but questionable CO2 number, I focussed first on things I can actually observe and control: model calls, token consumption, model selection, caching, retries, latency and successful outcomes.
Meet Project Pulse
The basic use case is intentionally simple. An employee asks the agent to help with a timesheet. The agent retrieves Outlook calendar events and the projects assigned to the employee. An LLM classifies which calendar events probably belong to which project.
That classification is only a proposal. Project Pulse calculates the hours itself, checks whether the calendar event already exists in the timesheet and presents the proposed entries to the employee for approval. Only after approval is the data written.
The flow looks roughly like this:
↓
Retrieve relevant calendar events + assigned projects
↓
AI: classify events against projects
↓
Code: validate IDs, calculate hours, check duplicates
↓
Store a Pending AI decision
↓
Human: review proposal
↓
Create Proposed time entries
There are several small design choices in this flow that turned out to make a big difference.
Rule 1: don't use AI for things that aren't AI problems
This is probably the easiest improvement you can make.
An LLM is great at semantic work. It can look at a calendar subject such as Pulse weekly project sync, compare this with a project called Project Pulse and understand that these things are probably related.
But I don't need an LLM to tell me that a meeting from 08:30 until 09:15 took 45 minutes.
In Project Pulse that is just Power Fx:
DateDiff(
DateTimeValue(StartDateTime),
DateTimeValue(EndDateTime),
TimeUnit.Minutes
) / 60
The same applies to duplicate detection, date filtering, active project assignments, identifiers and workflow states. If normal code can give me a deterministic answer, I prefer normal code.
This has more advantages than sustainability. It is cheaper, faster, easier to test and I don't have to wonder whether the model suddenly decides that 45 minutes is 0.8 hours.
A useful rule I now use is:
Let AI interpret. Let code calculate and enforce.
Rule 2: give the model less work
The next optimisation happens before the model is called.
Project Pulse doesn't retrieve every project in SharePoint and give the complete result to the LLM. It first retrieves the current employee, determines the active project assignments and only sends the projects that are relevant for that employee. The JSON sent to the classifier also contains only the fields needed to make the classification.
I also batch the calendar events. Instead of performing one LLM request for every meeting, the relevant events and projects are put into one structured request and the model returns a classification for every event.
The pattern becomes:
A large context window is useful capacity. It isn't a target you have to fill.
Rule 3: put something between your agent and your models
For the model calls I didn't connect Copilot Studio directly to one fixed model. The requests go through Azure API Management's AI gateway capabilities and then to a Microsoft Foundry Model Router.
↓
Azure API Management / AI Gateway
↓
Microsoft Foundry Model Router
↓
Selected model
I like having API Management in the middle because it gives me a control point which the application itself doesn't have to own. This is where I can monitor requests, apply policies, inspect token usage and eventually apply things like rate limits, caching or additional security controls.
Microsoft is investing quite a bit here. There is now also a dedicated AI Gateway tier in public preview. At the moment Microsoft documents it as a managed gateway specifically for models and MCP tools, with policies and OpenTelemetry-based metrics including token counts and latency.
There is also an interesting commercial development around creating AI Gateways from Microsoft Foundry. Microsoft has advertised a free allowance of up to 100,000 requests for qualifying AI Gateways created through Foundry. I would definitely check the current pricing conditions before building a business case around that number because these offerings are changing quickly, but it makes experimenting with a gateway much easier than when every experiment required another permanently paid APIM instance.
If you already have API Management, Microsoft also documents how to connect AI Gateway from Foundry to APIM.
Route, but measure
The Model Router is another nice optimisation. Instead of deciding that every request needs the biggest model I have access to, the router can select an underlying model based on the request.
That sounds sustainable, but there is an important catch: don't assume that routing means you saved anything.
The model response tells me which model actually served the request. I log that. This allows me to compare model distribution, tokens, latency and quality instead of simply putting "we use Model Router" in a green architecture diagram.
Caching can help, but caching can also be waste
Last year I wrote a complete article about semantic caching in Azure API Management. Microsoft has policies to cache semantically similar LLM requests.
This can avoid model inference and lower latency. But a semantic cache first has to create embeddings and perform a cache lookup. If your cache almost never gets a hit, you've added work instead of removing it.
There is another issue for agents like Project Pulse. A cached answer about someone's current project assignments, a current approval or a timesheet transaction can become stale very quickly. So caching isn't a checkbox I would enable globally.
Good candidates are stable, repeated information. Personal and rapidly changing transactional state is a very different story.
Rule 4: don't let the AI approve itself
One of the most important parts of Project Pulse is actually one of the least exciting technically: the model isn't allowed to turn its own classification into an approved business record.
For every classified calendar event the agent creates a proposed decision. The hours are calculated deterministically and duplicate checks are performed. The user then gets an Adaptive Card with the proposed entries.
Only after the user approves the proposal are the TimeEntries created, and even then their status is:
Status = "Proposed"
CreatedByAgent = true
This is a small difference in data modelling, but a very important difference in control. The AI is helping to prepare work. It isn't silently becoming the authority for that work.
Microsoft has some interesting developments here too. The newer Copilot Studio capabilities are getting more structured around approvals and agent workflows. For more advanced scenarios it is worth keeping an eye on Microsoft's preview features instead of assuming you need to build every human-in-the-loop pattern yourself.
Rule 5: record the decision, not just the result
If the user changes the suggestion, I also want to know that.
For that reason Project Pulse has an AgentDecisions list. A decision can contain things such as:
- Decision type
- Original ProjectID
- Source EventID
- Confidence
- A concise evidence summary
- Model or route used
- Whether a cached route was used
- Conversation correlation ID
- The final human outcome
A new classification starts as Pending.
After review it can become Accepted, Corrected or Rejected.
If the model proposes P-001 and the user says it should have been P-002, I don't overwrite P-001. The original proposal stays in the decision record and the human correction is stored separately.
Otherwise six months later I can tell you all my AI decisions were correct because I deleted all evidence that they weren't.
One small bug taught me a surprisingly important lesson
While building this I hit a problem which I think is quite representative of agentic systems.
A user pressed Cancel. My deterministic workflow mapped that to the internal state:
Rejected
But when another topic was called, generative orchestration helpfully interpreted what was happening and passed:
Canceled
That sounds perfectly reasonable to a human.
It was also wrong.
Canceled wasn't a valid value in my SharePoint choice column.
We ran into a similar issue where a technical EventID disappeared between topics because the orchestrator apparently considered the other calendar fields more useful.
The fix was to become very explicit about machine-to-machine contracts. Technical input descriptions now say things such as:
Preserve the supplied value exactly.
Do not infer, translate, summarize, normalize or replace it.
Where schemas were important, I serialised data to JSON at the topic boundary and parsed it again in the receiving topic. That isn't particularly beautiful, but it gives the receiving topic a typed schema it can validate.
My rule became:
Be forgiving with humans. Be strict with machines.
A user should be able to say "calendar", "calender", "agenda" or use another supported language. An internal EventID should never become something the model thinks looks a little nicer.
Rule 6: if you can't observe it, you can't optimise it
At this point I had controls, but I still wanted to know what the AI part was actually doing.
Copilot Studio can send agent-level telemetry to Application Insights. I also pass the Copilot conversation identifier with my model request through API Management.
This gives me a correlation path which looks roughly like this:
↓
Topic + SAFER events
↓
AgentDecision
↓
APIM request
↓
Foundry model call
↓
Actual model + token usage + latency
For the calls through my gateway I can capture things such as:
- Prompt tokens
- Cached tokens
- Completion tokens
- Reasoning tokens
- Total tokens
- Actual model selected
- Cache hit or miss
- Duration
I also added my own events such as:
SAFER.CalendarClassificationParsed
SAFER.AgentDecisionCreated
SAFER.TimeEntrySuggestionsPrepared
SAFER.AgentDecisionResolved
That gives me something much more useful than just an infrastructure graph. I can start relating consumption to an actual business outcome.
Instead of only measuring:
Tokens this month = 12,345,678
I would rather measure:
Tokens per successful task
Model calls per approved timesheet entry
Correction rate per model
Latency per successful task
Cache hit rate
AI avoidance rate
That last one is particularly interesting. If deterministic code completed part of the workflow without invoking a model, that is a model call that never happened.
This is also why I don't think sustainability and cost optimisation are completely separate conversations. Reducing pointless calls, oversized context and unnecessary retries often improves both. But don't automatically call a cost saving an emissions saving. They are different measurements.
Rule 7: test the user you actually have
Building the happy path was not enough. Project Pulse also needed to work when people didn't speak to it like a product demo.
The evaluation set therefore contains variations in:
- Language
- Spelling
- Grammar
- Short prompts
- Very verbose prompts
- Informal descriptions
- Ambiguous project references
- Personal calendar appointments
- Missing information
So these should all be understandable:
check my calendar
check my calender
look at my agenda
which meetings were for my projects?
can you see what time I probably worked on projects last week?
This is part of sustainability too. A system which only works for users who know the perfect prompt isn't particularly inclusive, and every failed interaction, retry and escalation also creates additional work.
Microsoft is making this easier. The newer Copilot Studio agent evaluation experience is currently in preview and supports repeatable test conversations and several ways to score agent behaviour. This makes it possible to move beyond clicking around in the test pane and deciding that "it seems to work".
There is more observability coming too
Another preview I find interesting is environment-level telemetry for Copilot Studio. This uses a more trace-oriented, OpenTelemetry-aligned model across agents in an environment.
For the demo I built my own correlation between Copilot Studio and API Management. A more standardized trace across agent invocation, tools and dependencies could remove a lot of custom plumbing in the future.
Can we now calculate the exact emissions of Project Pulse?
No.
And I think that is an important answer.
I know the request count. I can measure token consumption for the model calls I route myself. I can see actual model selection. I can compare latency. I can see which AI decisions were accepted and corrected.
But I don't have direct access to the complete physical infrastructure chain behind every hosted inference. So I won't put an extremely precise CO2 number on a dashboard and call that a measurement.
This isn't just my problem. Work such as NADIKI exists specifically because better infrastructure-level environmental transparency is needed. Their work combines software and hardware measurements with information from the datacenter itself to make energy and other lifecycle impacts more visible.
Research is also showing just how much variation there is. From Prompts to Power contains more than 32,500 measurements across 21 GPU configurations and 155 model architectures. If anything, research like this makes me less comfortable with one universal energy-per-token figure, not more.
So today my environmental dashboard would distinguish between:
- Measured: tokens, calls, duration, cache use, model selection
- Derived: tokens per successful outcome, correction rate, AI avoidance
- Estimated: environmental impact when a documented model is available
- Unknown: things for which I don't have defensible data
"Unknown" is much more useful than greenwashing.
So, is Project Pulse sustainable?
I would say it is more sustainable by design. I would be much more careful before declaring it "a sustainable AI agent".
The useful part of SAFER isn't giving your application a green badge. It is forcing you to keep asking questions:
- Did this need AI?
- Could I retrieve less data?
- Could I use deterministic code?
- Which model actually ran?
- Did the output create value?
- Could the user understand and correct it?
- Can I trace what happened later?
- What happens when one component fails?
- Do my evaluations still pass after I change the agent?
That is why sustainability, accountability, fairness, explainability and resilience fit together for me. A system that uses slightly fewer tokens but generates lots of incorrect actions isn't sustainable. A system that saves compute by excluding users who phrase things differently isn't sustainable. And an agent nobody can maintain six months from now isn't sustainable either.
Things you can try tomorrow
If you're already building AI agents, I would start with these:
- Find one model call you can remove. Replace arithmetic, validation or filtering with code.
- Reduce one context payload. Filter before retrieval reaches the LLM.
- Batch repeated work. Don't call a model once per row if one structured request can process the set.
- Add an AI gateway. Give yourself one place to observe and govern model traffic.
- Record the actual model and tokens. Don't assume your routing strategy did what you hoped.
- Require approval before consequential writes. AI can propose without being the authority.
- Store corrections. They are evaluation data, not inconvenient mistakes to delete.
- Add evaluations for messy inputs. Different languages, typos and unusual phrasing all belong in your test set.
- Measure outcomes. Tokens per successful task tells you far more than a monthly token total.
- Write "unknown" when it is unknown. Don't turn a rough sustainability estimate into a measurement.
What's next?
Project Pulse is still a demo, and there are plenty of things I want to improve. The new AI Gateway, environment-level Copilot Studio telemetry and built-in agent evaluation features are particularly interesting because several things I had to build manually are becoming platform capabilities.
I also want to keep improving the SAFER framework based on what we learn from actually implementing it. A framework is only useful to me if I can turn it into code, tests, telemetry and decisions.
Most importantly, the next time you build an AI agent, don't only ask:
"What else can I make the model do?"
Also ask:
"What can I stop asking the model to do?"
That might be one of the simplest ways to make your AI cheaper, easier to control and a little more sustainable at the same time.
And don't forget to check out the other contributions to the Festive Tech Calendar. If you build something with SAFER or have ideas for improving it, I would love to hear about it!
