Wednesday, April 8, 2026
HomeArtificial IntelligenceConstruct Manufacturing-Prepared Agentic Programs with Z.AI GLM-5 Utilizing Considering Mode, Software Calling,...

Construct Manufacturing-Prepared Agentic Programs with Z.AI GLM-5 Utilizing Considering Mode, Software Calling, Streaming, and Multi-Flip Workflows

print("n" + "=" * 70)
print("🤖 SECTION 8: Multi-Software Agentic Loop")
print("=" * 70)
print("Construct a whole agent that may use a number of instruments throughout turns.n")




class GLM5Agent:


   def __init__(self, system_prompt: str, instruments: checklist, tool_registry: dict):
       self.consumer = ZaiClient(api_key=API_KEY)
       self.messages = [{"role": "system", "content": system_prompt}]
       self.instruments = instruments
       self.registry = tool_registry
       self.max_iterations = 5


   def chat(self, user_input: str) -> str:
       self.messages.append({"position": "consumer", "content material": user_input})


       for iteration in vary(self.max_iterations):
           response = self.consumer.chat.completions.create(
               mannequin="glm-5",
               messages=self.messages,
               instruments=self.instruments,
               tool_choice="auto",
               max_tokens=2048,
               temperature=0.6,
           )


           msg = response.selections[0].message
           self.messages.append(msg.model_dump())


           if not msg.tool_calls:
               return msg.content material


           for tc in msg.tool_calls:
               fn_name = tc.operate.identify
               fn_args = json.hundreds(tc.operate.arguments)
               print(f"   🔧 [{iteration+1}] {fn_name}({fn_args})")


               if fn_name in self.registry:
                   consequence = self.registry[fn_name](**fn_args)
               else:
                   consequence = {"error": f"Unknown operate: {fn_name}"}


               self.messages.append({
                   "position": "device",
                   "content material": json.dumps(consequence, ensure_ascii=False),
                   "tool_call_id": tc.id,
               })


       return "⚠️ Agent reached most iterations and not using a last reply."




extended_tools = instruments + [
   {
       "type": "function",
       "function": {
           "name": "get_current_time",
           "description": "Get the current date and time in ISO format",
           "parameters": {
               "type": "object",
               "properties": {},
               "required": [],
           },
       },
   },
   {
       "sort": "operate",
       "operate": {
           "identify": "unit_converter",
           "description": "Convert between models (size, weight, temperature)",
           "parameters": {
               "sort": "object",
               "properties": {
                   "worth": {"sort": "quantity", "description": "Numeric worth to transform"},
                   "from_unit": {"sort": "string", "description": "Supply unit (e.g., 'km', 'miles', 'kg', 'lbs', 'celsius', 'fahrenheit')"},
                   "to_unit": {"sort": "string", "description": "Goal unit"},
               },
               "required": ["value", "from_unit", "to_unit"],
           },
       },
   },
]




def get_current_time() -> dict:
   return {"datetime": datetime.now().isoformat(), "timezone": "UTC"}




def unit_converter(worth: float, from_unit: str, to_unit: str) -> dict:
   conversions = {
       ("km", "miles"): lambda v: v * 0.621371,
       ("miles", "km"): lambda v: v * 1.60934,
       ("kg", "lbs"): lambda v: v * 2.20462,
       ("lbs", "kg"): lambda v: v * 0.453592,
       ("celsius", "fahrenheit"): lambda v: v * 9 / 5 + 32,
       ("fahrenheit", "celsius"): lambda v: (v - 32) * 5 / 9,
       ("meters", "toes"): lambda v: v * 3.28084,
       ("toes", "meters"): lambda v: v * 0.3048,
   }
   key = (from_unit.decrease(), to_unit.decrease())
   if key in conversions:
       consequence = spherical(conversions[key](worth), 4)
       return {"worth": worth, "from": from_unit, "to": to_unit, "consequence": consequence}
   return {"error": f"Conversion {from_unit} → {to_unit} not supported"}




extended_registry = {
   **TOOL_REGISTRY,
   "get_current_time": get_current_time,
   "unit_converter": unit_converter,
}


agent = GLM5Agent(
   system_prompt=(
       "You're a useful assistant with entry to climate, math, time, and "
       "unit conversion instruments. Use them each time they may also help reply the consumer's "
       "query precisely. All the time present your work."
   ),
   instruments=extended_tools,
   tool_registry=extended_registry,
)


print("🧑 Consumer: What time is it? Additionally, if it is 28°C in Tokyo, what's that in Fahrenheit?")
print("   And what's 2^16?")
consequence = agent.chat(
   "What time is it? Additionally, if it is 28°C in Tokyo, what's that in Fahrenheit? "
   "And what's 2^16?"
)
print(f"n🤖 Agent: {consequence}")




print("n" + "=" * 70)
print("⚖️  SECTION 9: Considering Mode ON vs OFF Comparability")
print("=" * 70)
print("See how considering mode improves accuracy on a difficult logic downside.n")


tricky_question = (
   "I've 12 cash. Certainly one of them is counterfeit and weighs otherwise than the remaining. "
)


print("─── WITHOUT Considering Mode ───")
t0 = time.time()
r_no_think = consumer.chat.completions.create(
   mannequin="glm-5",
   messages=[{"role": "user", "content": tricky_question}],
   considering={"sort": "disabled"},
   max_tokens=2048,
   temperature=0.6,
)
t1 = time.time()
print(f"⏱️  Time: {t1-t0:.1f}s | Tokens: {r_no_think.utilization.completion_tokens}")
print(f"📝 Reply (first 300 chars): {r_no_think.selections[0].message.content material[:300]}...")


print("n─── WITH Considering Mode ───")
t0 = time.time()
r_think = consumer.chat.completions.create(
   mannequin="glm-5",
   messages=[{"role": "user", "content": tricky_question}],
   considering={"sort": "enabled"},
   max_tokens=4096,
   temperature=0.6,
)
t1 = time.time()
print(f"⏱️  Time: {t1-t0:.1f}s | Tokens: {r_think.utilization.completion_tokens}")
print(f"📝 Reply (first 300 chars): {r_think.selections[0].message.content material[:300]}...")

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments