Skip to content

Commit 0d4f97a

Browse files
test: running code snippets from docstring in CI (#11103)
Co-authored-by: Stefano Fiorucci <stefanofiorucci@gmail.com>
1 parent 6fe0c15 commit 0d4f97a

6 files changed

Lines changed: 45 additions & 35 deletions

File tree

haystack/components/audio/whisper_local.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,16 @@ class LocalWhisperTranscriber:
4040
[GitHub repository](https://github.com/openai/whisper).
4141
4242
### Usage example
43-
<!-- test-ignore -->
43+
4444
```python
4545
from haystack.components.audio import LocalWhisperTranscriber
4646
4747
whisper = LocalWhisperTranscriber(model="small")
4848
transcription = whisper.run(sources=["test/test_files/audio/answer.wav"])
49+
print(transcription)
50+
51+
# >> {'documents': [Document(id=dae7051417caaf19304a4ef2ec845e981abe1efd4c8e6ee7ffb25867f165c411,
52+
# >> content: ' Answer.', meta: {'audio_file': PosixPath('test/test_files/audio/answer.wav'), 'language': 'en'})]}
4953
```
5054
"""
5155

haystack/components/converters/file_to_file_content.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,13 @@ class FileToFileContent:
2727
from haystack.components.converters import FileToFileContent
2828
2929
converter = FileToFileContent()
30-
31-
sources = ["document.pdf", "video.mp4"]
32-
30+
sources = ["test/test_files/pdf/react_paper.pdf", "test/test_files/images/haystack-logo.png"]
3331
file_contents = converter.run(sources=sources)["file_contents"]
34-
print(file_contents)
3532
36-
# [FileContent(base64_data='...',
37-
# mime_type='application/pdf',
38-
# filename='document.pdf',
39-
# extra={}),
40-
# ...]
33+
print(file_contents)
34+
# >> [FileContent(base64_data='...', mime_type='application/pdf', filename='react_paper.pdf', extra={}),
35+
# >> FileContent(base64_data='...', mime_type='image/png', filename='haystack-logo.png', extra={})
36+
# >>]
4137
```
4238
"""
4339

haystack/components/converters/image/document_to_image.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,31 +34,34 @@ class DocumentToImageContent:
3434
- For PDF files, a `page_number` key specifying which page to extract
3535
3636
### Usage example
37-
<!-- test-ignore -->
37+
3838
```python
3939
from haystack import Document
4040
from haystack.components.converters.image.document_to_image import DocumentToImageContent
4141
4242
converter = DocumentToImageContent(
4343
file_path_meta_field="file_path",
44-
root_path="/data/files",
44+
root_path="test/test_files",
4545
detail="high",
4646
size=(800, 600)
4747
)
4848
4949
documents = [
50-
Document(content="Optional description of image.jpg", meta={"file_path": "image.jpg"}),
51-
Document(content="Text content of page 1 of doc.pdf", meta={"file_path": "doc.pdf", "page_number": 1})
50+
Document(content="Optional description of apple.jpg", meta={"file_path": "images/apple.jpg"}),
51+
Document(
52+
content="Optional description of sample_pdf_1.pdf",
53+
meta={"file_path": "pdf/sample_pdf_1.pdf", "page_number": 1}
54+
)
5255
]
5356
5457
result = converter.run(documents)
5558
image_contents = result["image_contents"]
5659
# [ImageContent(
57-
# base64_image='/9j/4A...', mime_type='image/jpeg', detail='high', meta={'file_path': 'image.jpg'}
60+
# base64_image='/9j/4A...', mime_type='image/jpeg', detail='high', meta={'file_path': 'images/apple.jpg'}
5861
# ),
5962
# ImageContent(
6063
# base64_image='/9j/4A...', mime_type='image/jpeg', detail='high',
61-
# meta={'page_number': 1, 'file_path': 'doc.pdf'}
64+
# meta={'file_path': 'pdf/sample_pdf_1.pdf', 'page_number': 1})
6265
# )]
6366
```
6467
"""

haystack/components/extractors/named_entity_extractor.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ class NamedEntityExtractor:
9090
in the documents.
9191
9292
Usage example:
93-
<!-- test-ignore -->
93+
9494
```python
9595
from haystack import Document
9696
from haystack.components.extractors.named_entity_extractor import NamedEntityExtractor
@@ -103,6 +103,10 @@ class NamedEntityExtractor:
103103
results = extractor.run(documents=documents)["documents"]
104104
annotations = [NamedEntityExtractor.get_stored_annotations(doc) for doc in results]
105105
print(annotations)
106+
# >> [[NamedEntityAnnotation(entity='PER', start=4, end=10, score=np.float32(0.99054915))],
107+
# >> [NamedEntityAnnotation(entity='PER', start=11, end=16, score=np.float32(0.99641764)),
108+
# >> NamedEntityAnnotation(entity='LOC', start=31, end=39, score=np.float32(0.996198)),
109+
# >> NamedEntityAnnotation(entity='LOC', start=41, end=51, score=np.float32(0.9990196))]]
106110
```
107111
"""
108112

haystack/components/generators/azure.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,25 +28,23 @@ class AzureOpenAIGenerator(OpenAIGenerator):
2828
the component or when you run it. Any parameter that works with
2929
`openai.ChatCompletion.create` will work here too.
3030
31-
3231
For details on OpenAI API parameters, see
3332
[OpenAI documentation](https://platform.openai.com/docs/api-reference/chat).
3433
35-
3634
### Usage example
3735
<!-- test-ignore -->
3836
```python
3937
from haystack.components.generators import AzureOpenAIGenerator
4038
from haystack.utils import Secret
39+
4140
client = AzureOpenAIGenerator(
42-
azure_endpoint="<Your Azure endpoint e.g. `https://your-company.azure.openai.com/>",
43-
api_key=Secret.from_token("<your-api-key>"),
44-
azure_deployment="<this is a model name, e.g. gpt-4.1-mini>")
41+
azure_endpoint=Secret.from_env_var("AZURE_OPENAI_ENDPOINT").resolve_value(),
42+
api_key=Secret.from_env_var("AZURE_OPENAI_API_KEY"),
43+
azure_deployment="gpt-4.1-mini")
44+
4545
response = client.run("What's Natural Language Processing? Be brief.")
46-
print(response)
47-
```
4846
49-
```
47+
print(response)
5048
# >> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
5149
# >> the interaction between computers and human language. It involves enabling computers to understand, interpret,
5250
# >> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model':

haystack/components/generators/chat/hugging_face_api.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -264,27 +264,33 @@ class HuggingFaceAPIChatGenerator:
264264
### Usage examples
265265
266266
#### With the serverless inference API (Inference Providers) - free tier available
267-
<!-- test-ignore -->
267+
268268
```python
269269
from haystack.components.generators.chat import HuggingFaceAPIChatGenerator
270270
from haystack.dataclasses import ChatMessage
271271
from haystack.utils import Secret
272272
from haystack.utils.hf import HFGenerationAPIType
273273
274274
messages = [ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"),
275-
ChatMessage.from_user("What's Natural Language Processing?")]
275+
ChatMessage.from_user("What's Natural Language Processing? Please be succinct")]
276276
277277
# the api_type can be expressed using the HFGenerationAPIType enum or as a string
278278
api_type = HFGenerationAPIType.SERVERLESS_INFERENCE_API
279279
api_type = "serverless_inference_api" # this is equivalent to the above
280280
281-
generator = HuggingFaceAPIChatGenerator(api_type=api_type,
282-
api_params={"model": "Qwen/Qwen2.5-7B-Instruct",
283-
"provider": "together"},
284-
token=Secret.from_token("<your-api-key>"))
281+
generator = HuggingFaceAPIChatGenerator(
282+
api_type=api_type,
283+
api_params={"model": "Qwen/Qwen2.5-7B-Instruct", "provider": "together"},
284+
token=Secret.from_env_var("HF_API_TOKEN")
285+
)
285286
286287
result = generator.run(messages)
287288
print(result)
289+
# >> {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>,
290+
# >> _content=[TextContent(text='Natural Language Processing (NLP) is a field of AI that focuses on the interaction
291+
# >> between humans and computers using natural language. It enables machines to understand, interpret, and
292+
# >> generate human language.')], _name=None, _meta={'model': 'Qwen/Qwen2.5-7B-Instruct', 'finish_reason':
293+
# >> 'tool_calls', 'index': 0, 'usage': {'prompt_tokens': 33, 'completion_tokens': 39}})]}
288294
```
289295
290296
#### With the serverless inference API (Inference Providers) and text+image input
@@ -296,18 +302,17 @@ class HuggingFaceAPIChatGenerator:
296302
from haystack.utils.hf import HFGenerationAPIType
297303
298304
# Create an image from file path, URL, or base64
299-
image = ImageContent.from_file_path("path/to/your/image.jpg")
305+
image = ImageContent.from_file_path("test/test_files/images/apple.jpg")
300306
301307
# Create a multimodal message with both text and image
302308
messages = [ChatMessage.from_user(content_parts=["Describe this image in detail", image])]
303309
304310
generator = HuggingFaceAPIChatGenerator(
305311
api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API,
306312
api_params={
307-
"model": "Qwen/Qwen2.5-VL-7B-Instruct", # Vision Language Model
308-
"provider": "hyperbolic"
313+
"model": "Qwen/Qwen3.5-9B", "provider": "together" # Vision Language Model
309314
},
310-
token=Secret.from_token("<your-api-key>")
315+
token=Secret.from_env_var("HF_API_TOKEN")
311316
)
312317
313318
result = generator.run(messages)

0 commit comments

Comments
 (0)