Repository navigation
Expand file tree
/
Copy pathworkflows.py
More file actions
59 lines (47 loc) · 2.26 KB
/
Copy pathworkflows.py
File metadata and controls
59 lines (47 loc) · 2.26 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
"""ResearchWorkflow: search several angles of a question at once, read the best pages, return them with sources.
Durable: if the worker stops between steps, the workflow resumes where it was, and a finished
search or read is never paid again.
"""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
with workflow.unsafe.imports_passed_through():
from activities import Page, ReadInput, SearchInput, Source, read_pages, search
RETRY = RetryPolicy(initial_interval=timedelta(seconds=2), backoff_coefficient=2.0, maximum_attempts=5)
@dataclass
class ResearchInput:
question: str
queries: list[str] = field(default_factory=list) # angles to search; the question alone when empty
max_pages: int = 5
@dataclass
class ResearchResult:
question: str
sources: list[Source] = field(default_factory=list)
pages: list[Page] = field(default_factory=list)
searches: int = 0
cost_usd: float = 0.0
@workflow.defn
class ResearchWorkflow:
@workflow.run
async def run(self, request: ResearchInput) -> ResearchResult:
queries = list(dict.fromkeys(q.strip() for q in (request.queries or [request.question]) if q.strip()))
found = await asyncio.gather(*(
workflow.execute_activity(search, SearchInput(q), start_to_close_timeout=timedelta(seconds=60), retry_policy=RETRY)
for q in queries
))
cost = sum(f.price_usd for f in found)
sources: dict[str, Source] = {}
for rank in range(10): # interleave the angles, best of each first
for result in found:
if rank < len(result.sources):
sources.setdefault(result.sources[rank].url, result.sources[rank])
urls = list(sources)[: max(0, min(request.max_pages, 20))]
pages: list[Page] = []
if urls:
read = await workflow.execute_activity(
read_pages, ReadInput(urls, request.question), start_to_close_timeout=timedelta(seconds=90), retry_policy=RETRY)
pages, cost = read.pages, cost + read.price_usd
return ResearchResult(request.question, list(sources.values()), pages, len(queries), round(cost, 6))