Skip to content

Commit

Permalink
await model.prompt() now returns AsyncResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Nov 14, 2024
1 parent e677e2c commit cb2f151
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 4 deletions.
5 changes: 3 additions & 2 deletions docs/python-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,17 @@ model = llm.get_async_model("gpt-4o")
You can then run a prompt using `await model.prompt(...)`:

```python
result = await model.prompt(
response = await model.prompt(
"Five surprising names for a pet pelican"
)
print(await response.text())
```
Or use `async for chunk in ...` to stream the response as it is generated:
```python
async for chunk in model.prompt(
"Five surprising names for a pet pelican"
):
print(chunk, end="")
print(chunk, end="", flush=True)
```

## Conversations
Expand Down
2 changes: 2 additions & 0 deletions llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
)
from .models import (
AsyncModel,
AsyncResponse,
Attachment,
Conversation,
Model,
Expand All @@ -31,6 +32,7 @@
"get_model",
"get_key",
"user_dir",
"AsyncResponse",
"Attachment",
"Collection",
"Conversation",
Expand Down
3 changes: 2 additions & 1 deletion llm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@ async def _force(self):
if not self._done:
async for _ in self:
pass
return self

async def text(self) -> str:
await self._force()
Expand All @@ -409,7 +410,7 @@ async def datetime_utc(self) -> str:
return self._start_utcnow.isoformat() if self._start_utcnow else ""

def __await__(self):
return self.text().__await__()
return self._force().__await__()

@classmethod
def fake(
Expand Down
5 changes: 4 additions & 1 deletion tests/test_async.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import llm
import pytest


Expand All @@ -10,5 +11,7 @@ async def test_async_model(async_mock_model):
assert gathered == ["hello world"]
# Not as an iterator
async_mock_model.enqueue(["hello world"])
text = await async_mock_model.prompt("hello")
response = await async_mock_model.prompt("hello")
text = await response.text()
assert text == "hello world"
assert isinstance(response, llm.AsyncResponse)

0 comments on commit cb2f151

Please sign in to comment.