“Event loop is closed” with asyncio and replicate api

I have a gui program build in python with pywebview. When clicking on a button a prompt is executed via the replicate api. Everything works well when the button is pressed for the first time. After the function fetching the replicate api is finished I press the button a second time and I get the following error:

UsersbaschAppDataLocalProgramsPythonPython310libasynciobase_events.py”, line 515, in _check_closed
raise RuntimeError(‘Event loop is closed’)
RuntimeError: Event loop is closed

Here are some of the functions involved:

the function when triggered with the button:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>...
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
response = asyncio.run(config.execute_prompt(gui, prompt_text, {parameter.name: parameter.get_value() for parameter in config.parameters.values()}, append_prediction_part))
...
</code>
<code>... asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) response = asyncio.run(config.execute_prompt(gui, prompt_text, {parameter.name: parameter.get_value() for parameter in config.parameters.values()}, append_prediction_part)) ... </code>
...
   asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    response = asyncio.run(config.execute_prompt(gui, prompt_text, {parameter.name: parameter.get_value() for parameter in config.parameters.values()}, append_prediction_part))
...

config.execute_prompt:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> async def execute_prompt(self, gui, prompt, parameters, update_func):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
self.gui = gui
result = await predict(self.model, prompt, parameters, update_func, self.set_prediction)
return result
</code>
<code> async def execute_prompt(self, gui, prompt, parameters, update_func): asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) self.gui = gui result = await predict(self.model, prompt, parameters, update_func, self.set_prediction) return result </code>
    async def execute_prompt(self, gui, prompt, parameters,  update_func):
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        self.gui = gui
        result = await predict(self.model, prompt, parameters, update_func, self.set_prediction)


        return result

predict function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_KEY
input = {}
prompt = deepcopy(prompt)
for key, value in parameters.items():
if value is not None:
input[key] = value
if "pre_prompt" in input:
prompt = input["pre_prompt"] + "nn" + prompt
del input["pre_prompt"]
from pprint import pprint
input["prompt"] = prompt
pprint(input)
#print(input, model, prompt, parameters)
prediction = await replicate.models.predictions.async_create(
model,
input=input
)
set_prediction(prediction)
resp = {
"status": prediction.status
}
previous_output = ""
while resp["status"] != "succeeded" and resp["status"] != "failed":
resp = await prediction._client._async_request(
"GET",
prediction.urls["get"]
)
# _json_to_prediction(resp._client, resp.json())
# print(resp.decod.json())
resp = loads(resp.content.decode("utf-8"))
pprint(resp)
if "output" in resp and resp["output"] is not None:
output = "".join(resp["output"])
update(output[len(previous_output):])
previous_output = output
return resp
</code>
<code> asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_KEY input = {} prompt = deepcopy(prompt) for key, value in parameters.items(): if value is not None: input[key] = value if "pre_prompt" in input: prompt = input["pre_prompt"] + "nn" + prompt del input["pre_prompt"] from pprint import pprint input["prompt"] = prompt pprint(input) #print(input, model, prompt, parameters) prediction = await replicate.models.predictions.async_create( model, input=input ) set_prediction(prediction) resp = { "status": prediction.status } previous_output = "" while resp["status"] != "succeeded" and resp["status"] != "failed": resp = await prediction._client._async_request( "GET", prediction.urls["get"] ) # _json_to_prediction(resp._client, resp.json()) # print(resp.decod.json()) resp = loads(resp.content.decode("utf-8")) pprint(resp) if "output" in resp and resp["output"] is not None: output = "".join(resp["output"]) update(output[len(previous_output):]) previous_output = output return resp </code>
 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_KEY
    input = {}
    prompt = deepcopy(prompt)


    for key, value in parameters.items():
        if value is not None:
            input[key] = value

    if "pre_prompt" in input:
        prompt = input["pre_prompt"] + "nn" + prompt
        del input["pre_prompt"]

    from pprint import pprint

    input["prompt"] = prompt


    pprint(input)
    #print(input, model, prompt, parameters)
    prediction = await replicate.models.predictions.async_create(
        model,
        input=input
    )

    set_prediction(prediction)

    resp = {
        "status": prediction.status
    }
    previous_output = ""

    while resp["status"] != "succeeded" and resp["status"] != "failed":
        resp = await prediction._client._async_request(
            "GET",
            prediction.urls["get"]
        )
        # _json_to_prediction(resp._client, resp.json())
        # print(resp.decod.json())

        resp = loads(resp.content.decode("utf-8"))
        pprint(resp)
        if "output" in resp and resp["output"] is not None:
            output = "".join(resp["output"])

            update(output[len(previous_output):])

            previous_output = output


    return resp

The predict function sends the prompt to the replicate API and then retrieves the output of the llm as it progresses, sending the new parts to the update function, which will write to a div in the pywebview api. The last response is the finished output and will be returned

I am using python 3.10.4, Windows 11 with all recent updates, and replicate api 0.26.0

Am I using asyncio right? What can I do to resolve the issue?

Kind regards
Bastian

I was trying to write an asynchronous request to replicate, which should be triggered by a button. The first button click works as expected, the second one leads to the exception.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật