• bitcoinBitcoin(BTC)$83,406.00-1.26%
  • ethereumEthereum(ETH)$2,654.27-1.65%
  • tetherTether(USDT)$1.000.00%
  • binancecoinBNB(BNB)$770.70-0.22%
  • rippleXRP(XRP)$1.49-1.58%
  • usd-coinUSDC(USDC)$1.000.00%
  • solanaSolana(SOL)$119.80-0.78%
  • tronTRON(TRX)$0.3339740.25%
  • zcashZcash(ZEC)$1,563.05-4.40%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.06-0.38%
  • HyperliquidHyperliquid(HYPE)$89.75-4.27%
  • dogecoinDogecoin(DOGE)$0.093911-2.36%
  • chainlinkChainlink(LINK)$13.86-2.01%
  • moneroMonero(XMR)$536.71-4.49%
  • whitebitWhiteBIT Coin(WBT)$83.12-1.37%
  • USDSUSDS(USDS)$1.00-0.01%
  • cardanoCardano(ADA)$0.248686-1.43%
  • RainRain(RAIN)$0.012554-1.82%
  • leo-tokenLEO Token(LEO)$9.01-0.26%
  • stellarStellar(XLM)$0.210523-2.02%
  • nearNEAR Protocol(NEAR)$5.213.50%
  • bitcoin-cashBitcoin Cash(BCH)$315.49-5.16%
  • uniswapUniswap(UNI)$9.34-4.37%
  • CantonCanton(CC)$0.1410453.71%
  • litecoinLitecoin(LTC)$70.94-0.86%
  • suiSui(SUI)$1.235.05%
  • Ethena USDeEthena USDe(USDE)$1.00-0.01%
  • avalanche-2Avalanche(AVAX)$10.65-1.08%
  • daiDai(DAI)$1.000.02%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.624.49%
  • USD1USD1(USD1)$1.00-0.01%
  • hedera-hashgraphHedera(HBAR)$0.0952561.96%
  • quant-networkQuant(QNT)$262.7547.51%
  • BittensorBittensor(TAO)$307.93-4.19%
  • BitwayBitway(BTW)$1.2723.79%
  • shiba-inuShiba Inu(SHIB)$0.000006-2.52%
  • Global DollarGlobal Dollar(USDG)$1.00-0.01%
  • crypto-com-chainCronos(CRO)$0.064576-3.15%
  • tether-goldTether Gold(XAUT)$4,203.99-1.72%
  • OndoOndo(ONDO)$0.588.11%
  • paypal-usdPayPal USD(PYUSD)$1.00-0.01%
  • EthenaEthena(ENA)$0.2689790.64%
  • MemeCoreMemeCore(M)$1.18-4.02%
  • Ripple USDRipple USD(RLUSD)$1.000.01%
  • okbOKB(OKB)$117.97-2.47%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • Pump.funPump.fun(PUMP)$0.00510717.44%
  • aaveAave(AAVE)$150.05-3.67%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.06%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

Step-by-Step Guide to AI Agent Development Using Microsoft Agent-Lightning

September 1, 2025
in AI & Technology
Reading Time: 5 mins read
A A
Step-by-Step Guide to AI Agent Development Using Microsoft Agent-Lightning
ShareShareShareShareShare

In this tutorial, we walk through setting up an advanced AI Agent using Microsoft’s Agent-Lightning framework. We are running everything directly inside Google Colab, which means we can experiment with both the server and client components in one place. By defining a small QA agent, connecting it to a local Agent-Lightning server, and then training it with multiple system prompts, we can observe how the framework supports resource updates, task queuing, and automated evaluation. Check out the FULL CODES here.

!pip -q install agentlightning openai nest_asyncio python-dotenv > /dev/null
import os, threading, time, asyncio, nest_asyncio, random
from getpass import getpass
from agentlightning.litagent import LitAgent
from agentlightning.trainer import Trainer
from agentlightning.server import AgentLightningServer
from agentlightning.types import PromptTemplate
import openai
if not os.getenv("OPENAI_API_KEY"):
   try:
       os.environ["OPENAI_API_KEY"] = getpass("🔑 Enter OPENAI_API_KEY (leave blank if using a local/proxy base): ") or ""
   except Exception:
       pass
MODEL = os.getenv("MODEL", "gpt-4o-mini")

We begin by installing the required libraries & importing all the core modules we need for Agent-Lightning. We also set up our OpenAI API key securely and defined the model we will use for the tutorial. Check out the FULL CODES here.

YOU MAY ALSO LIKE

20 Agentic Use Cases of TypeSafe AI’s Jev

Which Is Better To Use?

