Skip to content

Commit 884eec3

Browse files
committed
Fix for async usage of schemas, refs #22
1 parent dc94a98 commit 884eec3

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

llm_anthropic.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -416,8 +416,13 @@ async def execute(self, prompt, stream, response, conversation, key):
416416
async with messages_client.stream(**kwargs) as stream_obj:
417417
if prefill_text:
418418
yield prefill_text
419-
async for text in stream_obj.text_stream:
420-
yield text
419+
async for chunk in stream_obj:
420+
if hasattr(chunk, "delta"):
421+
delta = chunk.delta
422+
if hasattr(delta, "text"):
423+
yield delta.text
424+
elif hasattr(delta, "partial_json"):
425+
yield delta.partial_json
421426
response.response_json = (await stream_obj.get_final_message()).model_dump()
422427
else:
423428
completion = await messages_client.create(**kwargs)

tests/test_anthropic.py

+30-5
Original file line numberDiff line numberDiff line change
@@ -98,16 +98,17 @@ def test_image_prompt():
9898
assert response.token_details is None
9999

100100

101+
class Dog(BaseModel):
102+
name: str
103+
age: int
104+
bio: str
105+
106+
101107
@pytest.mark.vcr
102108
def test_schema_prompt():
103109
model = llm.get_model("claude-3.7-sonnet")
104110
model.key = model.key or ANTHROPIC_API_KEY
105111

106-
class Dog(BaseModel):
107-
name: str
108-
age: int
109-
bio: str
110-
111112
response = model.prompt("Invent a good dog", schema=Dog)
112113
dog = json.loads(response.text())
113114
assert dog == {
@@ -117,6 +118,30 @@ class Dog(BaseModel):
117118
}
118119

119120

121+
@pytest.mark.vcr
122+
@pytest.mark.asyncio
123+
async def test_schema_prompt_async():
124+
model = llm.get_async_model("claude-3.7-sonnet")
125+
model.key = model.key or ANTHROPIC_API_KEY # don't override existing key
126+
response = await model.prompt("Invent a terrific dog", schema=Dog)
127+
dog_json = await response.text()
128+
dog = json.loads(dog_json)
129+
assert dog == {
130+
"name": "Maximus Thunder",
131+
"age": 3,
132+
"bio": (
133+
"Maximus Thunder is an extraordinary golden retriever with a natural "
134+
"talent for search and rescue operations. His keen sense of smell "
135+
"can detect people trapped under debris from over a mile away. When "
136+
"he's not saving lives, Maximus enjoys surfing at the beach and has "
137+
"won three local dog surfing competitions. He's also incredibly "
138+
"gentle with children and regularly visits hospitals as a therapy "
139+
"dog. His favorite treat is peanut butter, and he has a unique howl "
140+
'that sounds remarkably like he\'s saying "hello."'
141+
),
142+
}
143+
144+
120145
@pytest.mark.vcr
121146
def test_prompt_with_prefill_and_stop_sequences():
122147
model = llm.get_model("claude-3.5-haiku")

0 commit comments

Comments
 (0)