Spaces:
Sleeping
Download README.md from abdullah9873/e-comm-flask: direct link, hf CLI and curl.
- Browser
- Download file 46.7 kB
-
https://huggingface.co/spaces/abdullah9873/e-comm-flask/resolve/main/README.md
- Command line
-
hf download hf://spaces/abdullah9873/e-comm-flask/README.md
-
curl -L -o README.md https://huggingface.co/spaces/abdullah9873/e-comm-flask/resolve/main/README.md
title: E-Comm Flask
emoji: 🛒
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
pinned: false
[9/6, 6:15 PM] Quratulain: What is RECOMMENDED_PROMPT_PREFIX? Why it is recommended to use RECOMMENDED_PROMPT_PREFIX in a handoffs process? How useful it is?
Its primary purpose is to be included in an agent's instructions to help the LLM understand its role within a multi-agent system and how handoffs work
Including the RECOMMENDED_PROMPT_PREFIX is a prompt engineering best practice recommended by the SDK developers.
1. It Provides Essential System Context The prefix explains to the LLM that it is not a standalone agent but is part of a larger system built with the "Agents SDK." It introduces the core concepts of "Agents" and "Handoffs." This contextual framing is vital because it allows the LLM to reason about its role and the existence of other specialized agents.
2. It Explains Handoffs as Tools The prefix clarifies that the ability to transfer a conversation is represented as a tool (e.g., transfer_to_specialist_agent). This is a critical piece of understanding for the LLM. It doesn't see a "handoff" as a mysterious external process; it sees it as just another function it can call, similar to a sql_query_tool or a calculator_tool. This makes the handoff action fit naturally into the LLM's decision-making process of "which tool is right for this task?". [9/6, 11:15 PM] Quratulain: Why Input Guardrails Are Applied Only to the First Agent
1. Purpose of Input Guardrails Input guardrails are designed to validate, filter, or block raw user input before it enters the agentic system. Their primary role is to act as a "front-line defense" against:
Malicious or harmful queries (e.g., prompt injection attempts, jailbreaking)
Off-topic or irrelevant requests that shouldn't consume expensive LLM resources
Violations of policy (e.g., inappropriate content, sensitive topics)
2. Why Output Guardrails Are Applied Only to the Last Agent Output guardrails are intended to validate the final response that will be delivered to the user. They act as a "quality control" or "safety net" to ensure:
Appropriateness and safety of the content before it reaches the user
Correctness and adherence to format (e.g., valid JSON, no hallucinations)
Compliance with policies (e.g., redacting sensitive information, ensuring factual accuracy [9/10, 7:45 PM] Quratulain: What is StopAtTools?
A) Generic type B) Typealias C) TypedDict D) UnionType E) Class [9/10, 7:45 PM] Quratulain: What external library does the SDK use for parsing function docstring to generate tool descriptions?
Numpy Sphinix Docstring _parser Griffe [9/10, 7:45 PM] Quratulain: What logging level is used when check_tool_use.final_output is None in tool execution?
A) logger.warning() B)logger.debug() C)logger.error() D)no logging occurs [9/10, 7:45 PM] Quratulain: Last one
Which module is used to extract the signature of a function
Pydantic Inspect Typing Json Dataclasses [9/10, 7:45 PM] Quratulain: Typing ka module type hinting k liye use hota h Jb b python me kisi function ka signature (parameter, default value and return value) check krni ho toh inspect ka module use hota h [9/10, 10:57 PM] Quratulain: ``` from whatsapp_agent.utils._helpers import _get_current_time from whatsapp_agent.context.global_context import GlobalContext from whatsapp_agent.database.persona import PersonaDatabaseManager from agents import Agent, RunContextWrapper
AGENT_BASE_INSTRUCTIONS = """
Role
You are a Clinic Support Agent assisting patients through text-based communication. Your purpose is to help patients manage their appointments in a clear, polite, and professional manner.
Goals
- Help patients schedule, reschedule, or cancel appointments.
- Ensure all interactions are polite, accurate, and fully resolve the patient's request.
- Maintain professionalism and empathy throughout the conversation.
Tools Available
You have access to three tools:
- schedule_appointment — create a new appointment.
- cancel_appointment — cancel an existing appointment.
- change_appointment_time — reschedule an existing appointment.
Only use these tools when necessary and when the patient explicitly or implicitly requests the corresponding action.
Rules of Engagement
- Persistence: Continue the conversation until the patient confirms their request is resolved.
- Accuracy: Use only verified details. Never invent or assume data.
- Professionalism: Keep tone warm, polite, and empathetic.
- Step-by-Step Tool Usage:
- Before using a tool, explain to the patient what you are about to do.
- After using a tool, summarize the result and confirm with the patient.
- Do not chain multiple tools without reflecting on the first tool's result.
- Cultural Sensitivity: Respond respectfully to greetings (e.g., “Assalamoalaikum” → “Wa Alaikum Assalam”).
Context
{user_context} {chat_history}
Doctor Availability: {doctor_timings}
Current Time in Karachi: {current_time}
Task Guidelines
Appointment Scheduling
- Confirm patient's preferred date, time, and provider if specified.
- Ensure time is within business hours: Monday-Saturday, 09:00-18:00.
- If unavailable, politely suggest alternatives.
- Use
schedule_appointmentto confirm booking.
Appointment Rescheduling
- Confirm the new requested date and time.
- Check availability before proceeding.
- Use
change_appointment_timeto update the appointment. - Confirm updated details with the patient.
Appointment Cancellation
- Confirm which appointment the patient wants to cancel.
- Use
cancel_appointmentto remove the booking. - Confirm cancellation with the patient.
General FAQs
- Provide simple, verified answers to general questions.
- For complex or medical-specific concerns, advise the patient to consult a provider.
Edge Cases
- If request is unclear → ask clarifying questions.
- If outside working hours → politely inform the patient and offer the next available slot.
- If request is beyond your role (e.g., urgent medical advice) → escalate to a human provider.
Example Interaction
- Patient: “I want to book an appointment for tomorrow afternoon.”
- Agent:
- Step 1: Confirm details → “Sure! Could you please share your preferred time and doctor's specialty?”
- Step 2: Use tool → check and schedule.
- Step 3: Confirm → “✅ Your appointment is booked for Tuesday at 3:00 PM. Would you like me to also send a confirmation email?”
Constraints
- Do not give medical diagnoses or treatment advice.
- Do not use unverified information.
- Always align with business hours when scheduling.
{persona} """
def get_agent_instructions(wrapper: RunContextWrapper[GlobalContext], agent: Agent) -> str: persona_db = PersonaDatabaseManager() persona = persona_db.get_persona(wrapper.context.company.whatsapp_number) return AGENT_BASE_INSTRUCTIONS.format( user_context=wrapper.context.user.formatted_user, chat_history=wrapper.context.chat_history.formatted_messages, current_time=_get_current_time(), doctor_timings=wrapper.context.business_hours.formatted_timings, persona=persona.persona.instructions, )
[9/11, 7:42 AM] Quratulain: For schema validation: pydantic
For function signature: inspect
For function docstring extraction:
Griffee
[9/11, 7:42 AM] Quratulain: resolve() ka kaam hai do settings ko mila kar ek final settings banana.
Ek settings aati hai Agent ki.
Ek settings aati hai Runner ki.
Dono ko mila kar nayi settings ban jati hain.
Agar dono mai ek hi cheez likhi ho (same key ho) to Runner wali value use hoti hai, Agent wali ignore ho jati hai.
Example:
Agent: { temperature: 0.5, max_tokens: 100 }
Runner: { temperature: 0.9 }
resolve() ke baad result hoga:
{ temperature: 0.9, max_tokens: 100 }
Yani final mai runner ki baat chalti hai.
[9/19, 1:39 PM] Quratulain: Agar aap agent.clone(tools=[new_tool]) nahi dete ho, to tools behavior kaise hoga?
A) Clone gets no tools
B) Clone gets copy of tools list but same tool objects (shared)
C) Clone has its own entirely new tool objects
D) Error
clone() method kis class pe milti hai?
A) Only RealtimeAgent
B) Only AgentBase
C) Both Agent and RealtimeAgent have clone method
D) None
Agar base agent ka model_settings.temperature = 0.7 aur clone override kare temperature=0.9, to clone ka behavior kaisa hoga?
A) Clone bhi 0.7 use karega
B) Clone 0.9 use karega, base unchanged
C) Base change ho jayega bhi clone se
D) Error
tools list share hone se kya issue ho sakta hai?
A) Clone tools update nahi hote
B) Base agent aur clone dono pe ek hi tool call hogi
C) Memory leak hoga
D) No impact
Agar handoffs list bhi shallow copied hai, to agar base agent ke handoffs update karein, clone ka handoff list me bhi reflect hoga?
A) Yes
B) No
C) Depends on model_settings
D) Only if override
[9/22, 1:16 AM] Quratulain: In the OpenAI Agents SDK, when AgentA coordinates with AgentB for a specialized task, what is a key theoretical difference in how responsibility is distributed between a handoff to AgentB and using AgentB as a tool?
a) A handoff delegates full responsibility to AgentB, while using AgentB as a tool keeps AgentA responsible for coordinating and processing AgentB's output.
b) Using AgentB as a tool shifts all responsibility to AgentB, while a handoff allows AgentA to oversee the task's outcome.
c) Both approaches distribute responsibility equally, as AgentA and AgentB share control in the workflow.
d) A handoff requires AgentA to monitor AgentB's progress, while using AgentB as a tool absolves AgentA of any responsibility.
[9/22, 1:16 AM] Quratulain: 1- Your financial trading agent system processes real-time market data through
multiple tools. During market volatility, you observe that tool execution latencies
spike unpredictably (50ms → 5000ms). Some tools become temporarily unavailable,
others return stale data. The system must continue operating with degraded data
rather than failing completely. Which exception handling strategy maintains trading
capability during infrastructure stress?
a) Implement timeout-based tool selection with fallback chains, graceful degradation to cached/stale data with age
indicators.
b) Always use the fastest responding tool regardless of data quality.
c) Stop all trading when any tool shows increased latency.
d) Cache all responses and never call external tools during volatility.
2- Which of the following correctly describes what happens if you pass a dataclass
PurchaseInfo as output_type to an agent?
a) The SDK requires you to manually write a JSON schema.
b) The SDK auto-generates a strict JSON schema and converts the final JSON into a PurchaseInfo instance.
c) The SDK ignores the dataclass and returns raw JSON.
d) The SDK only supports Pydantic models, not dataclasses.
3- You want your target agent to only receive the last 2 messages from history when
a handoff occurs. Which handoff() parameter helps with that?
a) tool_name_override
b) tool_description_override
c) input_filter
d) on_handoff
4- When using a low temperature (e.g. 0.3), a moderate top_k (e.g. 50), and a high
top_p (e.g. 0.95), what kind of output is most likely?
a) Very random, with lots of strange word choices
b) Creative and varied, but still coherent
c) Extremely focused and repetitive
d) Completely deterministic with no variety
[9/22, 1:16 AM] Quratulain: 5- When you call the Agent constructor in the OpenAI Agents Python SDK, which
parameter is required?
a) instructions
b) name
c) model and model_settings
d) No parameters are required; all are optional
6- What is the purpose of the resolve() method within ModelSettings?
a) Combines default settings with overrides and returns a new settings instance.
b) Immediately sends settings to the LLM API.
c) Validates if all required settings are non-null.
d) Deletes unset fields and returns the same object.
7- By default, what OpenAI API does the Agents SDK use?
a) Chat Completions API
b) Responses API
c) Assistants API
d) Doesn't use any API by default
8- You have an orchestrator agent that uses 5 specialist agents as tools. During
execution, one specialist agent (translation_agent) encounters a temporary API rate
limit and fails. The orchestrator's instructions include "If any translation fails, try
an alternative approach." What happens to the orchestrator's execution context and
the remaining specialist agents?
a) The orchestrator immediately fails with the specialist's exception, and all pending tool calls are cancelled
b) The orchestrator receives the exception as tool output, can handle it in its reasoning, and continues with other
specialists
c) The failed specialist automatically retries 3 times before the orchestrator sees the failure
d) All specialist agents share the same execution context, so the failure affects all of them
9- When is an input guardrail function logically applied in relation to the agent's
processing of user input?
a) After the agent produces output
b) Before the agent processes the user's input
c) Only when a tool call is made
d) During agent initialization
10- Which return type does Runner.run_streamed(...) provide?
a) RunResult
b) AsyncGenerator[str]
c) StreamingClientResponse
d) RunResultStreaming
[9/22, 1:16 AM] Quratulain: 11- Which scenario best fits the use of Runner.run_streamed()?
a) You want to block until completion and collect a final output object.
b) You need live, partial output updates as the agent processes input, like typing a chat response in real-time.
c) You only plan to use synchronous code and don't need real-time updates.
d) You want to execute multiple agents simultaneously práctica parallel.
12- Only the first agent's input guardrails are executed; downstream agents in a
multi-agent chain do not re-run input guardrails.
a) True
b) False
c) Only if guardrails_disabled=True
d) Only if max_turns > 1
13- In a banking chatbot, you want to ensure that before any transaction request is
processed, the system verifies that the amount provided is a positive number and
doesn't exceed the user's daily transfer limit. Which scenario best demonstrates the
essential use of an input guardrail?
a) Ensuring the chatbot's output is polite and well-mannered before displaying it to the user.
b) Blocking the chatbot from connecting to unauthorized external banking APIs during execution.
c) Validating that the requested transfer amount is a valid positive integer and below the allowed daily maximum before
the agent attempts the transaction.
d) Shortening overly long user messages to conserve tokens before the agent processes them.
14- You want two separate Runner.run() calls to be part of the same trace session
named "JokeWorkflow". How should you configure this?
A) Wrap both Runner.run(...) invocations inside a with trace("JokeWorkflow"): block.
B) Pass trace="JokeWorkflow" into both run() calls individually.
C) Use the group_id parameter in Runner.run(...) to label both runs identically.
D) Manually merge trace files after both runs complete.
15- Your OpenAI-based financial assistant will handle highly sensitive financial
information. According to prompt engineering best practices, what should the
system message include to ensure safe behavior?
A) A full list of supported financial tools and detailed schemas for each one
B) A careful persona with explicit safety instructions, such as: “You are a secure financial assistant. Never expose
account numbers. Always confirm actions through the designated secure API or tool.”
C) A low temperature setting (e.g. 0.1) in ModelSettings to make responses consistent
D) A planning checkpoint that instructs the agent to reflect before using any tool
[9/22, 1:16 AM] Quratulain: 16- What is the practical difference between Runner.run() and
Runner.run_sync()?
A) run_sync is asynchronous and returns immediately, while run blocks until the agent finishes.
B) run is async and must be awaited, whereas run_sync blocks execution and should only be used when no event loop
is running.
C) They behave identically; run_sync just wraps run_streamed() under the hood.
D) run returns streaming events incrementally; run_sync returns the final result only.
17- You're developing a multi-agent supply chain assistant with: InventoryAgent:
monitors stock levels and forecasts shortages. OrderAgent: handles ordering,
shipment, and vendor interactions. What's the best way to utilize the handoffs
primitive?
A) Each agent runs on its own; a central script manually pipes data between them based on alerts.
B) InventoryAgent directly imports and calls OrderAgent's methods as a library.
C) When InventoryAgent detects a stock shortage needing replenishment, it uses a handoff to transfer control,
along with context, to OrderAgent to manage the ordering process.
D) Use handoffs randomly to balance load across agents when requests pile up.
18- Suppose you have a synchronous Python function
analyze_portfolio(data: dict) -> str that processes financial data, but
your OpenAI Agents SDK workflow is fully asynchronous. What's the best practice
for exposing this synchronous function as a tool in your async-first agent?
A) Just decorate it with @function_tool; the SDK will automatically handle running it, so your async event loop isn't
blocked.
B) Manually wrap analyze_portfolio inside an async def that calls await asyncio.to_thread(...), then
decorate the wrapper with @function_tool.
C) Rewrite the entire function to be async; the SDK doesn't support synchronous functions at all.
D) Use a special @sync_function_tool decorator that OpenAI provides for synchronous functions.
19- What is the primary reason to use @pydantic.dataclasses.dataclass
over pydantic.BaseModel?
a) It adds validation on top of standard dataclasses while preserving familiar dataclass behavior.
b) It provides the same validation and schema capabilities as BaseModel.
c) It supports mutable default values like lists without default_factory.
d) It speeds up validation by disabling type coercion.
20- What happens when a guardrail tripwire is triggered?
A) The agent logs a warning but continues processing
B) A GuardrailTripwireTriggered exception is raised, stopping agent execution
C) The agent automatically retries the same prompt
D) The next agent in the workflow takes over
[9/22, 1:16 AM] Quratulain: 21- You want your LLM to solve a tricky puzzle and explain its reasoning. Which system
message best applies Chain of Thought prompting?
A) Give only the final answer—no explanation.
B) Please think step-by-step, show your reasoning, then give the final answer.
C) Use high temperature to explore many possibilities randomly.
D) Internally reflect, then output the best answer without showing thought steps.
22- Which of the following is a valid item in the tools list when initializing an agent?
A) A plain Python function (without a decorator).
B) A FunctionTool object created via @function_tool.
C) A raw dictionary representing a tool schema (not wrapped).
D) A plain class instance without tool wrapping.
23- Which exception is raised when an LLM output fails to match the declared
output_type schema at runtime?
A) UserError
B) ModelBehaviorError
C) MaxTurnsExceeded
D) InvalidSchemaError
24- In the OpenAI Agents SDK, which statement accurately reflects the relationship
between Traces and Spans?
A) A Trace represents a single operation like an LLM generation, and each Span corresponds to different agent runs.
B) A Trace is a sequence of Spans, where each Span logs an event such as tool calls, LLM generations, or
handoffs during a single workflow.
C) Spans are only used for tool calls, while Traces only track guardrail checks.
D) Traces and Spans are interchangeable; both record identical events in agent execution.
25- One of Pydantic's standout features is that it uses Python type hints for data
validation and schema definition. Why is this advantageous?
A) They allow seamless validation, integrate with IDEs and static type-checkers like MyPy or Pyright.
B) Type hints are optional and don't affect validation.
C) Type hints allow storing runtime values inside models.
D) Type hints ensure Pydantic will bypass all validation if annotations match.
26- The OpenAI Agents SDK is described as "Python-first." What does this mean?
A) It only runs on CPython and cannot run on PyPy or MicroPython.
B) It only supports OpenAI models, not local or external models.
C) It limits users to sync Python code, disallowing async workflows.
D) It requires Python syntax to define agents, tools, and orchestration—with no new DSL.
[9/22, 1:16 AM] Quratulain: 27- You want the agent to greet each user by name dynamically based on the context.
Which behavior illustrates the correct use of instructions?
a) Passing "Hello {name}!" directly—expecting the SDK to auto-substitute {name}.
b) Defining a function greet(ctx, agent) -> str and passing it to instructions.
c) Manually building the Agent inside Runner.run(...), reconstructing instructions each time.
d) Using a class method override to compute instructions.
28- What is the effect of using high temperature (e.g. 1.2) with low top_k (e.g. 5) and
low top_p (e.g. 0.3)?
a) Output will be highly unpredictable and full of odd word choices
b) Very stable but limited—choosing from only a few top tokens
c) Balanced mix of randomness within a small set of top picks
d) Identical outputs every time with no creativity
29- If you create an Agent without specifying a model, which model will it use by
default?
a) gpt-3.5-turbo
b) gpt-4.1
c) gpt-4o
d) It won't use any model until you set one
30- What is the primary purpose of RunHooks in the Agents SDK?
a) To validate the final output of an agent
b) To provide callbacks that fire during any agent run across handoffs
c) To modify the agent's instructions on the fly
d) To automatically generate JSON schemas from Pydantic models
31- Your system has tools that call external APIs with different authentication methods. A
developer implements this pattern:
@function_tool
def call_api_a(data: str) -> str:
headers = {"Authorization": f"Bearer {API_A_TOKEN}"}
return requests.post("https://api-a.com", json=data, headers=headers).text
@function_tool
def call_api_b(data: str) -> str:
headers = {"Authorization": f"Bearer {API_B_TOKEN}"}
return requests.post("https://api-b.com", json=data, headers=headers).text
The agent sometimes gets confused about which API to use for different types of data. Beyond better instructions,
what's the fundamental design issue?
a) API tokens should be passed as parameters instead of being hardcoded
b) Tools are too similar; the LLM can't distinguish between them without data-type-specific tool names and clear
functional differences
c) Should use a single generic api_call tool with API type as parameter
d) Each tool needs different parameter schemas to help the LLM choose
[9/22, 1:16 AM] Quratulain: 32- If an agent exceeds its allowed number of turns (including tool invocations), which
exception is raised?
Options:
a) ModelBehaviorError
b) UserError
c) AgentsException
d) MaxTurnsExceeded
33- If you want to log whenever your agent starts or finishes using a tool, where should
you attach your AgentHooks?
a) Create an AgentHooks instance and pass it into RunHooks when running the agent.
b) Assign your custom AgentHooks to the hooks attribute of the Agent before running it.
c) Modify the RunHooks class to include your AgentHooks methods.
d) Use the RunContextWrapper to register your AgentHooks during execution.
34- Which combination of attributes controls how an agent's final LLM output is validated
and parsed?
a) output_type, agent_output_schema, output_parser
b) tools, handoffs, model
c) instructions, name, temperature
d) convert_schemas_to_strict, tools, parse_mode
35- By default, if you set output_type=BarModel (a Pydantic model) and do not
specify output_schema_strict, the SDK will generate a strict JSON schema.
a) True
b) False
c) Only if you used StrictInt or StrictStr in BarModel
d) Only if you passed convert_schemas_to_strict=True to the Agent
36- Which of the following statements about the @function_tool decorator in the
OpenAI Agents SDK is correct?
a) You must use @function_tool on every function that an agent can access as a tool.
b) The decorator @function_tool cannot be applied to asynchronous (async) functions.
c) Every tool function must include a docstring, or it won’t be registered.
d) Using @function_tool automatically generates an OpenAPI spec for the function.
[9/22, 1:16 AM] Quratulain: 37- You create a custom tool with error handling:
@function_tool
def risky_operation(data: str) -> str:
if data == "fail":
raise ValueError("Operation failed!")
return f"Success: {data}"
agent = Agent(
name="Test Agent",
instructions="Use the risky tool. If it fails, try again with 'retry' as input.",
tools=[risky_operation]
)
result = Runner.run_sync(agent, "Please use risky_operation with input 'fail'")
What happens when the tool raises ValueError?
a) The agent execution stops with an unhandled ValueError, terminating the conversation
b) The agent receives the error message as tool output and can retry based on its instructions
c) The SDK automatically retries the tool call 3 times before failing
d) The tool call is skipped and the agent responds without using any tools
38- Suppose you have a support agent that needs to tailor its guidance based on
whether a user is a premium subscriber or basic user:
@dataclass
class UserContext:
user_id: str
is_premium: bool
def premium_instructions(context: RunContextWrapper[UserContext], agent: Agent):
if context.is_premium:
return "You are a support agent prioritizing and fast-tracking premium user issues."
else:
return "You are a support agent helping a basic user with general support."
agent = Agent(
name="SupportAgent",
instructions=?,
tools=[...],
)
How should you configure instructions so it dynamically updates based on the user's subscription status at runtime?
A) Pass a template string like instructions="You are a support agent. User type: {is_premium}" and the
SDK will auto-fill {is_premium} from context.
B) Subclass Agent and override a protected method like _get_dynamic_instructions (self, context).
C) Provide the function premium_instructions directly to the instructions argument-since it accepts (context,
agent) and returns the proper string.
D) Dynamic instructions aren't supported; instructions must be a fixed string at agent creation.
[9/22, 1:16 AM] Quratulain: Markdown me image insert karne ka basic tareeqa yeh hota hai:
text

! lagana zaroori hai taake Markdown samjhay ke yeh image hai.
[ aur ] ke andar alt text hota hai jo describe karta hai image ko. Yeh accessibility ke liye zaroori hai.
( ) ke andar image ka URL ya path hota hai.
Agar chaho toh image ke URL ke baad double quotes me tooltip title (jo mouse hover pe dikhai de) likh sakte ho.
Agar image ko clickable banana hai (matlab image pe click karo aur koi link khulay), toh pura image ke Markdown syntax ko ek aur square bracket ke andar link ke saath wrap karte hain:
text
[](link_url)
Iska matlab: image ke upar ek link add kar diya gaya.
Option B isi tarah likha gaya hai:
text
[](https://flickr.com)
An old rock in the desert alt text hai
/assets/images/shiprock.jpg image ka path hai
"Shiprock, New Mexico by Beau Rogers" image ka tooltip title hai
Poora image link hai https://flickr.com par
Is liye yeh sahi hai kyunki image pe hover karne se tooltip dikhega, aur image click karne par flickr.com open hoga.
Baaki options me yah rule theek nahi hai, isliye wo galat hain.
Yeh simple si baat hai jo Markdown me image ko clickable aur tooltip dono banata hai .
[9/22, 1:16 AM] Quratulain: Level 2: Professional Agentic AI Development
Targets advanced proficiency in Python, Agentic AI, AI protocols, Agentic Web, and Building Effective Agents.
Exam L2:P1-PAI Professional Agentic AI Development
Duration: 2 Hours 30 Minutes | Questions: 60
OpenAI Agents SDK core principles and architecture
Python-first orchestration and control flow in agent development
Agents, Tools, and Handoffs – roles, usage, and design patterns
Runner methods (run_sync, run, run_streamed) – behaviors and blocking
Pydantic models for input/output validation and default handling
@function_tool decorator – usage and schema generation
Dynamic instructions using callable functions with context
AgentHooks and lifecycle event handling
Synchronous vs asynchronous tools integration
Input and output guardrails for validation and compliance
Error handling during tool execution and error propagation
Tool choice and tool use behavior (auto, required, stop_on_first_tool, etc.)
Agent cloning vs creating new agents
Context management with RunContextWrapper
Conversation history handling in multi-agent handoffs
Output type parsing and handling invalid or extra fields
Prompt engineering techniques (system prompts, dynamic context, CoT)
Planning reminders and reasoning in prompts
Sensitive data handling and persona-based instruction design
Multi-agent workflows and sequential orchestration
Access control and permission checks for tools and handoffs
Regional compliance filtering in handoffs (e.g., GDPR, US regulations)
Feature gating and subscription-based tool access
Custom runners with orchestration hooks and context engineering
Keyword-based routing limitations in handoffs
Audit logging and tool call tracking with tool_call_id
Markdown basics (links and images)
[9/22, 1:16 AM] Quratulain: Suppose you have a synchronous Python function
analyze_portfolio(data: dict) -> str that processes financial data, but
your OpenAI Agents SDK workflow is fully asynchronous. What's the best practice
for exposing this synchronous function as a tool in your async-first agent?
A) Just decorate it with @function_tool; the SDK will automatically handle running it, so your async event loop isn't
blocked.
B) Manually wrap analyze_portfolio inside an async def that calls await asyncio.to_thread(...), then
decorate the wrapper with @function_tool.
C) Rewrite the entire function to be async; the SDK doesn't support synchronous functions at all.
D) Use a special @sync_function_tool decorator that OpenAI provides for synchronous functions.
[9/22, 1:16 AM] Quratulain: 22- Which of the following is a valid item in the tools list when initializing an agent?
A) A plain Python function (without a decorator).
B) A FunctionTool object created via @function_tool.
C) A raw dictionary representing a tool schema (not wrapped).
D) A plain class instance without tool wrapping.
[9/22, 1:16 AM] Quratulain: Q16.
Which of the following is NOT automatically traced? A. Tool function calls B. Transcription of speech inputs C. Manual Python logging statements ✅ D. Text-to-speech output
[9/22, 4:23 PM] Quratulain: 🔎 Detail Explanation of Strict JSON Schema in OpenAI Agents SDK
OpenAI Agents SDK ke andar ek class hoti hai AgentOutputSchema jo aapke output_type (jaise BarModel Pydantic model) ka schema generate karti hai. Is class ke __init__ function me ek parameter hota hai strict_json_schema, jiska default value True hai.
Matlab ye hua ke agar aap sirf output_type=BarModel set karte ho aur output_schema_strict explicitly pass nahi karte, tab bhi SDK backend me strict JSON schema banata hai. Strict ka matlab hai ke jo types aapke model me defined hain (for example: int, str), woh exactly enforce kiye jate hain aur LLM ko isi strict schema ke against output dena padta hai.
Ye behavior SDK ke andar on_invoke_tool aur TypeAdapter ke through apply hota hai, jahan schema banate waqt default hi strict=True set hota hai. Iska sabse bara fayda ye hai ke aapko reliable aur predictable JSON outputs milte hain, aur LLM ke galat type conversion chances kam ho jate hain.
Is liye, pehle jo confusion tha (ke strict manually enable karna padta hai) woh incorrect tha. Asal me SDK ki design hi aisi hai ke strict schema by default generate hota hai, aur aapko manually kuch karna nahi padta — sirf agar aap loose schema chahte ho to tab explicitly strict_json_schema=False pass karna hoga.
---
👉 Summary:
Default = strict_json_schema=True → Strict schema banega
Agar aap loose chahte ho to → strict_json_schema=False pass karna hoga
[9/22, 8:38 PM] Quratulain: Quiz Covers:
https://openai.github.io/openai-agents-python/
https://cookbook.openai.com/examples/gpt4-1_prompting_guide
https://www.markdownguide.org/basic-syntax/
https://www.markdownguide.org/cheat-sheet/
https://github.com/panaversity/learn-agentic-ai/tree/main/01_ai_agents_first
You Can Generate Mock Quizzes for Practice using LLMs from this Prompt:
Create a comprehensive quiz covering OpenAI Agents SDK. It should include as many MCQ Quiz Questions as required to test the material, the questions should be difficult and at the graduate level and should test both concepts and include code were required. From the following following documentation:
https://openai.github.io/openai-agents-python/
[9/23, 2:32 AM] Quratulain: 1. Agent as Tool ka Model
Jab aap agent ko ek tool ke taur pe expose karte ho (agent.as_tool()), to usko chalane ke liye bhi ek LLM model chahiye hota hai (jaise gpt-4o-mini, gpt-4.1, waghera).
Agar aap explicitly model pass nahi karte (model=...), to wo SDK default logic use karega.
---
🔹 2. OpenAI SDK ka Behavior
OpenAI SDK me by default model inference hoti hai. Agar aapne Runner ya Agent banate waqt already ek default model set kiya hai, to agent.as_tool() bhi usi ko pick kar lega.
Is liye OpenAI models ke sath aapko error nahi milta — kyunki wo fallback karke default model use kar leta hai.
---
🔹 3. Gemini ya Dusre Providers ka Case
Gemini ya koi dusra provider (Anthropic, Mistral, etc.) me ye fallback behavior hamesha available nahi hota.
Agar aap agent.as_tool() banate waqt model pass nahi karte, to backend pe jab function decorator (@function_tool) call hota hai aur LLM inference ki zaroorat hoti hai, tab error throw karega — kyunki SDK ko samajh nahi ayega kaunsa model use karna hai.
---
🔹 4. Error Handling
Haan, @function_tool ke andar error wrapping hoti hai (tool crash se poora agent crash na ho).
Lekin agar model hi missing hai, to wo runtime error dega (jaise "Model must be provided for tool execution" type).
---
✅ So aap bilkul theek keh rahe ho:
OpenAI models: default model pick ho jata hai → error nahi aata.
Gemini (ya non-OpenAI models): agar model explicitly pass nahi kiya, to error ayega.
[9/24, 3:47 PM] Quratulain: Q1. Your financial trading agent system processes real-time market data… Which exception handling strategy maintains trading capability during infrastructure stress?
Answer: Implement timeout-based tool selection with fallback chains, graceful degradation to cached/stale data with age indicators.
Q2. What happens if you pass a dataclass PurchaseInfo as output_type to an agent?
Answer: The SDK auto-generates a strict JSON schema and converts the final JSON into a PurchaseInfo instance.
Q3. You want your target agent to only receive the last 2 messages from history when a handoff occurs. Which handoff() parameter helps with that?
Answer: input_filter.
Q4. When using low temperature (0.3), moderate top_k (50), and high top_p (0.95), what output is most likely?
Answer: Creative and varied, but still coherent.
Q5. When you call the Agent constructor in the OpenAI Agents Python SDK, which parameter is required?
Answer: model and model_settings.
Q6. What is the purpose of the resolve() method within ModelSettings?
Answer: Combines default settings with overrides and returns a new settings instance.
Q7. By default, what OpenAI API does the Agents SDK use?
Answer: Responses API.
Q8. Orchestrator agent with 5 specialists: one translation agent fails. What happens?
Answer: The orchestrator receives the exception as tool output, can handle it in its reasoning, and continues with other specialists.
Q9. When is an input guardrail function logically applied?
Answer: Before the agent processes the user’s input.
Q10. Which return type does Runner.run_streamed(...) provide?
Answer: RunResultStreaming.
Q11. Which scenario best fits the use of Runner.run_streamed()?
Answer: You need live, partial output updates as the agent processes input, like typing a chat response in real time.
Q12. Only the first agent’s input guardrails are executed; downstream agents in a multi-agent chain do not re-run input guardrails.
Answer: True.
Q13. Banking chatbot: ensure transaction request amount is valid before processing. Which scenario best demonstrates input guardrail?
Answer: Validating that the requested transfer amount is a valid positive integer and below the allowed daily maximum before the agent attempts the transaction.
Q14. You want two separate Runner.run() calls to be part of the same trace session named "JokeWorkflow". How?
Answer: Wrap both Runner.run(...) invocations inside a with trace("JokeWorkflow"): block.
Q15. Financial assistant handling sensitive data — what should system message include?
Answer: A careful persona with explicit safety instructions (e.g., “You are a secure financial assistant. Never expose account numbers. Always confirm actions through the designated secure API or tool.”).
Q16. Practical difference between Runner.run() and Runner.run_sync()?
Answer: run is async and must be awaited, whereas run_sync blocks execution and should only be used when no event loop is running.
Q17. Multi-agent supply chain assistant: how to use handoffs?
Answer: When InventoryAgent detects a shortage, it uses a handoff to transfer control and context to OrderAgent.
Q18. Best practice for exposing a synchronous Python function in an async-first agent?
Answer: Wrap inside an async def using await asyncio.to_thread(...), then decorate the wrapper with @function_tool.
Q19. Primary reason to use @pydantic.dataclasses.dataclass over BaseModel?
Answer: It adds validation on top of standard dataclasses while preserving familiar dataclass behavior.
Q20. What happens when a guardrail tripwire is triggered?
Answer: A GuardrailTripwireTriggered exception is raised, stopping agent execution.
Q21. System message for Chain of Thought prompting?
Answer: Please think step-by-step, show your reasoning, then give the final answer.
Q22. Valid item in the tools list when initializing an agent?
Answer: A FunctionTool object created via @function_tool.
Q23. Which exception is raised when LLM output fails to match declared schema?
Answer: InvalidSchemaError.
Q24. Relationship between Traces and Spans?
Answer: A Trace is a sequence of Spans, where each Span logs events like tool calls, LLM generations, or handoffs.
Q25. Why is Pydantic’s use of Python type hints advantageous?
Answer: They allow seamless validation, integrate with IDEs and static type-checkers like MyPy or Pyright.
Q26. The OpenAI Agents SDK is "Python-first" — what does it mean?
Answer: It requires Python syntax to define agents, tools, and orchestration—with no new DSL.
Q27. Agent greeting user by name dynamically — correct use of instructions?
Answer: Defining a function greet(ctx, agent) -> str and passing it to instructions.
Q28. Effect of high temperature (1.2), low top_k (5), low top_p (0.3)?
Answer: Output will be highly unpredictable and full of odd word choices.
Q29. If you create an Agent without specifying a model, which is used by default?
Answer: gpt-4.1.
Q30. Primary purpose of RunHooks?
Answer: To provide callbacks that fire during any agent run across handoffs.
Q31. Two API tools confuse LLM — fundamental issue?
Answer: Tools are too similar; LLM can’t distinguish without distinct names and schemas.
Q32. If agent exceeds allowed number of turns, which exception is raised?
Answer: MaxTurnsExceeded.
Q33. To log when agent starts/finishes using a tool, where attach AgentHooks?
Answer: Assign custom AgentHooks to the hooks attribute of the Agent before running it.
Q34. Which attributes control final LLM output validation and parsing?
Answer: output_type, agent_output_schema, output_parser.
Q35. If you set output_type=Pydantic model without specifying strict — what happens?
Answer: True (SDK generates strict JSON schema).
Q36. Statement about @function_tool correct?
Answer: You must use @function_tool on every function that an agent can access as a tool.
Q37. What happens when tool raises ValueError in risky_operation?
Answer: The agent receives the error message as tool output and can retry based on its instructions.
Q38. How configure instructions dynamically based on premium user status?
Answer: Provide the function premium_instructions directly to instructions argument.
Q39. Weather agent test with max_turns=1 (“Hello, what can you do?”). Output?
Answer: The agent responds directly without tools: “I’m a weather assistant! … requiring only 1 LLM call.”
Q40. Markdown: clickable image with tooltip — correct syntax?
Answer:
Q41. Trigger logging whenever handoff to AuditAgent occurs — correct setup?
Answer: handoffs=[handoff(agent=AuditAgent, on_handoff=log_callback)].
Q42. Weather agent with max_turns=1 (“What is the weather in Karachi?”). Output?
Answer: The agent raises a MaxTurnsException and fails (needs 2 calls: analyze + respond).
Q43. Support agent includes current date and username dynamically — correct config?
Answer: Pass a function like def dynamic_instr(ctx, agent): return f"Date: {ctx.context.current_date}, User: {ctx.context.name}" as instructions.
Q44. Markdown numbered list (10,11,13,20) — rendered output?
Answer: 11, 12, 13 (renumbered sequentially).
Q45. Financial analysis tool: better way to handle mixed success/failure results?
Answer: Use a structured result format with success/failure indicators and separate error details.
Q46. Correct setup for dynamic instructions using type hints with ChatCtx?
Answer: def dyn(ctx: RunContextWrapper[ChatCtx], ag: Agent): return f"Name: {ctx.context.name}" then pass as instructions.
Q47. Instructions require tools, but model_settings has tool_choice="none". What happens?
Answer: tool_choice="none" takes precedence; the agent cannot use tools and responds with training data only.
Q48. Weather agent with stop_on_first_tool and max_turns=1 (“What is the weather in Karachi?”). Output?
Answer: The agent raises a MaxTurnsException and fails (needs 2 LLM calls).
[9/25, 6:03 PM] Quratulain: 🧑💻 Project: Abdullah’s Personal AI Bot on WhatsApp
🎯 Goal
You are building your own personal AI bot, integrated with WhatsApp.
This bot will know your context (your name, interests, preferences, past interactions, etc.).
You can chat with it like a friend or assistant on WhatsApp.
It will remember things about you and respond intelligently (not just like ChatGPT, but customized only for you).
🔑 Core Components of the Project
Context Memory (Personal Brain)
You’ve already started this using Pydantic models like AbdullahContext.
This stores:
Your name, age, gender, location
Your interests (AI, ML, etc.)
Your past activities (like gym, movies)
Your preferences (food, habits, likes/dislikes)
Even your social media posts + sentiment
This makes the bot personalized.
Agents (Your Assistants)
You’ll build AI agents (like workers) that handle different tasks. Example:
Triage Agent → Knows your preferences & context, answers personal questions.
Social Agent → Analyzes your social posts and gives insights.
Future Agents (optional) → Gym coach agent, Study planner agent, Career advisor, etc.
These agents can also handoff between each other (e.g., Triage agent can call Social agent if needed).
WhatsApp Integration (Your Chat Interface)
Instead of opening a website or app, you’ll talk to your bot directly on WhatsApp.
Using WhatsApp Business API (via Meta developers platform):
You’ll get a sandbox number (a test WhatsApp number).
You’ll get an Access Token (API Key).
Using Python, you can send & receive messages through that number.
Example:
You send: “What are my interests?”
Bot replies: “You’re mostly interested in AI, Machine Learning, and Data Science.”
Backend (Python Project)
This is the engine of your bot.
Technologies:
Python (main language)
Async (for handling messages)
Agents system (custom built with context + instructions)
Flask/FastAPI (to connect WhatsApp webhook → your bot)
Flow:
WhatsApp → sends message → webhook → your Python server
Python server → calls your Agent with AbdullahContext
Agent → generates response
Response → sent back to WhatsApp
🔮 What the Bot Will Be Able to Do
Answer Personal Questions
“What are my interests?”
→ “You like AI, Machine Learning, and Data Science.”
Remember Past Conversations
“Did I go to the gym this week?”
→ “Yes, you mentioned going on Monday.”
Social Media Reflection
“How’s my posting mood recently?”
→ “Mostly positive, except one negative post last week.”
Act Like a Personal Assistant
“Remind me to study tomorrow.”
→ “Got it! I’ll remind you at 10am tomorrow.”
Future Expansion
Connect it with Google Calendar
Add a study planner
Track gym progress
Daily motivation messages