HomeSample Page

Sample Page Title


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




class GLM5Agent:


   def __init__(self, system_prompt: str, instruments: record, 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.perform.title
               fn_args = json.hundreds(tc.perform.arguments)
               print(f"   🔧 [{iteration+1}] {fn_name}({fn_args})")


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


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


       return "⚠️ Agent reached most iterations with no ultimate 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": "perform",
       "perform": {
           "title": "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", "ft"): lambda v: v * 3.28084,
       ("ft", "meters"): lambda v: v * 0.3048,
   }
   key = (from_unit.decrease(), to_unit.decrease())
   if key in conversions:
       outcome = spherical(conversions[key](worth), 4)
       return {"worth": worth, "from": from_unit, "to": to_unit, "outcome": outcome}
   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 at any time when they may also help reply the consumer's "
       "query precisely. At all times present your work."
   ),
   instruments=extended_tools,
   tool_registry=extended_registry,
)


print("🧑 Person: What time is it? Additionally, if it is 28°C in Tokyo, what's that in Fahrenheit?")
print("   And what's 2^16?")
outcome = 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: {outcome}")




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


tricky_question = (
   "I've 12 cash. Certainly one of them is counterfeit and weighs in another way than the remainder. "
)


print("─── WITHOUT Considering Mode ───")
t0 = time.time()
r_no_think = consumer.chat.completions.create(
   mannequin="glm-5",
   messages=[{"role": "user", "content": tricky_question}],
   pondering={"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}],
   pondering={"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

Latest Articles