class QAAgent(LitAgent):
   def training_rollout(self, task, rollout_id, resources):
       """Given a task {'prompt':..., 'answer':...}, ask LLM using the server-provided system prompt and return a reward in [0,1]."""
       sys_prompt = resources["system_prompt"].template
       user = task["prompt"]; gold = task.get("answer","").strip().lower()
       try:
           r = openai.chat.completions.create(
               model=MODEL,
               messages=[{"role":"system","content":sys_prompt},
                         {"role":"user","content":user}],
               temperature=0.2,
           )
           pred = r.choices[0].message.content.strip()
       except Exception as e:
           pred = f"[error]{e}"
       def score(pred, gold):
           P = pred.lower()
           base = 1.0 if gold and gold in P else 0.0
           gt = set(gold.split()); pr = set(P.split());
           inter = len(gt & pr); denom = (len(gt)+len(pr)) or 1
           overlap = 2*inter/denom
           brevity = 0.2 if base==1.0 and len(P.split())<=8 else 0.0
           return max(0.0, min(1.0, 0.7*base + 0.25*overlap + brevity))
       return float(score(pred, gold))

We define a simple QAAgent by extending LitAgent, where we handle each training rollout by sending the user’s prompt to the LLM, collecting the response, and scoring it against the gold answer. We design the reward function to verify correctness, token overlap, and brevity, enabling the agent to learn and produce concise and accurate outputs. Check out the FULL CODES here.

TASKS = [
   {"prompt":"Capital of France?","answer":"Paris"},
   {"prompt":"Who wrote Pride and Prejudice?","answer":"Jane Austen"},
   {"prompt":"2+2 = ?","answer":"4"},
]
PROMPTS = [
   "You are a terse expert. Answer with only the final fact, no sentences.",
   "You are a helpful, knowledgeable AI. Prefer concise, correct answers.",
   "Answer as a rigorous evaluator; return only the canonical fact.",
   "Be a friendly tutor. Give the one-word answer if obvious."
]
nest_asyncio.apply()
HOST, PORT = "127.0.0.1", 9997

We define a tiny benchmark with three QA tasks and curate multiple candidate system prompts to optimize. We then apply nest_asyncio and set our local server host and port, allowing us to run the Agent-Lightning server and clients within a single Colab runtime. Check out the FULL CODES here.

async def run_server_and_search():
   server = AgentLightningServer(host=HOST, port=PORT)
   await server.start()
   print("✅ Server started")
   await asyncio.sleep(1.5)
   results = []
   for sp in PROMPTS:
       await server.update_resources({"system_prompt": PromptTemplate(template=sp, engine="f-string")})
       scores = []
       for t in TASKS:
           tid = await server.queue_task(sample=t, mode="train")
           rollout = await server.poll_completed_rollout(tid, timeout=40)  # waits for a worker
           if rollout is None:
               print("⏳ Timeout waiting for rollout; continuing...")
               continue
           scores.append(float(getattr(rollout, "final_reward", 0.0)))
       avg = sum(scores)/len(scores) if scores else 0.0
       print(f"🔎 Prompt avg: {avg:.3f}  |  {sp}")
       results.append((sp, avg))
   best = max(results, key=lambda x: x[1]) if results else ("<none>",0)
   print("n🏁 BEST PROMPT:", best[0], " | score:", f"{best[1]:.3f}")
   await server.stop()

We start the Agent-Lightning server and iterate through our candidate system prompts, updating the shared system_prompt before queuing each training task. We then poll for completed rollouts, compute average rewards per prompt, report the best-performing prompt, and gracefully stop the server. Check out the FULL CODES here.

def run_client_in_thread():
   agent = QAAgent()
   trainer = Trainer(n_workers=2)    
   trainer.fit(agent, backend=f"http://{HOST}:{PORT}")
client_thr = threading.Thread(target=run_client_in_thread, daemon=True)
client_thr.start()
asyncio.run(run_server_and_search())

We launch the client in a separate thread with two parallel workers, allowing it to process tasks sent by the server. At the same time, we run the server loop, which evaluates different prompts, collects rollout results, and reports the best system prompt based on average reward.

In conclusion, we will see how Agent-Lightning enables us to create a flexible agent pipeline with only a few lines of code. We can start a server, run parallel client workers, evaluate different system prompts, and automatically measure performance, all within a single Colab environment. This demonstrates how the framework streamlines the process of building, testing, and optimizing AI agents in a structured manner.


Check out the FULL CODES here. Feel free to check out our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter.


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.

Credit: Source link

ShareTweetSendSharePin

Related Posts

20 Agentic Use Cases of TypeSafe AI’s Jev
AI & Technology

20 Agentic Use Cases of TypeSafe AI’s Jev

September 28, 2026
Which Is Better To Use?
AI & Technology

Which Is Better To Use?

September 28, 2026
Are 3D Printers Worth Buying In 2026?
AI & Technology

Are 3D Printers Worth Buying In 2026?

September 28, 2026
Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards
AI & Technology

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards

September 27, 2026
Next Post
Video captures explosion on cargo ship carrying coal in Baltimore Harbor

Video captures explosion on cargo ship carrying coal in Baltimore Harbor

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Susan Sarandon and Hannah Einbinder arrested at anti-Netanyahu protest in New York – The Guardian

Susan Sarandon and Hannah Einbinder arrested at anti-Netanyahu protest in New York – The Guardian

September 25, 2026
Village in Nepal hit by massive wave of water

Village in Nepal hit by massive wave of water

September 22, 2026
Don’t Wait For Cheaper Stocks — Rebecca Walser On Stocks To Buy Now

Don’t Wait For Cheaper Stocks — Rebecca Walser On Stocks To Buy Now

September 24, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!