-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathtest_openai.py
More file actions
2277 lines (1991 loc) · 75.7 KB
/
test_openai.py
File metadata and controls
2277 lines (1991 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import os
import sys
import uuid
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, AsyncIterator, Optional, Union, no_type_check
import nexusrpc
import pydantic
import pytest
from agents import (
Agent,
AgentOutputSchemaBase,
CodeInterpreterTool,
FileSearchTool,
GuardrailFunctionOutput,
Handoff,
HostedMCPTool,
ImageGenerationTool,
InputGuardrailTripwireTriggered,
ItemHelpers,
LocalShellTool,
MCPToolApprovalFunctionResult,
MCPToolApprovalRequest,
MessageOutputItem,
Model,
ModelProvider,
ModelResponse,
ModelSettings,
ModelTracing,
OpenAIChatCompletionsModel,
OpenAIResponsesModel,
OutputGuardrailTripwireTriggered,
RunConfig,
RunContextWrapper,
Runner,
SQLiteSession,
Tool,
TResponseInputItem,
Usage,
function_tool,
handoff,
input_guardrail,
output_guardrail,
trace,
)
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
from agents.items import (
HandoffOutputItem,
ToolCallItem,
ToolCallOutputItem,
TResponseOutputItem,
TResponseStreamEvent,
)
from openai import APIStatusError, AsyncOpenAI, BaseModel
from openai.types.responses import (
EasyInputMessageParam,
ResponseCodeInterpreterToolCall,
ResponseFileSearchToolCall,
ResponseFunctionToolCall,
ResponseFunctionToolCallParam,
ResponseFunctionWebSearch,
ResponseInputTextParam,
ResponseOutputMessage,
ResponseOutputText,
)
from openai.types.responses.response_file_search_tool_call import Result
from openai.types.responses.response_function_web_search import ActionSearch
from openai.types.responses.response_input_item_param import Message
from openai.types.responses.response_output_item import (
ImageGenerationCall,
McpApprovalRequest,
McpCall,
)
from openai.types.responses.response_prompt_param import ResponsePromptParam
from pydantic import ConfigDict, Field, TypeAdapter
import temporalio.api.cloud.namespace.v1
from temporalio import activity, workflow
from temporalio.client import Client, WorkflowFailureError, WorkflowHandle
from temporalio.common import RetryPolicy, SearchAttributeValueType
from temporalio.contrib import openai_agents
from temporalio.contrib.openai_agents import (
ModelActivityParameters,
TestModel,
TestModelProvider,
)
from temporalio.contrib.openai_agents._model_parameters import ModelSummaryProvider
from temporalio.contrib.openai_agents._temporal_model_stub import _extract_summary
from temporalio.contrib.pydantic import pydantic_data_converter
from temporalio.exceptions import ApplicationError, CancelledError
from temporalio.testing import WorkflowEnvironment
from tests.contrib.openai_agents.research_agents.research_manager import (
ResearchManager,
)
from tests.helpers import assert_task_fail_eventually, new_worker
from tests.helpers.nexus import create_nexus_endpoint, make_nexus_endpoint_name
class StaticTestModel(TestModel):
__test__ = False
responses: list[ModelResponse] = []
def __init__(
self,
) -> None:
self._responses = iter(self.responses)
super().__init__(lambda: next(self._responses))
class ResponseBuilders:
@staticmethod
def model_response(output: TResponseOutputItem) -> ModelResponse:
return ModelResponse(
output=[output],
usage=Usage(),
response_id=None,
)
@staticmethod
def response_output_message(text: str) -> ResponseOutputMessage:
return ResponseOutputMessage(
id="",
content=[
ResponseOutputText(
text=text,
annotations=[],
type="output_text",
)
],
role="assistant",
status="completed",
type="message",
)
@staticmethod
def tool_call(arguments: str, name: str) -> ModelResponse:
return ResponseBuilders.model_response(
ResponseFunctionToolCall(
arguments=arguments,
call_id="call",
name=name,
type="function_call",
id="id",
status="completed",
)
)
@staticmethod
def output_message(text: str) -> ModelResponse:
return ResponseBuilders.model_response(
ResponseBuilders.response_output_message(text)
)
class TestHelloModel(StaticTestModel):
responses = [ResponseBuilders.output_message("test")]
@workflow.defn
class HelloWorldAgent:
@workflow.run
async def run(self, prompt: str) -> str:
agent = Agent[None](
name="Assistant",
instructions="You only respond in haikus.",
)
result = await Runner.run(starting_agent=agent, input=prompt)
return result.final_output
@pytest.mark.parametrize("use_local_model", [True, False])
async def test_hello_world_agent(client: Client, use_local_model: bool):
if not use_local_model and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("No openai API key")
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=TestModelProvider(TestHelloModel())
if use_local_model
else None,
)
]
client = Client(**new_config)
async with new_worker(client, HelloWorldAgent) as worker:
result = await client.execute_workflow(
HelloWorldAgent.run,
"Tell me about recursion in programming.",
id=f"hello-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=5),
)
if use_local_model:
assert result == "test"
@dataclass
class Weather:
city: str
temperature_range: str
conditions: str
@activity.defn
async def get_weather(city: str) -> Weather:
"""
Get the weather for a given city.
"""
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")
@activity.defn
async def get_weather_country(city: str, country: str) -> Weather:
"""
Get the weather for a given city in a country.
"""
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")
@dataclass
class WeatherInput:
city: str
@activity.defn
async def get_weather_object(input: WeatherInput) -> Weather:
"""
Get the weather for a given city.
"""
return Weather(
city=input.city, temperature_range="14-20C", conditions="Sunny with wind."
)
@activity.defn
async def get_weather_context(ctx: RunContextWrapper[str], city: str) -> Weather:
"""
Get the weather for a given city.
"""
return Weather(city=city, temperature_range="14-20C", conditions=ctx.context)
class ActivityWeatherService:
@activity.defn
async def get_weather_method(self, city: str) -> Weather:
"""
Get the weather for a given city.
"""
return Weather(
city=city, temperature_range="14-20C", conditions="Sunny with wind."
)
@nexusrpc.service
class WeatherService:
get_weather_nexus_operation: nexusrpc.Operation[WeatherInput, Weather]
@nexusrpc.handler.service_handler(service=WeatherService)
class WeatherServiceHandler:
@nexusrpc.handler.sync_operation
async def get_weather_nexus_operation(
self, ctx: nexusrpc.handler.StartOperationContext, input: WeatherInput
) -> Weather:
return Weather(
city=input.city, temperature_range="14-20C", conditions="Sunny with wind."
)
class TestWeatherModel(StaticTestModel):
responses = [
ResponseBuilders.tool_call('{"city":"Tokyo"}', "get_weather"),
ResponseBuilders.tool_call('{"input":{"city":"Tokyo"}}', "get_weather_object"),
ResponseBuilders.tool_call(
'{"city":"Tokyo","country":"Japan"}', "get_weather_country"
),
ResponseBuilders.tool_call('{"city":"Tokyo"}', "get_weather_context"),
ResponseBuilders.tool_call('{"city":"Tokyo"}', "get_weather_method"),
ResponseBuilders.output_message("Test weather result"),
]
class TestNexusWeatherModel(StaticTestModel):
responses = [
ResponseBuilders.tool_call(
'{"input":{"city":"Tokyo"}}', "get_weather_nexus_operation"
),
ResponseBuilders.output_message("Test nexus weather result"),
]
@workflow.defn
class ToolsWorkflow:
@workflow.run
async def run(self, question: str) -> str:
agent = Agent[str](
name="Tools Workflow",
instructions="You are a helpful agent.",
tools=[
openai_agents.workflow.activity_as_tool(
get_weather, start_to_close_timeout=timedelta(seconds=10)
),
openai_agents.workflow.activity_as_tool(
get_weather_object, start_to_close_timeout=timedelta(seconds=10)
),
openai_agents.workflow.activity_as_tool(
get_weather_country, start_to_close_timeout=timedelta(seconds=10)
),
openai_agents.workflow.activity_as_tool(
get_weather_context, start_to_close_timeout=timedelta(seconds=10)
),
openai_agents.workflow.activity_as_tool(
ActivityWeatherService.get_weather_method,
start_to_close_timeout=timedelta(seconds=10),
),
openai_agents.workflow.activity_as_tool(
get_weather_failure,
start_to_close_timeout=timedelta(seconds=10),
),
],
)
result = await Runner.run(
starting_agent=agent, input=question, context="Stormy"
)
return result.final_output
@workflow.defn
class NexusToolsWorkflow:
@workflow.run
async def run(self, question: str) -> str:
agent = Agent[str](
name="Nexus Tools Workflow",
instructions="You are a helpful agent.",
tools=[
openai_agents.workflow.nexus_operation_as_tool(
WeatherService.get_weather_nexus_operation,
service=WeatherService,
endpoint=make_nexus_endpoint_name(workflow.info().task_queue),
schedule_to_close_timeout=timedelta(seconds=10),
),
],
)
result = await Runner.run(
starting_agent=agent, input=question, context="Stormy"
)
return result.final_output
@pytest.mark.parametrize("use_local_model", [True, False])
async def test_tool_workflow(client: Client, use_local_model: bool):
if not use_local_model and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("No openai API key")
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=TestModelProvider(TestWeatherModel())
if use_local_model
else None,
)
]
client = Client(**new_config)
async with new_worker(
client,
ToolsWorkflow,
activities=[
get_weather,
get_weather_object,
get_weather_country,
get_weather_context,
ActivityWeatherService().get_weather_method,
],
) as worker:
workflow_handle = await client.start_workflow(
ToolsWorkflow.run,
"What is the weather in Tokio?",
id=f"tools-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=30),
)
result = await workflow_handle.result()
if use_local_model:
assert result == "Test weather result"
events = []
async for e in workflow_handle.fetch_history_events():
if e.HasField("activity_task_completed_event_attributes"):
events.append(e)
assert len(events) == 11
assert (
"function_call"
in events[0]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Sunny with wind"
in events[1]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"function_call"
in events[2]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Sunny with wind"
in events[3]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"function_call"
in events[4]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Sunny with wind"
in events[5]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"function_call"
in events[6]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Stormy"
in events[7]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"function_call"
in events[8]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Sunny with wind"
in events[9]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Test weather result"
in events[10]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
@activity.defn
async def get_weather_failure(city: str) -> Weather:
"""
Get the weather for a given city.
"""
raise ApplicationError("No weather", non_retryable=True)
class TestWeatherFailureModel(StaticTestModel):
responses = [
ResponseBuilders.tool_call('{"city":"Tokyo"}', "get_weather_failure"),
]
async def test_tool_failure_workflow(client: Client):
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=TestModelProvider(TestWeatherFailureModel()),
)
]
client = Client(**new_config)
async with new_worker(
client,
ToolsWorkflow,
activities=[
get_weather_failure,
],
) as worker:
workflow_handle = await client.start_workflow(
ToolsWorkflow.run,
"What is the weather in Tokio?",
id=f"tools-failure-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=2),
)
with pytest.raises(WorkflowFailureError) as e:
result = await workflow_handle.result()
cause = e.value.cause
assert isinstance(cause, ApplicationError)
assert "Workflow failure exception in Agents Framework" in cause.message
@pytest.mark.parametrize("use_local_model", [True, False])
async def test_nexus_tool_workflow(
client: Client, env: WorkflowEnvironment, use_local_model: bool
):
if not use_local_model and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("No openai API key")
if env.supports_time_skipping:
pytest.skip("Nexus tests don't work with time-skipping server")
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=TestModelProvider(TestNexusWeatherModel())
if use_local_model
else None,
)
]
client = Client(**new_config)
async with new_worker(
client,
NexusToolsWorkflow,
nexus_service_handlers=[WeatherServiceHandler()],
) as worker:
await create_nexus_endpoint(worker.task_queue, client)
workflow_handle = await client.start_workflow(
NexusToolsWorkflow.run,
"What is the weather in Tokio?",
id=f"nexus-tools-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=30),
)
result = await workflow_handle.result()
if use_local_model:
assert result == "Test nexus weather result"
events = []
async for e in workflow_handle.fetch_history_events():
if e.HasField("activity_task_completed_event_attributes") or e.HasField(
"nexus_operation_completed_event_attributes"
):
events.append(e)
assert len(events) == 3
assert (
"function_call"
in events[0]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Sunny with wind"
in events[
1
].nexus_operation_completed_event_attributes.result.data.decode()
)
assert (
"Test nexus weather result"
in events[2]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
@no_type_check
class TestResearchModel(StaticTestModel):
responses = [
ResponseBuilders.output_message(
'{"searches":[{"query":"best Caribbean surfing spots April","reason":"Identify locations with optimal surfing conditions in the Caribbean during April."},{"query":"top Caribbean islands for hiking April","reason":"Find Caribbean islands with excellent hiking opportunities that are ideal in April."},{"query":"Caribbean water sports destinations April","reason":"Locate Caribbean destinations offering a variety of water sports activities in April."},{"query":"surfing conditions Caribbean April","reason":"Understand the surfing conditions and which islands are suitable for surfing in April."},{"query":"Caribbean adventure travel hiking surfing","reason":"Explore adventure travel options that combine hiking and surfing in the Caribbean."},{"query":"best beaches for surfing Caribbean April","reason":"Identify which Caribbean beaches are renowned for surfing in April."},{"query":"Caribbean islands with national parks hiking","reason":"Find islands with national parks or reserves that offer hiking trails."},{"query":"Caribbean weather April surfing conditions","reason":"Research the weather conditions in April affecting surfing in the Caribbean."},{"query":"Caribbean water sports rentals April","reason":"Look for places where water sports equipment can be rented in the Caribbean during April."},{"query":"Caribbean multi-activity vacation packages","reason":"Look for vacation packages that offer a combination of surfing, hiking, and water sports."}]}'
)
]
for i in range(10):
responses.append(
ModelResponse(
output=[
ResponseFunctionWebSearch(
id="",
status="completed",
type="web_search_call",
action=ActionSearch(query="", type="search"),
),
ResponseBuilders.response_output_message("Granada"),
],
usage=Usage(),
response_id=None,
)
)
responses.append(
ResponseBuilders.output_message(
'{"follow_up_questions":[], "markdown_report":"report", "short_summary":"rep"}'
)
)
@workflow.defn
class ResearchWorkflow:
@workflow.run
async def run(self, query: str):
return await ResearchManager().run(query)
@pytest.mark.parametrize("use_local_model", [True, False])
@pytest.mark.timeout(120)
async def test_research_workflow(client: Client, use_local_model: bool):
if not use_local_model and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("No openai API key")
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=120),
schedule_to_close_timeout=timedelta(seconds=120),
),
model_provider=TestModelProvider(TestResearchModel())
if use_local_model
else None,
)
]
client = Client(**new_config)
async with new_worker(
client,
ResearchWorkflow,
) as worker:
workflow_handle = await client.start_workflow(
ResearchWorkflow.run,
"Caribbean vacation spots in April, optimizing for surfing, hiking and water sports",
id=f"research-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=120),
)
result = await workflow_handle.result()
if use_local_model:
assert result == "report"
events = []
async for e in workflow_handle.fetch_history_events():
if e.HasField("activity_task_completed_event_attributes"):
events.append(e)
assert len(events) == 12
assert (
'"type":"output_text"'
in events[0]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
for i in range(1, 11):
assert (
"web_search_call"
in events[i]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
'"type":"output_text"'
in events[11]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
def orchestrator_agent() -> Agent:
spanish_agent = Agent[None](
name="spanish_agent",
instructions="You translate the user's message to Spanish",
handoff_description="An english to spanish translator",
)
french_agent = Agent[None](
name="french_agent",
instructions="You translate the user's message to French",
handoff_description="An english to french translator",
)
italian_agent = Agent[None](
name="italian_agent",
instructions="You translate the user's message to Italian",
handoff_description="An english to italian translator",
)
orchestrator_agent = Agent[None](
name="orchestrator_agent",
instructions=(
"You are a translation agent. You use the tools given to you to translate."
"If asked for multiple translations, you call the relevant tools in order."
"You never translate on your own, you always use the provided tools."
),
tools=[
spanish_agent.as_tool(
tool_name="translate_to_spanish",
tool_description="Translate the user's message to Spanish",
),
french_agent.as_tool(
tool_name="translate_to_french",
tool_description="Translate the user's message to French",
),
italian_agent.as_tool(
tool_name="translate_to_italian",
tool_description="Translate the user's message to Italian",
),
],
)
return orchestrator_agent
def synthesizer_agent() -> Agent:
return Agent(
name="synthesizer_agent",
instructions="You inspect translations, correct them if needed, and produce a final concatenated response.",
)
@workflow.defn
class AgentsAsToolsWorkflow:
@workflow.run
async def run(self, msg: str) -> str:
# Run the entire orchestration in a single trace
with trace("Orchestrator evaluator"):
orchestrator = orchestrator_agent()
synthesizer = synthesizer_agent()
orchestrator_result = await Runner.run(
starting_agent=orchestrator, input=msg
)
for item in orchestrator_result.new_items:
if isinstance(item, MessageOutputItem):
text = ItemHelpers.text_message_output(item)
if text:
print(f" - Translation step: {text}")
synthesizer_result = await Runner.run(
starting_agent=synthesizer, input=orchestrator_result.to_input_list()
)
return synthesizer_result.final_output
class AgentAsToolsModel(StaticTestModel):
responses = [
ResponseBuilders.tool_call('{"input":"I am full"}', "translate_to_spanish"),
ResponseBuilders.output_message("Estoy lleno."),
ResponseBuilders.output_message(
'The translation to Spanish is: "Estoy lleno."'
),
ResponseBuilders.output_message(
'The translation to Spanish is: "Estoy lleno."'
),
]
@pytest.mark.parametrize("use_local_model", [True, False])
async def test_agents_as_tools_workflow(client: Client, use_local_model: bool):
if not use_local_model and not os.environ.get("OPENAI_API_KEY"):
pytest.skip("No openai API key")
new_config = client.config()
new_config["plugins"] = [
openai_agents.OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=TestModelProvider(AgentAsToolsModel())
if use_local_model
else None,
)
]
client = Client(**new_config)
async with new_worker(
client,
AgentsAsToolsWorkflow,
) as worker:
workflow_handle = await client.start_workflow(
AgentsAsToolsWorkflow.run,
"Translate to Spanish: 'I am full'",
id=f"agents-as-tools-workflow-{uuid.uuid4()}",
task_queue=worker.task_queue,
execution_timeout=timedelta(seconds=30),
)
result = await workflow_handle.result()
if use_local_model:
assert result == 'The translation to Spanish is: "Estoy lleno."'
events = []
async for e in workflow_handle.fetch_history_events():
if e.HasField("activity_task_completed_event_attributes"):
events.append(e)
assert len(events) == 4
assert (
"function_call"
in events[0]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"Estoy lleno"
in events[1]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"The translation to Spanish is:"
in events[2]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
assert (
"The translation to Spanish is:"
in events[3]
.activity_task_completed_event_attributes.result.payloads[0]
.data.decode()
)
class AirlineAgentContext(BaseModel):
passenger_name: Optional[str] = None
confirmation_number: Optional[str] = None
seat_number: Optional[str] = None
flight_number: Optional[str] = None
@function_tool(
name_override="faq_lookup_tool",
description_override="Lookup frequently asked questions.",
)
async def faq_lookup_tool(question: str) -> str:
if "bag" in question or "baggage" in question:
return (
"You are allowed to bring one bag on the plane. "
"It must be under 50 pounds and 22 inches x 14 inches x 9 inches."
)
elif "seats" in question or "plane" in question:
return (
"There are 120 seats on the plane. "
"There are 22 business class seats and 98 economy seats. "
"Exit rows are rows 4 and 16. "
"Rows 5-8 are Economy Plus, with extra legroom. "
)
elif "wifi" in question:
return "We have free wifi on the plane, join Airline-Wifi"
return "I'm sorry, I don't know the answer to that question."
@function_tool
async def update_seat(
context: RunContextWrapper[AirlineAgentContext],
confirmation_number: str,
new_seat: str,
) -> str:
# Update the context based on the customer's input
context.context.confirmation_number = confirmation_number
context.context.seat_number = new_seat
# Ensure that the flight number has been set by the incoming handoff
assert context.context.flight_number is not None, "Flight number is required"
return f"Updated seat to {new_seat} for confirmation number {confirmation_number}"
### HOOKS
async def on_seat_booking_handoff(
context: RunContextWrapper[AirlineAgentContext],
) -> None:
flight_number = f"FLT-{workflow.random().randint(100, 999)}"
context.context.flight_number = flight_number
### AGENTS
def init_agents() -> Agent[AirlineAgentContext]:
"""
Initialize the agents for the airline customer service workflow.
:return: triage agent
"""
faq_agent = Agent[AirlineAgentContext](
name="FAQ Agent",
handoff_description="A helpful agent that can answer questions about the airline.",
instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
You are an FAQ agent. If you are speaking to a customer, you probably were transferred to from the triage agent.
Use the following routine to support the customer.
# Routine
1. Identify the last question asked by the customer.
2. Use the faq lookup tool to answer the question. Do not rely on your own knowledge.
3. If you cannot answer the question, transfer back to the triage agent.""",
tools=[faq_lookup_tool],
)
seat_booking_agent = Agent[AirlineAgentContext](
name="Seat Booking Agent",
handoff_description="A helpful agent that can update a seat on a flight.",
instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
You are a seat booking agent. If you are speaking to a customer, you probably were transferred to from the triage agent.
Use the following routine to support the customer.
# Routine
1. Ask for their confirmation number.
2. Ask the customer what their desired seat number is.
3. Use the update seat tool to update the seat on the flight.
If the customer asks a question that is not related to the routine, transfer back to the triage agent. """,
tools=[update_seat],
)
triage_agent = Agent[AirlineAgentContext](
name="Triage Agent",
handoff_description="A triage agent that can delegate a customer's request to the appropriate agent.",
instructions=(
f"{RECOMMENDED_PROMPT_PREFIX} "
"You are a helpful triaging agent. You can use your tools to delegate questions to other appropriate agents."
),
handoffs=[
faq_agent,
handoff(agent=seat_booking_agent, on_handoff=on_seat_booking_handoff),
],
)
faq_agent.handoffs.append(triage_agent)
seat_booking_agent.handoffs.append(triage_agent)
return triage_agent
class ProcessUserMessageInput(BaseModel):
user_input: str
chat_length: int
class CustomerServiceModel(StaticTestModel):
responses = [
ResponseBuilders.output_message("Hi there! How can I assist you today?"),
ResponseBuilders.tool_call("{}", "transfer_to_seat_booking_agent"),
ResponseBuilders.output_message(
"Could you please provide your confirmation number?"
),
ResponseBuilders.output_message(
"Thanks! What seat number would you like to change to?"
),
ResponseBuilders.tool_call(
'{"confirmation_number":"11111","new_seat":"window seat"}', "update_seat"
),
ResponseBuilders.output_message(
"Your seat has been updated to a window seat. If there's anything else you need, feel free to let me know!"
),
]
@workflow.defn
class CustomerServiceWorkflow:
def __init__(self, input_items: list[TResponseInputItem] = []):
self.chat_history: list[str] = []
self.current_agent: Agent[AirlineAgentContext] = init_agents()
self.context = AirlineAgentContext()
self.input_items = input_items
@workflow.run
async def run(self, input_items: list[TResponseInputItem] = []):
await workflow.wait_condition(
lambda: workflow.info().is_continue_as_new_suggested()
and workflow.all_handlers_finished()
)
workflow.continue_as_new(self.input_items)
@workflow.query
def get_chat_history(self) -> list[str]:
return self.chat_history
@workflow.update
async def process_user_message(self, input: ProcessUserMessageInput) -> list[str]:
length = len(self.chat_history)
self.chat_history.append(f"User: {input.user_input}")
with trace("Customer service", group_id=workflow.info().workflow_id):
self.input_items.append({"content": input.user_input, "role": "user"})
result = await Runner.run(
starting_agent=self.current_agent,
input=self.input_items,