Package: azure-communication-jobrouter
Azure Communication JobRouter Package client library for PythonThis package contains a Python SDK for Azure Communication Services for JobRouter.
Read more about Azure Communication ServiceshereSource code|Package (Pypi)|Product documentationDisclaimerAzure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer tohttps://github.com/Azure/azure-sdk-for-python/issues/20691Getting startedPrerequisitesYou need anAzure subscriptionand aCommunication Service Resourceto use this package.Python 3.7 or later is required to use this package. For more details, please read our page onAzure SDK for Python version support policy.To create a new Communication Service, you can use theAzure Portal, theAzure PowerShellInstall the packageInstall the Azure Communication JobRouter client library for Python withpip:pipinstallazure-communication-jobrouterKey conceptsJobA Job represents the unit of work, which needs to be routed to an available Worker.
A real-world example of this may be an incoming call or chat in the context of a call center.WorkerA Worker represents the supply available to handle a Job. Each worker registers with or more queues to receive jobs.
A real-world example of this may be an agent working in a call center.QueueA Queue represents an ordered list of jobs waiting to be served by a worker.  Workers will register with a queue to receive work from it.
A real-world example of this may be a call queue in a call center.ChannelA Channel represents a grouping of jobs by some type.  When a worker registers to receive work, they must also specify for which channels they can handle work, and how much of each can they handle concurrently.
A real-world example of this may bevoice callsorchatsin a call center.OfferAn Offer is extended by JobRouter to a worker to handle a particular job when it determines a match, this notification is normally delivered viaEventGrid.  The worker can either accept or decline the offer using th JobRouter API, or it will expire according to the time to live configured on the distribution policy.
A real-world example of this may be the ringing of an agent in a call center.Distribution PolicyA Distribution Policy represents a configuration set that governs how jobs in a queue are distributed to workers registered with that queue.
This configuration includes how long an Offer is valid before it expires and the distribution mode, which define the order in which workers are picked when there are multiple available.Distribution ModeThe 3 types of modes areRound Robin: Workers are ordered byIdand the next worker after the previous one that got an offer is picked.Longest Idle: The worker that has not been working on a job for the longest.Best Worker: You can specify an expression to compare 2 workers to determine which one to pick.LabelsYou can attach labels to workers, jobs and queues.  These are key value pairs that can be ofstring,numberorbooleandata types.
A real-world example of this may be the skill level of a particular worker or the team or geographic location.Label SelectorsLabel selectors can be attached to a job in order to target a subset of workers serving the queue.
A real-world example of this may be a condition on an incoming call that the agent must have a minimum level of knowledge of a particular product.Classification policyA classification policy can be used to dynamically select a queue, determine job priority and attach worker label selectors to a job by leveraging a rules engine.Exception policyAn exception policy controls the behavior of a Job based on a trigger and executes a desired action. The exception policy is attached to a Queue so it can control the behavior of Jobs in the Queue.ExamplesClient InitializationTo initialize the SMS Client, the connection string can be used to instantiate.
Alternatively, you can also use Active Directory authentication using DefaultAzureCredential.fromazure.communication.jobrouterimport(JobRouterClient,JobRouterAdministrationClient)connection_string="endpoint=ENDPOINT;accessKey=KEY"router_client=JobRouterClient.from_connection_string(conn_str=connection_string)router_admin_client=JobRouterAdministrationClient.from_connection_string(conn_str=connection_string)Distribution PolicyBefore we can create a Queue, we need a Distribution Policy.fromazure.communication.jobrouter.modelsimport(LongestIdleMode,DistributionPolicy)distribution_policy:DistributionPolicy=DistributionPolicy(offer_expires_after_seconds=24*60*60,mode=LongestIdleMode(min_concurrent_offers=1,max_concurrent_offers=1))distribution_policy:DistributionPolicy=router_admin_client.upsert_distribution_policy("distribution-policy-1",distribution_policy)QueueNext, we can create the queue.fromazure.communication.jobrouter.modelsimport(RouterQueue)queue:RouterQueue=RouterQueue(distribution_policy_id="distribution-policy-1")queue:RouterQueue=router_admin_client.upsert_queue("queue-1",queue)JobNow, we can submit a job directly to that queue, with a worker selector the requires the worker to have the labelSome-Skillgreater than 10.fromazure.communication.jobrouter.modelsimport(RouterJob,RouterWorkerSelector,LabelOperator)router_job:RouterJob=RouterJob(channel_id="my-channel",queue_id="queue-1",channel_reference="12345",priority=1,requested_worker_selectors=[RouterWorkerSelector(key="Some-Skill",label_operator=LabelOperator.EQUAL,value=10)])job:RouterJob=router_client.upsert_job("jobId-1",router_job)WorkerNow, we register a worker to receive work from that queue, with a label ofSome-Skillequal to 11.fromazure.communication.jobrouter.modelsimport(RouterWorker,RouterChannel)router_worker:RouterWorker=RouterWorker(capacity=1,queues=["queue-1"],labels={"Some-Skill":11},channels=[RouterChannel(channel_id="my-channel",capacity_cost_per_job=1)],available_for_offers=True)worker=router_client.upsert_worker("worker-1",router_worker)OfferWe should get aRouterWorkerOfferIssuedfrom ourEventGrid subscription.There are several different Azure services that act as aevent handler.
For this scenario, we are going to assume Webhooks for event delivery.Learn more about Webhook event deliveryOnce events are delivered to the event handler, we can deserialize the JSON payload into a list of events.# Parse the JSON payload into a list of eventsfromazure.eventgridimportEventGridEventimportjson## deserialize payload into a list of typed Eventsevents=[EventGridEvent.from_json(json.loads(msg))formsginpayload]offer_id=""foreventinevents:ifevent.event_type=="Microsoft.Communication.RouterWorkerOfferIssued":offer_id=event.data.offer_idelse:continueHowever, we could also wait a few seconds and then query the worker directly against the JobRouter API to see if an offer was issued to it.fromazure.communication.jobrouter.modelsimport(RouterWorker,)router_worker:RouterWorker=router_client.get_worker(worker_id="worker-1")forofferinrouter_worker.offers:print(f"Worker{router_worker.id}has an active offer for job{offer.job_id}")Accept an offerOnce a worker receives an offer, it can take two possible actions: accept or decline. We are going to accept the offer.fromazure.communication.jobrouter.modelsimport(RouterJobOffer,AcceptJobOfferResult,RouterJobStatus)# fetching the offer idjob_offer:RouterJobOffer=[offerforofferinrouter_worker.offersifoffer.job_id=="jobId-1"][0]offer_id=job_offer.offer_id# accepting the offer sent to `worker-1`accept_job_offer_result:AcceptJobOfferResult=router_client.accept_job_offer(worker_id="worker-1",offer_id=offer_id)print(f"Offer:{job_offer.offer_id}sent to worker:{router_worker.id}has been accepted")print(f"Job has been assigned to worker:{router_worker.id}with assignment:{accept_job_offer_result.assignment_id}")# verify job assignment is populated when querying jobupdated_job=router_client.get_job(job_id="jobId-1")print(f"Job assignment has been successful:{updated_job.job_status==RouterJobStatus.Assignedandaccept_job_offer_result.assignment_idinupdated_job.assignments}")Completing a jobOnce the worker is done with the job, the worker has to mark the job ascompleted.importdatetimefromazure.communication.jobrouter.modelsimport(CompleteJobOptions)complete_job_result=router_client.complete_job("jobId-1",accept_job_offer_result.assignment_id,CompleteJobOptions(note=f"Job has been completed by{router_worker.id}at{datetime.datetime.utcnow()}"))print(f"Job has been successfully completed.")Closing a jobAfter a job has been completed, the worker can perform wrap up actions to the job before closing the job and finally releasing its capacity to accept more incoming jobsfromazure.communication.jobrouter.modelsimport(RouterJob,RouterJobStatus,CloseJobOptions,)close_job_result=router_client.close_job("jobId-1",accept_job_offer_result.assignment_id,CloseJobOptions(note=f"Job has been closed by{router_worker.id}at{datetime.datetime.utcnow()}"))print(f"Job has been successfully closed.")update_job:RouterJob=router_client.get_job(job_id="jobId-1")print(f"Updated job status:{update_job.job_status==RouterJobStatus.CLOSED}")importtimefromdatetimeimportdatetime,timedeltafromazure.communication.jobrouter.modelsimport(RouterJob,RouterJobStatus,CloseJobOptions,)close_job_in_future_result=router_client.close_job("jobId-1",accept_job_offer_result.assignment_id,CloseJobOptions(note=f"Job has been closed by{router_worker.id}at{datetime.utcnow()}",close_at=datetime.utcnow()+timedelta(seconds=2)))print(f"Job has been marked to close")time.sleep(secs=2)update_job:RouterJob=router_client.get_job(job_id="jobId-1")print(f"Updated job status:{update_job.job_status==RouterJobStatus.CLOSED}")TroubleshootingRunning into issues? This section should contain details as to what to do there.Next stepsRead more about Router in Azure Communication ServicesMore sample codePlease take a look at thesamplesdirectory for detailed examples of how to use this library.Provide FeedbackIf you encounter any bugs or have suggestions, please file an issue in theIssuessection of the projectContributingThis project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visitcla.microsoft.com.This project has adopted theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.